Struct broot::task_sync::Dam

source ·
pub struct Dam { /* private fields */ }
Expand description

The dam controls the flow of events. A dam is used in broot to manage long computations and, when the user presses a key, either tell the computation to stop (the computation function checking has_event) or drop the computation.

Implementations§

Examples found in repository?
src/task_sync.rs (line 51)
50
51
52
    pub fn unlimited() -> Self {
        Self::from(channel::never())
    }
More examples
Hide additional examples
src/app/app.rs (line 696)
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
    pub fn run(
        mut self,
        w: &mut W,
        con: &mut AppContext,
        conf: &Conf,
    ) -> Result<Option<Launchable>, ProgramError> {
        #[cfg(feature = "clipboard")]
        {
            // different systems have different clipboard capabilities
            // and it may be useful to know which one we have
            debug!("Clipboard backend: {:?}", terminal_clipboard::get_type());
        }

        // we listen for events in a separate thread so that we can go on listening
        // when a long search is running, and interrupt it if needed
        let event_source = EventSource::new()?;
        let rx_events = event_source.receiver();
        let mut dam = Dam::from(rx_events);
        let skin = AppSkin::new(conf, con.launch_args.color == TriBool::No);
        let mut app_state = AppState {
            stage: Stage::default(),
            root: con.initial_root.clone(),
            other_panel_path: None,
        };

        self.screen.clear_bottom_right_char(w, &skin.focused)?;

        if let Some(raw_sequence) = &con.launch_args.cmd {
            self.tx_seqs
                .send(Sequence::new_local(raw_sequence.to_string()))
                .unwrap();
        }

        #[cfg(unix)]
        let _server = con.launch_args.listen.as_ref()
            .map(|server_name| {
                let shared_root = Arc::new(Mutex::new(app_state.root.clone()));
                let server = crate::net::Server::new(
                    server_name,
                    self.tx_seqs.clone(),
                    Arc::clone(&shared_root),
                );
                self.shared_root = Some(shared_root);
                server
            })
            .transpose()?;

        loop {
            if !self.quitting {
                self.display_panels(w, &skin, &app_state, con)?;
                time!(
                    Info,
                    "pending_tasks",
                    self.do_pending_tasks(w, &skin, &mut dam, &mut app_state, con)?,
                );
            }
            #[allow(unused_mut)]
            match dam.next(&self.rx_seqs) {
                Either::First(Some(event)) => {
                    info!("event: {:?}", &event);
                    let mut handled = false;

                    // app level handling
                    if let Some((x, y)) = event.as_click() {
                        if self.clicked_panel_index(x, y) != self.active_panel_idx {
                            // panel activation click
                            self.active_panel_idx = self.clicked_panel_index(x, y);
                            handled = true;
                        }
                    } else if let Event::Resize(mut width, mut height) = event.event {
                        // I don't know why but Crossterm seems to always report an
                        // understimated size on Windows
                        #[cfg(windows)]
                        {
                            width += 1;
                            height += 1;
                        }
                        self.screen.set_terminal_size(width, height, con);
                        Areas::resize_all(
                            self.panels.as_mut_slice(),
                            self.screen,
                            self.preview_panel.is_some(),
                        );
                        for panel in &mut self.panels {
                            panel.mut_state().refresh(self.screen, con);
                        }
                        handled = true;
                    }

                    // event handled by the panel
                    if !handled {
                        let cmd = self.mut_panel().add_event(w, event, &app_state, con)?;
                        debug!("command after add_event: {:?}", &cmd);
                        self.apply_command(w, cmd, &skin.focused, &mut app_state, con)?;

                    }

                    event_source.unblock(self.quitting);
                }
                Either::First(None) => {
                    // this is how we quit the application,
                    // when the input thread is properly closed
                    break;
                }
                Either::Second(Some(raw_sequence)) => {
                    debug!("got command sequence: {:?}", &raw_sequence);
                    for (input, arg_cmd) in raw_sequence.parse(con)? {
                        self.mut_panel().set_input_content(&input);
                        self.apply_command(w, arg_cmd, &skin.focused, &mut app_state, con)?;
                        if self.quitting {
                            // is that a 100% safe way of quitting ?
                            return Ok(self.launch_at_end.take());
                        } else {
                            self.display_panels(w, &skin, &app_state, con)?;
                            time!(
                                "sequence pending tasks",
                                self.do_pending_tasks(w, &skin, &mut dam, &mut app_state, con)?,
                            );
                        }
                    }
                }
                Either::Second(None) => {
                    warn!("I didn't expect a None to occur here");
                }
            }
        }

        Ok(self.launch_at_end.take())
    }
Examples found in repository?
src/verb/internal_focus.rs (line 47)
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
pub fn new_state_on_path(
    path: PathBuf,
    screen: Screen,
    tree_options: TreeOptions,
    con: &AppContext,
) -> CmdResult {
    let path = path::closest_dir(&path);
    CmdResult::from_optional_state(
        BrowserState::new(path, tree_options, screen, con, &Dam::unlimited()),
        None,
        false,
    )
}

pub fn new_panel_on_path(
    path: PathBuf,
    screen: Screen,
    tree_options: TreeOptions,
    purpose: PanelPurpose,
    con: &AppContext,
    direction: HDir,
) -> CmdResult {
    if purpose.is_preview() {
        let pattern = tree_options.pattern.tree_to_preview();
        CmdResult::NewPanel {
            state: Box::new(PreviewState::new(path, pattern, None, tree_options, con)),
            purpose,
            direction,
        }
    } else {
        let path = path::closest_dir(&path);
        match BrowserState::new(path, tree_options, screen, con, &Dam::unlimited()) {
            Ok(os) => CmdResult::NewPanel {
                state: Box::new(os),
                purpose,
                direction,
            },
            Err(e) => CmdResult::DisplayError(e.to_string()),
        }
    }
}
More examples
Hide additional examples
src/browser/browser_state.rs (line 88)
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
    fn modified(
        &self,
        screen: Screen,
        root: PathBuf,
        options: TreeOptions,
        message: Option<&'static str>,
        in_new_panel: bool,
        con: &AppContext,
    ) -> CmdResult {
        let tree = self.displayed_tree();
        let mut new_state = BrowserState::new(root, options, screen, con, &Dam::unlimited());
        if let Ok(bs) = &mut new_state {
            if tree.selection != 0 {
                bs.displayed_tree_mut().try_select_path(&tree.selected_line().path);
            }
        }
        CmdResult::from_optional_state(
            new_state,
            message,
            in_new_panel,
        )
    }

    pub fn root(&self) -> &Path {
        self.tree.root()
    }

    pub fn page_height(screen: Screen) -> usize {
        screen.height as usize - 2 // br shouldn't be displayed when the screen is smaller
    }

    /// return a reference to the currently displayed tree, which
    /// is the filtered tree if there's one, the base tree if not.
    pub fn displayed_tree(&self) -> &Tree {
        self.filtered_tree.as_ref().unwrap_or(&self.tree)
    }

    /// return a mutable reference to the currently displayed tree, which
    /// is the filtered tree if there's one, the base tree if not.
    pub fn displayed_tree_mut(&mut self) -> &mut Tree {
        self.filtered_tree.as_mut().unwrap_or(&mut self.tree)
    }

    pub fn open_selection_stay_in_broot(
        &mut self,
        screen: Screen,
        con: &AppContext,
        in_new_panel: bool,
        keep_pattern: bool,
    ) -> Result<CmdResult, ProgramError> {
        let tree = self.displayed_tree();
        let line = tree.selected_line();
        let mut target = line.target().to_path_buf();
        if line.is_dir() {
            if tree.selection == 0 {
                // opening the root would be going to where we already are.
                // We go up one level instead
                if let Some(parent) = target.parent() {
                    target = PathBuf::from(parent);
                }
            }
            let dam = Dam::unlimited();
            Ok(CmdResult::from_optional_state(
                BrowserState::new(
                    target,
                    if keep_pattern {
                        tree.options.clone()
                    } else {
                        tree.options.without_pattern()
                    },
                    screen,
                    con,
                    &dam,
                ),
                None,
                in_new_panel,
            ))
        } else {
            match opener::open(&target) {
                Ok(exit_status) => {
                    info!("open returned with exit_status {:?}", exit_status);
                    Ok(CmdResult::Keep)
                }
                Err(e) => Ok(CmdResult::error(format!("{:?}", e))),
            }
        }
    }

    pub fn go_to_parent(
        &mut self,
        screen: Screen,
        con: &AppContext,
        in_new_panel: bool,
    ) -> CmdResult {
        match &self.displayed_tree().selected_line().path.parent() {
            Some(path) => CmdResult::from_optional_state(
                BrowserState::new(
                    path.to_path_buf(),
                    self.displayed_tree().options.without_pattern(),
                    screen,
                    con,
                    &Dam::unlimited(),
                ),
                None,
                in_new_panel,
            ),
            None => CmdResult::error("no parent found"),
        }
    }
src/preview/preview.rs (line 67)
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
    pub fn with_mode(
        path: &Path,
        mode: PreviewMode,
        con: &AppContext,
    ) -> Result<Self, ProgramError> {
        match mode {
            PreviewMode::Hex => {
                Ok(HexView::new(path.to_path_buf()).map(Self::Hex)?)
            }
            PreviewMode::Image => {
                ImageView::new(path).map(Self::Image)
            }
            PreviewMode::Text => {
                Ok(
                    SyntacticView::new(path, InputPattern::none(), &mut Dam::unlimited(), con, false)
                        .transpose()
                        .expect("syntactic view without pattern shouldn't be none")
                        .map(Self::Syntactic)?,
                )
            }
        }
    }
    /// build an image view, unless the file can't be interpreted
    /// as an image, in which case a hex view is used
    pub fn image(path: &Path) -> Self {
        ImageView::new(path)
            .ok()
            .map(Self::Image)
            .unwrap_or_else(|| Self::hex(path))

    }
    /// build a text preview (maybe with syntaxic coloring) if possible,
    /// a hex (binary) view if content isnt't UTF8, a ZeroLen file if there's
    /// no length (it's probably a linux pseudofile) or a IOError when
    /// there's a IO problem
    pub fn unfiltered_text(
        path: &Path,
        con: &AppContext,
    ) -> Self {
        match SyntacticView::new(path, InputPattern::none(), &mut Dam::unlimited(), con, false) {
            Ok(Some(sv)) => Self::Syntactic(sv),
            Err(ProgramError::ZeroLenFile | ProgramError::UnmappableFile) => {
                debug!("zero len or unmappable file - check if system file");
                Self::ZeroLen(ZeroLenFileView::new(path.to_path_buf()))
            }
            Err(ProgramError::SyntectCrashed { details }) => {
                warn!("syntect crashed with message : {details:?}");
                Self::unstyled_text(path, con)
            }
            // not previewable as UTF8 text
            // we'll try reading it as binary
            Err(ProgramError::UnprintableFile) => Self::hex(path),
            _ => Self::hex(path),
        }
    }
    /// build a text preview with no syntax highlighting, if possible
    pub fn unstyled_text(
        path: &Path,
        con: &AppContext,
    ) -> Self {
        match SyntacticView::new(path, InputPattern::none(), &mut Dam::unlimited(), con, true) {
            Ok(Some(sv)) => Self::Syntactic(sv),
            Err(ProgramError::ZeroLenFile | ProgramError::UnmappableFile) => {
                debug!("zero len or unmappable file - check if system file");
                Self::ZeroLen(ZeroLenFileView::new(path.to_path_buf()))
            }
            // not previewable as UTF8 text - we'll try reading it as binary
            Err(ProgramError::UnprintableFile) => Self::hex(path),
            _ => Self::hex(path),
        }
    }
src/tree/tree.rs (line 52)
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
    pub fn refresh(
        &mut self,
        page_height: usize,
        con: &AppContext,
    ) -> Result<(), errors::TreeBuildError> {
        let builder = TreeBuilder::from(
            self.root().to_path_buf(),
            self.options.clone(),
            page_height,
            con,
        )?;
        let mut tree = builder
            .build_tree(
                false, // on refresh we always do a non total search
                &Dam::unlimited(),
            )
            .unwrap(); // should not fail
                       // we save the old selection to try restore it
        let selected_path = self.selected_line().path.to_path_buf();
        mem::swap(&mut self.lines, &mut tree.lines);
        self.scroll = 0;
        if !self.try_select_path(&selected_path) {
            if self.selection >= self.lines.len() {
                self.selection = 0;
            }
        }
        self.make_selection_visible(page_height);
        Ok(())
    }
src/app/app.rs (line 90)
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
    pub fn new(
        con: &AppContext,
    ) -> Result<App, ProgramError> {
        let screen = Screen::new(con)?;
        let panel = Panel::new(
            PanelId::from(0),
            Box::new(
                BrowserState::new(
                    con.initial_root.clone(),
                    con.initial_tree_options.clone(),
                    screen,
                    con,
                    &Dam::unlimited(),
                )?
            ),
            Areas::create(&mut Vec::new(), 0, screen, false),
            con,
        );
        let (tx_seqs, rx_seqs) = unbounded::<Sequence>();
        Ok(App {
            screen,
            active_panel_idx: 0,
            panels: panel.into(),
            quitting: false,
            launch_at_end: None,
            created_panels_count: 1,
            preview_panel: None,
            stage_panel: None,
            shared_root: None,
            tx_seqs,
            rx_seqs,
            drawing_count: 0,
        })
    }

    fn panel_ref_to_idx(&self, panel_ref: PanelReference) -> Option<usize> {
        match panel_ref {
            PanelReference::Active => Some(self.active_panel_idx),
            PanelReference::Leftest => Some(0),
            PanelReference::Rightest => Some(self.panels.len().get() - 1),
            PanelReference::Id(id) => self.panel_id_to_idx(id),
            PanelReference::Preview => self.preview_panel.and_then(|id| self.panel_id_to_idx(id)),
        }
    }

    /// return the current index of the panel with given id
    fn panel_id_to_idx(&self, id: PanelId) -> Option<usize> {
        self.panels.iter().position(|panel| panel.id == id)
    }

    fn state(&self) -> &dyn PanelState {
        self.panels[self.active_panel_idx].state()
    }
    fn mut_state(&mut self) -> &mut dyn PanelState {
        self.panels[self.active_panel_idx].mut_state()
    }
    fn panel(&self) -> &Panel {
        &self.panels[self.active_panel_idx]
    }
    fn mut_panel(&mut self) -> &mut Panel {
        unsafe {
            self.panels
                .as_mut_slice()
                .get_unchecked_mut(self.active_panel_idx)
        }
    }

    /// close the panel if it's not the last one
    ///
    /// Return true when the panel has been removed (ie it wasn't the last one)
    fn close_panel(&mut self, panel_idx: usize) -> bool {
        let active_panel_id = self.panels[self.active_panel_idx].id;
        if let Some(preview_id) = self.preview_panel {
            if self.panels.has_len(2) && self.panels[panel_idx].id != preview_id {
                // we don't want to stay with just the preview
                return false;
            }
        }
        if let Some(stage_id) = self.stage_panel {
            if self.panels.has_len(2) && self.panels[panel_idx].id != stage_id {
                // we don't want to stay with just the stage
                return false;
            }
        }
        if let Ok(removed_panel) = self.panels.remove(panel_idx) {
            if self.preview_panel == Some(removed_panel.id) {
                self.preview_panel = None;
            }
            if self.stage_panel == Some(removed_panel.id) {
                self.stage_panel = None;
            }
            Areas::resize_all(
                self.panels.as_mut_slice(),
                self.screen,
                self.preview_panel.is_some(),
            );
            self.active_panel_idx = self
                .panels
                .iter()
                .position(|p| p.id == active_panel_id)
                .unwrap_or(self.panels.len().get() - 1);
            true
        } else {
            false // there's no other panel to go to
        }
    }

    /// remove the top state of the current panel
    ///
    /// Close the panel too if that was its only state.
    /// Close nothing and return false if there's not
    /// at least two states in the app.
    fn remove_state(&mut self) -> bool {
        self.panels[self.active_panel_idx].remove_state()
            || self.close_panel(self.active_panel_idx)
    }

    /// redraw the whole screen. All drawing
    /// are supposed to happen here, and only here.
    fn display_panels(
        &mut self,
        w: &mut W,
        skin: &AppSkin,
        app_state: &AppState,
        con: &AppContext,
    ) -> Result<(), ProgramError> {
        self.drawing_count += 1;
        for (idx, panel) in self.panels.as_mut_slice().iter_mut().enumerate() {
            let active = idx == self.active_panel_idx;
            let panel_skin = if active { &skin.focused } else { &skin.unfocused };
            let disc = DisplayContext {
                count: self.drawing_count,
                active,
                screen: self.screen,
                panel_skin,
                state_area: panel.areas.state.clone(),
                app_state,
                con,
            };
            time!(
                "display panel",
                panel.display(w, &disc)?,
            );
        }
        kitty::manager().lock().unwrap().erase_images_before(w, self.drawing_count)?;
        w.flush()?;
        Ok(())
    }

    /// if there are exactly two non preview panels, return the selection
    /// in the non focused panel
    fn get_other_panel_path(&self) -> Option<PathBuf> {
        let len = self.panels.len().get();
        if len == 3 {
            if let Some(preview_id) = self.preview_panel {
                for (idx, panel) in self.panels.iter().enumerate() {
                    if self.active_panel_idx != idx && panel.id != preview_id {
                        return panel.state().selected_path()
                            .map(|p| p.to_path_buf());
                    }
                }
            }
            None
        } else if self.panels.len().get() == 2 && self.preview_panel.is_none() {
            let non_focused_panel_idx = if self.active_panel_idx == 0 { 1 } else { 0 };
            self.panels[non_focused_panel_idx].state().selected_path()
                .map(|p| p.to_path_buf())
        } else {
            None
        }
    }

    /// apply a command. Change the states but don't redraw on screen.
    fn apply_command(
        &mut self,
        w: &mut W,
        cmd: Command,
        panel_skin: &PanelSkin,
        app_state: &mut AppState,
        con: &mut AppContext,
    ) -> Result<(), ProgramError> {
        use CmdResult::*;
        let mut error: Option<String> = None;
        let is_input_invocation = cmd.is_verb_invocated_from_input();
        let app_cmd_context = AppCmdContext {
            panel_skin,
            preview_panel: self.preview_panel,
            stage_panel: self.stage_panel,
            screen: self.screen, // it can't change in this function
            con,
        };
        let cmd_result = self.mut_panel().apply_command(w, &cmd, app_state, &app_cmd_context)?;
        debug!("cmd_result: {:?}", &cmd_result);
        match cmd_result {
            ApplyOnPanel { id } => {
                if let Some(idx) = self.panel_id_to_idx(id) {
                    if let DisplayError(txt) = self.panels[idx].apply_command(
                        w, &cmd, app_state, &app_cmd_context
                    )? {
                        // we should probably handle other results
                        // which implies the possibility of a recursion
                        error = Some(txt);
                    } else if is_input_invocation {
                        self.mut_panel().clear_input();
                    }
                } else {
                    warn!("no panel found for ApplyOnPanel");
                }
            }
            ClosePanel { validate_purpose, panel_ref } => {
                if is_input_invocation {
                    self.mut_panel().clear_input_invocation(con);
                }
                let close_idx = self.panel_ref_to_idx(panel_ref)
                    .unwrap_or_else(||
                        // when there's a preview panel, we close it rather than the app
                        if self.panels.len().get()==2 && self.preview_panel.is_some() {
                            1
                        } else {
                            self.active_panel_idx
                        }
                    );
                let mut new_arg = None;
                if validate_purpose {
                    let purpose = &self.panels[close_idx].purpose;
                    if let PanelPurpose::ArgEdition { .. } = purpose {
                        new_arg = self.panels[close_idx]
                            .state()
                            .selected_path()
                            .map(|p| p.to_string_lossy().to_string());
                    }
                }
                if self.close_panel(close_idx) {
                    let screen = self.screen;
                    self.mut_state().refresh(screen, con);
                    if let Some(new_arg) = new_arg {
                        self.mut_panel().set_input_arg(new_arg);
                        let new_input = self.panel().get_input_content();
                        let cmd = Command::from_raw(new_input, false);
                        let app_cmd_context = AppCmdContext {
                            panel_skin,
                            preview_panel: self.preview_panel,
                            stage_panel: self.stage_panel,
                            screen,
                            con,
                        };
                        self.mut_panel().apply_command(w, &cmd, app_state, &app_cmd_context)?;
                    }
                } else {
                    self.quitting = true;
                }
            }
            DisplayError(txt) => {
                error = Some(txt);
            }
            ExecuteSequence { sequence } => {
                self.tx_seqs.send(sequence).unwrap();
            }
            HandleInApp(internal) => {
                debug!("handling internal {internal:?} at app level");
                match internal {
                    Internal::panel_left_no_open | Internal::panel_right_no_open => {
                        let new_active_panel_idx = if internal == Internal::panel_left_no_open {
                            // we're here because the state wants us to either move to the panel
                            // to the left, or close the rightest one
                            if self.active_panel_idx == 0 {
                                self.close_panel(self.panels.len().get()-1);
                                None
                            } else {
                                Some(self.active_panel_idx - 1)
                            }
                        } else { // panel_right
                            // we either move to the right or close the leftest panel
                            if self.active_panel_idx + 1 == self.panels.len().get() {
                                self.close_panel(0);
                                None
                            } else {
                                Some(self.active_panel_idx + 1)
                            }
                        };
                        if let Some(idx) = new_active_panel_idx {
                            if is_input_invocation {
                                self.mut_panel().clear_input();
                            }
                            self.active_panel_idx = idx;
                            let app_cmd_context = AppCmdContext {
                                panel_skin,
                                preview_panel: self.preview_panel,
                                stage_panel: self.stage_panel,
                                screen: self.screen,
                                con,
                            };
                            self.mut_panel().refresh_input_status(app_state, &app_cmd_context);
                        }
                    }
                    Internal::toggle_second_tree => {
                        let panels_count = self.panels.len().get();
                        let trees_count = self.panels.iter()
                            .filter(|p| p.state().get_type() == PanelStateType::Tree)
                            .count();
                        if trees_count < 2 {
                            // we open a tree, closing a (non tree) panel if necessary
                            if panels_count >= con.max_panels_count {
                                for i in (0..panels_count).rev() {
                                    if self.panels[i].state().get_type() != PanelStateType::Tree {
                                        self.close_panel(i);
                                        break;
                                    }
                                }
                            }
                            if let Some(selected_path) = self.state().selected_path() {
                                let dir = closest_dir(selected_path);
                                if let Ok(new_state) = BrowserState::new(
                                    dir,
                                    self.state().tree_options().without_pattern(),
                                    self.screen,
                                    con,
                                    &Dam::unlimited(),
                                ) {
                                    if let Err(s) = self.new_panel(
                                        Box::new(new_state),
                                        PanelPurpose::None,
                                        HDir::Right,
                                        is_input_invocation,
                                        con,
                                    ) {
                                        error = Some(s);
                                    }
                                }
                            }
                        } else {
                            // we close the rightest inactive tree
                            for i in (0..panels_count).rev() {
                                if self.panels[i].state().get_type() == PanelStateType::Tree {
                                    if i == self.active_panel_idx {
                                        continue;
                                    }
                                    self.close_panel(i);
                                    break;
                                }
                            }
                        }
                    }
                    Internal::set_syntax_theme => {
                        let arg = cmd
                            .as_verb_invocation()
                            .and_then(|vi| vi.args.as_ref());
                        match arg {
                            Some(arg) => {
                                match SyntaxTheme::from_str(arg) {
                                    Ok(theme) => {
                                        con.syntax_theme = Some(theme);
                                        self.update_preview(con, true);
                                    }
                                    Err(e) => {
                                        error = Some(e.to_string());
                                    }
                                }
                            }
                            None => {
                                error = Some("no theme provided".to_string());
                            }
                        }
                    }
                    _ => {
                        info!("unhandled propagated internal. cmd={:?}", &cmd);
                    }
                }
            }
            Keep => {
                if is_input_invocation {
                    self.mut_panel().clear_input_invocation(con);
                }
            }
            Launch(launchable) => {
                self.launch_at_end = Some(*launchable);
                self.quitting = true;
            }
            NewPanel {
                state,
                purpose,
                direction,
            } => {
                if let Err(s) = self.new_panel(state, purpose, direction, is_input_invocation, con) {
                    error = Some(s);
                }
            }
            NewState { state, message } => {
                self.mut_panel().clear_input();
                self.mut_panel().push_state(state);
                if let Some(md) = message {
                    self.mut_panel().set_message(md);
                } else {
                    self.mut_panel().refresh_input_status(app_state, &app_cmd_context);
                }
            }
            PopState => {
                if is_input_invocation {
                    self.mut_panel().clear_input();
                }
                if self.remove_state() {
                    self.mut_state().refresh(app_cmd_context.screen, con);
                    self.mut_panel().refresh_input_status(app_state, &app_cmd_context);
                } else if con.quit_on_last_cancel {
                    self.quitting = true;
                }
            }
            PopStateAndReapply => {
                if is_input_invocation {
                    self.mut_panel().clear_input();
                }
                if self.remove_state() {
                    let app_cmd_context = AppCmdContext {
                        panel_skin,
                        preview_panel: self.preview_panel,
                        stage_panel: self.stage_panel,
                        screen: self.screen,
                        con,
                    };
                    self.mut_panel().apply_command(w, &cmd, app_state, &app_cmd_context)?;
                } else if con.quit_on_last_cancel {
                    self.quitting = true;
                }
            }
            Quit => {
                self.quitting = true;
            }
            RefreshState { clear_cache } => {
                if is_input_invocation {
                    self.mut_panel().clear_input_invocation(con);
                }
                if clear_cache {
                    clear_caches();
                }
                app_state.stage.refresh();
                for i in 0..self.panels.len().get() {
                    self.panels[i].mut_state().refresh(self.screen, con);
                }
            }
        }
        if let Some(text) = error {
            self.mut_panel().set_error(text);
        }

        app_state.other_panel_path = self.get_other_panel_path();
        if let Some(path) = self.state().tree_root() {
            app_state.root = path.to_path_buf();
        }


        if let Some(shared_root) = &mut self.shared_root {
            if let Ok(mut root) = shared_root.lock() {
                *root = app_state.root.clone();
            }
        }

        self.update_preview(con, false);

        Ok(())
    }
src/filesystems/filesystems_state.rs (line 515)
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
    fn on_internal(
        &mut self,
        w: &mut W,
        internal_exec: &InternalExecution,
        input_invocation: Option<&VerbInvocation>,
        trigger_type: TriggerType,
        app_state: &mut AppState,
        cc: &CmdContext,
    ) -> Result<CmdResult, ProgramError> {
        let screen = cc.app.screen;
        let con = &cc.app.con;
        use Internal::*;
        Ok(match internal_exec.internal {
            Internal::back => {
                if let Some(f) = self.filtered.take() {
                    if !f.mounts.is_empty() {
                        self.selection_idx = self.mounts.iter()
                            .position(|m| m.info.id == f.mounts[f.selection_idx].info.id)
                            .unwrap(); // all filtered mounts come from self.mounts
                    }
                    CmdResult::Keep
                } else {
                    CmdResult::PopState
                }
            }
            Internal::line_down => {
                self.move_line(internal_exec, input_invocation, 1, true)
            }
            Internal::line_up => {
                self.move_line(internal_exec, input_invocation, -1, true)
            }
            Internal::line_down_no_cycle => {
                self.move_line(internal_exec, input_invocation, 1, false)
            }
            Internal::line_up_no_cycle => {
                self.move_line(internal_exec, input_invocation, -1, false)
            }
            Internal::open_stay => {
                let in_new_panel = input_invocation
                    .map(|inv| inv.bang)
                    .unwrap_or(internal_exec.bang);
                let dam = Dam::unlimited();
                let mut tree_options = self.tree_options();
                tree_options.show_root_fs = true;
                CmdResult::from_optional_state(
                    BrowserState::new(
                        self.no_opt_selected_path().to_path_buf(),
                        tree_options,
                        screen,
                        con,
                        &dam,
                    ),
                    None,
                    in_new_panel,
                )
            }
            Internal::panel_left => {
                let areas = &cc.panel.areas;
                if areas.is_first() && areas.nb_pos < con.max_panels_count {
                    // we ask for the creation of a panel to the left
                    internal_focus::new_panel_on_path(
                        self.no_opt_selected_path().to_path_buf(),
                        screen,
                        self.tree_options(),
                        PanelPurpose::None,
                        con,
                        HDir::Left,
                    )
                } else {
                    // we ask the app to focus the panel to the left
                    CmdResult::HandleInApp(Internal::panel_left_no_open)
                }
            }
            Internal::panel_left_no_open => CmdResult::HandleInApp(Internal::panel_left_no_open),
            Internal::panel_right => {
                let areas = &cc.panel.areas;
                if areas.is_last() && areas.nb_pos < con.max_panels_count {
                    // we ask for the creation of a panel to the right
                    internal_focus::new_panel_on_path(
                        self.no_opt_selected_path().to_path_buf(),
                        screen,
                        self.tree_options(),
                        PanelPurpose::None,
                        con,
                        HDir::Right,
                    )
                } else {
                    // we ask the app to focus the panel to the right
                    CmdResult::HandleInApp(Internal::panel_right_no_open)
                }
            }
            Internal::panel_right_no_open => CmdResult::HandleInApp(Internal::panel_right_no_open),
            Internal::page_down => {
                if !self.try_scroll(ScrollCommand::Pages(1)) {
                    self.selection_idx = self.count() - 1;
                }
                CmdResult::Keep
            }
            Internal::page_up => {
                if !self.try_scroll(ScrollCommand::Pages(-1)) {
                    self.selection_idx = 0;
                }
                CmdResult::Keep
            }
            open_leave => CmdResult::PopStateAndReapply,
            _ => self.on_internal_generic(
                w,
                internal_exec,
                input_invocation,
                trigger_type,
                app_state,
                cc,
            )?,
        })
    }

provide an observer which can be used for periodic check a task can be used. The observer can safely be moved to another thread but Be careful not to use it after the event listener started again. In any case using try_compute should be preferred for immediate return to the ui thread.

Examples found in repository?
src/file_sum/sum_computation.rs (line 177)
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
    pub fn compute_dir_sum(
        &mut self,
        path: &Path,
        cache: &mut AHashMap<PathBuf, FileSum>,
        dam: &Dam,
        con: &AppContext,
    ) -> Option<FileSum> {
        let threads_count = self.thread_count;

        if is_ignored(path, &con.special_paths) {
            return Some(FileSum::zero());
        }

        // there are problems in /proc - See issue #637
        if path.starts_with("/proc") {
            debug!("not summing in /proc");
            return Some(FileSum::zero());
        }
        if path.starts_with("/run") {
            debug!("not summing in /run");
            return Some(FileSum::zero());
        }

        // to avoid counting twice a node, we store their id in a set
        #[cfg(unix)]
        let nodes = Arc::new(Mutex::new(FnvHashSet::<NodeId>::default()));

        // busy is the number of directories which are either being processed or queued
        // We use this count to determine when threads can stop waiting for tasks
        let mut busy = 0;
        let mut sum = compute_file_sum(path);

        // this MPMC channel contains the directory paths which must be handled.
        // A None means there's nothing left and the thread may send its result and stop
        let (dirs_sender, dirs_receiver) = channel::unbounded();

        let special_paths: Vec<SpecialPath> = con.special_paths.iter()
            .filter(|sp| sp.can_have_matches_in(path))
            .cloned()
            .collect();

        // the first level is managed a little differently: we look at the cache
        // before adding. This enables faster computations in two cases:
        // - for the root line (assuming it's computed after the content)
        // - when we navigate up the tree
        if let Ok(entries) = fs::read_dir(path) {
            for e in entries.flatten() {
                if let Ok(md) = e.metadata() {
                    if md.is_dir() {
                        let entry_path = e.path();

                        if is_ignored(&entry_path, &special_paths) {
                            debug!("not summing special path {:?}", entry_path);
                            continue;
                        }

                        // we check the cache
                        if let Some(entry_sum) = cache.get(&entry_path) {
                            sum += *entry_sum;
                            continue;
                        }

                        // we add the directory to the channel of dirs needing
                        // processing
                        busy += 1;
                        dirs_sender.send(Some(entry_path)).unwrap();
                    } else {

                        #[cfg(unix)]
                        if md.nlink() > 1 {
                            let mut nodes = nodes.lock().unwrap();
                            let node_id = NodeId {
                                inode: md.ino(),
                                dev: md.dev(),
                            };
                            if !nodes.insert(node_id) {
                                // it was already in the set
                                continue;
                            }
                        }

                    }
                    sum += md_sum(&md);
                }
            }
        }

        if busy == 0 {
            return Some(sum);
        }

        let busy = Arc::new(AtomicIsize::new(busy));

        // this MPMC channel is here for the threads to send their results
        // at end of computation
        let (thread_sum_sender, thread_sum_receiver) = channel::bounded(threads_count);

        // Each  thread does a summation without merge and the data are merged
        // at the end (this avoids waiting for a mutex during computation)
        for _ in 0..threads_count {
            let busy = Arc::clone(&busy);
            let (dirs_sender, dirs_receiver) = (dirs_sender.clone(), dirs_receiver.clone());

            #[cfg(unix)]
            let nodes = nodes.clone();

            let special_paths = special_paths.clone();

            let observer = dam.observer();
            let thread_sum_sender = thread_sum_sender.clone();
            self.thread_pool.spawn(move || {
                let mut thread_sum = FileSum::zero();
                loop {
                    let o = dirs_receiver.recv();
                    if let Ok(Some(open_dir)) = o {
                        if let Ok(entries) = fs::read_dir(&open_dir) {
                            for e in entries.flatten() {
                                if let Ok(md) = e.metadata() {
                                    if md.is_dir() {

                                        let path = e.path();

                                        if is_ignored(&path, &special_paths) {
                                            debug!("not summing (deep) special path {:?}", path);
                                            continue;
                                        }

                                        // we add the directory to the channel of dirs needing
                                        // processing
                                        busy.fetch_add(1, Ordering::Relaxed);
                                        dirs_sender.send(Some(path)).unwrap();
                                    } else {

                                        #[cfg(unix)]
                                        if md.nlink() > 1 {
                                            let mut nodes = nodes.lock().unwrap();
                                            let node_id = NodeId {
                                                inode: md.ino(),
                                                dev: md.dev(),
                                            };
                                            if !nodes.insert(node_id) {
                                                // it was already in the set
                                                continue;
                                            }
                                        }

                                    }
                                    thread_sum += md_sum(&md);
                                } else {
                                    // we can't measure much but we can count the file
                                    thread_sum.incr();
                                }
                            }
                        }
                        busy.fetch_sub(1, Ordering::Relaxed);
                    }
                    if observer.has_event() {
                        dirs_sender.send(None).unwrap(); // to unlock the next waiting thread
                        break;
                    }
                    if busy.load(Ordering::Relaxed) < 1 {
                        dirs_sender.send(None).unwrap(); // to unlock the next waiting thread
                        break;
                    }
                }
                thread_sum_sender.send(thread_sum).unwrap();
            });
        }
        // Wait for the threads to finish and consolidate their results
        for _ in 0..threads_count {
            match thread_sum_receiver.recv() {
                Ok(thread_sum) => {
                    sum += thread_sum;
                }
                Err(e) => {
                    warn!("Error while recv summing thread result : {:?}", e);
                }
            }
        }
        if dam.has_event() {
            return None;
        }
        Some(sum)
    }

launch the computation on a new thread and return when it finishes or when a new event appears on the channel. Note that the task itself isn’t interrupted so that this should not be used when many tasks are expected to be launched (or it would result in many working threads uselessly working in the background) : use dam.has_event from inside the task whenever possible.

Examples found in repository?
src/git/status_computer.rs (lines 80-90)
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
pub fn get_tree_status(root_path: &Path, dam: &mut Dam) -> ComputationResult<TreeGitStatus> {
    match git::closest_repo_dir(root_path) {
        None => ComputationResult::None,
        Some(repo_path) => {
            let comp = TS_CACHE_MX
                .lock()
                .unwrap()
                .get(&repo_path)
                .map(|c| (*c).clone());
            match comp {
                Some(Computation::Finished(comp_res)) => {
                    // already computed
                    comp_res
                }
                Some(Computation::InProgress(comp_receiver)) => {
                    // computation in progress
                    // We do a select! to wait for either the dam
                    // or the receiver
                    debug!("start select on in progress computation");
                    dam.select(comp_receiver)
                }
                None => {
                    // not yet started. We launch the computation and store
                    // the receiver immediately.
                    // We use the dam to return from this function when
                    // needed (while letting the underlying thread finish
                    // the job)
                    //
                    // note: must also update the TS_CACHE entry at end
                    let (s, r) = bounded(1);
                    TS_CACHE_MX
                        .lock()
                        .unwrap()
                        .insert(repo_path.clone(), Computation::InProgress(r));
                    dam.try_compute(move || {
                        let comp_res = compute_tree_status(&repo_path);
                        TS_CACHE_MX
                            .lock()
                            .unwrap()
                            .insert(repo_path.clone(), Computation::Finished(comp_res.clone()));
                        if let Err(e) = s.send(comp_res.clone()) {
                            debug!("error while sending comp result: {:?}", e);
                        }
                        comp_res
                    })
                }
            }
        }
    }
}
Examples found in repository?
src/task_sync.rs (line 85)
74
75
76
77
78
79
80
81
82
83
84
85
86
    pub fn try_compute<V: Send + 'static, F: Send + 'static + FnOnce() -> ComputationResult<V>>(
        &mut self,
        f: F,
    ) -> ComputationResult<V> {
        let (comp_sender, comp_receiver) = bounded(1);
        thread::spawn(move || {
            let comp_res = time!("comp in dam", f());
            if comp_sender.send(comp_res).is_err() {
                debug!("no channel at end of computation");
            }
        });
        self.select(comp_receiver)
    }
More examples
Hide additional examples
src/git/status_computer.rs (line 65)
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
pub fn get_tree_status(root_path: &Path, dam: &mut Dam) -> ComputationResult<TreeGitStatus> {
    match git::closest_repo_dir(root_path) {
        None => ComputationResult::None,
        Some(repo_path) => {
            let comp = TS_CACHE_MX
                .lock()
                .unwrap()
                .get(&repo_path)
                .map(|c| (*c).clone());
            match comp {
                Some(Computation::Finished(comp_res)) => {
                    // already computed
                    comp_res
                }
                Some(Computation::InProgress(comp_receiver)) => {
                    // computation in progress
                    // We do a select! to wait for either the dam
                    // or the receiver
                    debug!("start select on in progress computation");
                    dam.select(comp_receiver)
                }
                None => {
                    // not yet started. We launch the computation and store
                    // the receiver immediately.
                    // We use the dam to return from this function when
                    // needed (while letting the underlying thread finish
                    // the job)
                    //
                    // note: must also update the TS_CACHE entry at end
                    let (s, r) = bounded(1);
                    TS_CACHE_MX
                        .lock()
                        .unwrap()
                        .insert(repo_path.clone(), Computation::InProgress(r));
                    dam.try_compute(move || {
                        let comp_res = compute_tree_status(&repo_path);
                        TS_CACHE_MX
                            .lock()
                            .unwrap()
                            .insert(repo_path.clone(), Computation::Finished(comp_res.clone()));
                        if let Err(e) = s.send(comp_res.clone()) {
                            debug!("error while sending comp result: {:?}", e);
                        }
                        comp_res
                    })
                }
            }
        }
    }
}

non blocking

Examples found in repository?
src/app/app.rs (line 624)
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
    fn do_pending_tasks(
        &mut self,
        w: &mut W,
        skin: &AppSkin,
        dam: &mut Dam,
        app_state: &mut AppState,
        con: &AppContext,
    ) -> Result<(), ProgramError> {
        while self.has_pending_task() && !dam.has_event() {
            let error = self.do_pending_task(app_state, con, dam).err();
            self.update_preview(con, false); // the selection may have changed
            if let Some(error) = &error {
                self.mut_panel().set_error(error.to_string());
            //} else {
            //    // the refresh here removes the toggle status message. Not
            //    // sure there's a case it's useful
            //    let app_cmd_context = AppCmdContext {
            //        panel_skin: &skin.focused,
            //        preview_panel: self.preview_panel,
            //        stage_panel: self.stage_panel,
            //        screen: self.screen,
            //        con,
            //    };
            //    self.mut_panel().refresh_input_status(app_state, &app_cmd_context);
            }
            self.display_panels(w, skin, app_state, con)?;
            if error.is_some() {
                return Ok(()); // breaking pending tasks chain on first error/interruption
            }
        }
        Ok(())
    }
More examples
Hide additional examples
src/syntactic/syntactic_view.rs (line 170)
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
    fn read_lines(
        &mut self,
        dam: &mut Dam,
        con: &AppContext,
        no_style: bool,
    ) -> Result<bool, ProgramError> {
        let f = File::open(&self.path)?;
        {
            // if we detect the file isn't mappable, we'll
            // let the ZeroLenFilePreview try to read it
            let mmap = unsafe { Mmap::map(&f) };
            if mmap.is_err() {
                return Err(ProgramError::UnmappableFile);
            }
        }
        let md = f.metadata()?;
        if md.len() == 0 {
            return Err(ProgramError::ZeroLenFile);
        }
        let with_style = !no_style && md.len() < MAX_SIZE_FOR_STYLING;
        let mut reader = BufReader::new(f);
        self.lines.clear();
        let mut line = String::new();
        self.total_lines_count = 0;
        let mut offset = 0;
        let mut number = 0;
        static SYNTAXER: Lazy<Syntaxer> = Lazy::new(Syntaxer::default);
        let mut highlighter = if with_style {
            SYNTAXER.highlighter_for(&self.path, con)
        } else {
            None
        };
        let pattern = &self.pattern.pattern;
        while reader.read_line(&mut line)? > 0 {
            number += 1;
            self.total_lines_count += 1;
            let start = offset;
            offset += line.len();
            for c in line.chars() {
                if !is_char_printable(c) {
                    debug!("unprintable char: {:?}", c);
                    return Err(ProgramError::UnprintableFile);
                }
            }
            // We don't remove '\n' or '\r' at this point because some syntax sets
            // need them for correct detection of comments. See #477
            // Those chars are removed on printing
            if pattern.is_empty() || pattern.score_of_string(&line).is_some() {
                let name_match = pattern.search_string(&line);
                let regions = if let Some(highlighter) = highlighter.as_mut() {
                    highlighter
                        .highlight(&line, &SYNTAXER.syntax_set)
                        .map_err(|e| ProgramError::SyntectCrashed { details: e.to_string() })?
                        .iter()
                        .map(Region::from_syntect)
                        .collect()
                } else {
                    Vec::new()
                };
                self.lines.push(Line {
                    regions,
                    start,
                    len: line.len(),
                    name_match,
                    number,
                });
            }
            line.clear();
            if dam.has_event() {
                info!("event interrupted preview filtering");
                return Ok(false);
            }
        }
        Ok(true)
    }
src/tree_build/builder.rs (line 326)
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
    fn gather_lines(&mut self, total_search: bool, dam: &Dam) -> Result<Vec<BId>, TreeBuildError> {
        let start = Instant::now();
        let mut out_blines: Vec<BId> = Vec::new(); // the blines we want to display
        let optimal_size = if self.options.pattern.pattern.has_real_scores() {
            10 * self.targeted_size
        } else {
            self.targeted_size
        };
        out_blines.push(self.root_id);
        let mut nb_lines_ok = 1; // in out_blines
        let mut open_dirs: VecDeque<BId> = VecDeque::new();
        let mut next_level_dirs: Vec<BId> = Vec::new();
        self.load_children(self.root_id);
        open_dirs.push_back(self.root_id);
        loop {
            if !total_search && (
                (nb_lines_ok > optimal_size)
                || (nb_lines_ok >= self.targeted_size && start.elapsed() > NOT_LONG)
            ) {
                self.total_search = false;
                break;
            }
            if let Some(max) = self.matches_max {
                if nb_lines_ok > max {
                    return Err(TreeBuildError::TooManyMatches{max});
                }
            }
            if let Some(open_dir_id) = open_dirs.pop_front() {
                if let Some(child_id) = self.next_child(open_dir_id) {
                    open_dirs.push_back(open_dir_id);
                    let child = &self.blines[child_id];
                    if child.has_match {
                        nb_lines_ok += 1;
                    }
                    if child.can_enter() {
                        next_level_dirs.push(child_id);
                    }
                    out_blines.push(child_id);
                }
            } else {
                // this depth is finished, we must go deeper
                if self.options.sort.prevent_deep_display() {
                    // in sort mode, only one level is displayed
                    break;
                }
                if next_level_dirs.is_empty() {
                    // except there's nothing deeper
                    break;
                }
                for next_level_dir_id in &next_level_dirs {
                    if dam.has_event() {
                        info!("task expired (core build - inner loop)");
                        return Err(TreeBuildError::Interrupted);
                    }
                    let has_child_match = self.load_children(*next_level_dir_id);
                    if has_child_match {
                        // we must ensure the ancestors are made Ok
                        let mut id = *next_level_dir_id;
                        loop {
                            let mut bline = &mut self.blines[id];
                            if !bline.has_match {
                                bline.has_match = true;
                                nb_lines_ok += 1;
                            }
                            if let Some(pid) = bline.parent_id {
                                id = pid;
                            } else {
                                break;
                            }
                        }
                    }
                    open_dirs.push_back(*next_level_dir_id);
                }
                next_level_dirs.clear();
            }
        }
        if let Some(max) = self.matches_max {
            if nb_lines_ok > max {
                return Err(TreeBuildError::TooManyMatches{max});
            }
        }
        if !self.trim_root {
            // if the root directory isn't totally read, we finished it even
            // it it goes past the bottom of the screen
            while let Some(child_id) = self.next_child(self.root_id) {
                out_blines.push(child_id);
            }
        }
        Ok(out_blines)
    }
src/file_sum/sum_computation.rs (line 248)
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
    pub fn compute_dir_sum(
        &mut self,
        path: &Path,
        cache: &mut AHashMap<PathBuf, FileSum>,
        dam: &Dam,
        con: &AppContext,
    ) -> Option<FileSum> {
        let threads_count = self.thread_count;

        if is_ignored(path, &con.special_paths) {
            return Some(FileSum::zero());
        }

        // there are problems in /proc - See issue #637
        if path.starts_with("/proc") {
            debug!("not summing in /proc");
            return Some(FileSum::zero());
        }
        if path.starts_with("/run") {
            debug!("not summing in /run");
            return Some(FileSum::zero());
        }

        // to avoid counting twice a node, we store their id in a set
        #[cfg(unix)]
        let nodes = Arc::new(Mutex::new(FnvHashSet::<NodeId>::default()));

        // busy is the number of directories which are either being processed or queued
        // We use this count to determine when threads can stop waiting for tasks
        let mut busy = 0;
        let mut sum = compute_file_sum(path);

        // this MPMC channel contains the directory paths which must be handled.
        // A None means there's nothing left and the thread may send its result and stop
        let (dirs_sender, dirs_receiver) = channel::unbounded();

        let special_paths: Vec<SpecialPath> = con.special_paths.iter()
            .filter(|sp| sp.can_have_matches_in(path))
            .cloned()
            .collect();

        // the first level is managed a little differently: we look at the cache
        // before adding. This enables faster computations in two cases:
        // - for the root line (assuming it's computed after the content)
        // - when we navigate up the tree
        if let Ok(entries) = fs::read_dir(path) {
            for e in entries.flatten() {
                if let Ok(md) = e.metadata() {
                    if md.is_dir() {
                        let entry_path = e.path();

                        if is_ignored(&entry_path, &special_paths) {
                            debug!("not summing special path {:?}", entry_path);
                            continue;
                        }

                        // we check the cache
                        if let Some(entry_sum) = cache.get(&entry_path) {
                            sum += *entry_sum;
                            continue;
                        }

                        // we add the directory to the channel of dirs needing
                        // processing
                        busy += 1;
                        dirs_sender.send(Some(entry_path)).unwrap();
                    } else {

                        #[cfg(unix)]
                        if md.nlink() > 1 {
                            let mut nodes = nodes.lock().unwrap();
                            let node_id = NodeId {
                                inode: md.ino(),
                                dev: md.dev(),
                            };
                            if !nodes.insert(node_id) {
                                // it was already in the set
                                continue;
                            }
                        }

                    }
                    sum += md_sum(&md);
                }
            }
        }

        if busy == 0 {
            return Some(sum);
        }

        let busy = Arc::new(AtomicIsize::new(busy));

        // this MPMC channel is here for the threads to send their results
        // at end of computation
        let (thread_sum_sender, thread_sum_receiver) = channel::bounded(threads_count);

        // Each  thread does a summation without merge and the data are merged
        // at the end (this avoids waiting for a mutex during computation)
        for _ in 0..threads_count {
            let busy = Arc::clone(&busy);
            let (dirs_sender, dirs_receiver) = (dirs_sender.clone(), dirs_receiver.clone());

            #[cfg(unix)]
            let nodes = nodes.clone();

            let special_paths = special_paths.clone();

            let observer = dam.observer();
            let thread_sum_sender = thread_sum_sender.clone();
            self.thread_pool.spawn(move || {
                let mut thread_sum = FileSum::zero();
                loop {
                    let o = dirs_receiver.recv();
                    if let Ok(Some(open_dir)) = o {
                        if let Ok(entries) = fs::read_dir(&open_dir) {
                            for e in entries.flatten() {
                                if let Ok(md) = e.metadata() {
                                    if md.is_dir() {

                                        let path = e.path();

                                        if is_ignored(&path, &special_paths) {
                                            debug!("not summing (deep) special path {:?}", path);
                                            continue;
                                        }

                                        // we add the directory to the channel of dirs needing
                                        // processing
                                        busy.fetch_add(1, Ordering::Relaxed);
                                        dirs_sender.send(Some(path)).unwrap();
                                    } else {

                                        #[cfg(unix)]
                                        if md.nlink() > 1 {
                                            let mut nodes = nodes.lock().unwrap();
                                            let node_id = NodeId {
                                                inode: md.ino(),
                                                dev: md.dev(),
                                            };
                                            if !nodes.insert(node_id) {
                                                // it was already in the set
                                                continue;
                                            }
                                        }

                                    }
                                    thread_sum += md_sum(&md);
                                } else {
                                    // we can't measure much but we can count the file
                                    thread_sum.incr();
                                }
                            }
                        }
                        busy.fetch_sub(1, Ordering::Relaxed);
                    }
                    if observer.has_event() {
                        dirs_sender.send(None).unwrap(); // to unlock the next waiting thread
                        break;
                    }
                    if busy.load(Ordering::Relaxed) < 1 {
                        dirs_sender.send(None).unwrap(); // to unlock the next waiting thread
                        break;
                    }
                }
                thread_sum_sender.send(thread_sum).unwrap();
            });
        }
        // Wait for the threads to finish and consolidate their results
        for _ in 0..threads_count {
            match thread_sum_receiver.recv() {
                Ok(thread_sum) => {
                    sum += thread_sum;
                }
                Err(e) => {
                    warn!("Error while recv summing thread result : {:?}", e);
                }
            }
        }
        if dam.has_event() {
            return None;
        }
        Some(sum)
    }

block until next event (including the one which may have been pushed back into the dam). no event means the source is dead (i.e. we must quit broot) There’s no event kept in dam after this call.

Examples found in repository?
src/app/app.rs (line 736)
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
    pub fn run(
        mut self,
        w: &mut W,
        con: &mut AppContext,
        conf: &Conf,
    ) -> Result<Option<Launchable>, ProgramError> {
        #[cfg(feature = "clipboard")]
        {
            // different systems have different clipboard capabilities
            // and it may be useful to know which one we have
            debug!("Clipboard backend: {:?}", terminal_clipboard::get_type());
        }

        // we listen for events in a separate thread so that we can go on listening
        // when a long search is running, and interrupt it if needed
        let event_source = EventSource::new()?;
        let rx_events = event_source.receiver();
        let mut dam = Dam::from(rx_events);
        let skin = AppSkin::new(conf, con.launch_args.color == TriBool::No);
        let mut app_state = AppState {
            stage: Stage::default(),
            root: con.initial_root.clone(),
            other_panel_path: None,
        };

        self.screen.clear_bottom_right_char(w, &skin.focused)?;

        if let Some(raw_sequence) = &con.launch_args.cmd {
            self.tx_seqs
                .send(Sequence::new_local(raw_sequence.to_string()))
                .unwrap();
        }

        #[cfg(unix)]
        let _server = con.launch_args.listen.as_ref()
            .map(|server_name| {
                let shared_root = Arc::new(Mutex::new(app_state.root.clone()));
                let server = crate::net::Server::new(
                    server_name,
                    self.tx_seqs.clone(),
                    Arc::clone(&shared_root),
                );
                self.shared_root = Some(shared_root);
                server
            })
            .transpose()?;

        loop {
            if !self.quitting {
                self.display_panels(w, &skin, &app_state, con)?;
                time!(
                    Info,
                    "pending_tasks",
                    self.do_pending_tasks(w, &skin, &mut dam, &mut app_state, con)?,
                );
            }
            #[allow(unused_mut)]
            match dam.next(&self.rx_seqs) {
                Either::First(Some(event)) => {
                    info!("event: {:?}", &event);
                    let mut handled = false;

                    // app level handling
                    if let Some((x, y)) = event.as_click() {
                        if self.clicked_panel_index(x, y) != self.active_panel_idx {
                            // panel activation click
                            self.active_panel_idx = self.clicked_panel_index(x, y);
                            handled = true;
                        }
                    } else if let Event::Resize(mut width, mut height) = event.event {
                        // I don't know why but Crossterm seems to always report an
                        // understimated size on Windows
                        #[cfg(windows)]
                        {
                            width += 1;
                            height += 1;
                        }
                        self.screen.set_terminal_size(width, height, con);
                        Areas::resize_all(
                            self.panels.as_mut_slice(),
                            self.screen,
                            self.preview_panel.is_some(),
                        );
                        for panel in &mut self.panels {
                            panel.mut_state().refresh(self.screen, con);
                        }
                        handled = true;
                    }

                    // event handled by the panel
                    if !handled {
                        let cmd = self.mut_panel().add_event(w, event, &app_state, con)?;
                        debug!("command after add_event: {:?}", &cmd);
                        self.apply_command(w, cmd, &skin.focused, &mut app_state, con)?;

                    }

                    event_source.unblock(self.quitting);
                }
                Either::First(None) => {
                    // this is how we quit the application,
                    // when the input thread is properly closed
                    break;
                }
                Either::Second(Some(raw_sequence)) => {
                    debug!("got command sequence: {:?}", &raw_sequence);
                    for (input, arg_cmd) in raw_sequence.parse(con)? {
                        self.mut_panel().set_input_content(&input);
                        self.apply_command(w, arg_cmd, &skin.focused, &mut app_state, con)?;
                        if self.quitting {
                            // is that a 100% safe way of quitting ?
                            return Ok(self.launch_at_end.take());
                        } else {
                            self.display_panels(w, &skin, &app_state, con)?;
                            time!(
                                "sequence pending tasks",
                                self.do_pending_tasks(w, &skin, &mut dam, &mut app_state, con)?,
                            );
                        }
                    }
                }
                Either::Second(None) => {
                    warn!("I didn't expect a None to occur here");
                }
            }
        }

        Ok(self.launch_at_end.take())
    }

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The alignment of pointer.
The type for initializers.
Initializes a with the given initializer. Read more
Dereferences the given pointer. Read more
Mutably dereferences the given pointer. Read more
Drops the object pointed to by the given pointer. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.