Skip to content

Tutorial Scheduler Threaded Execution Task

ddbnl edited this page Sep 2, 2022 · 1 revision

To run custom code that will not return immediately (i.e. your app that you are building the UI for), you must used threaded execution to avoid blocking the UI in the main thread. There will be an example mock app below. First we'll discuss manipulating the UI from a thread.

Working with the UI from a thread is nearly identical to working with the UI from a normal task or callback. The small difference is that in a normal callback you have a "Context" object available, giving you access to the scheduler (context.scheduler) and state tree (context.state_tree). This is the case in threads as well, but now you have a "ThreadedContext" object instead. Where in a normal Context you have a "&mut Scheduler" and "&mut StateTree", in a "ThreadedContext" you have a full "Scheduler" and a full "StateTree" (because we can't use the mutable references in threads). So where in a normal callback you would write "context.scheduler", you now write "&mut context.scheduler", and where you write "context.state_tree", you will now write "&mut context.state_tree".

Any changes you make in a threaded state tree will be synced to the main thread automatically. Any methods you call on the scheduler will be passed to the main thread for you as well. Changes to the state tree from the main thread are not synced to threads automatically for performance reasons (often you don't need them), so you can call 'context.scheduler.sync_state_tree()' from a thread to sync the state tree, or 'context.scheduler.sync_properties()' to sync custom properties.

When scheduling a threaded task, the first parameter is the function you want to execute, and the second parameter will be an optional on_finish function or closure. The on_finish will be executed when the thread terminates. We'll now look at examples of scheduling threaded functions, and two ways to work with the UI from a thread (first with the state tree, then with a custom property):

Working with the UI from threads using the StateTree

Let's schedule a threaded task, and use the state tree to manipulate the UI from the thread. We'll look at an example using a mock app. The mock app will sleep regularly to simulate a long running function. We'll create a UI that contains a progress bar and a label, and every time we finish sleeping we will update the progress bar and the label. We will also use an on_finish closure to make the label say "finished!" when the thread terminates (if you do not want an on_finish function, just pass "None"):

- Layout:
    mode: box
    orientation: vertical
    - Button:
        id: my_button
        text: Start
        auto_scale: true, true
        halign: center
    - Label:
        id: my_progress_label
        text: Not started.
        auto_scale: true, true
        halign: center
    - ProgressBar:
        id: my_progress_bar
        border: true
use ez_term::*;
use std::time::Duration;

let (root_widget, mut state_tree, mut scheduler) = load_ui();

fn mock_app(mut context: ThreadedContext) {

    for x in 1..=5 {
        let state = context.state_tree.get_mut("my_progress_bar").as_progress_bar_mut();
        state.set_value(x*20);
        state.update(&mut context.scheduler);

        let state = context.state_tree.get_mut("my_progress_label").as_label_mut();
        state.set_text(format!("{}%", x*20));
        state.update(&mut context.scheduler);

        std::thread::sleep(Duration::from_secs(1)) };
}


let start_button_callback = |context: Context| {

    let on_finish = |context: Context| {

       let state = context.state_tree.get_mut("my_progress_label").as_label_mut();
       state.set_text("Finished!".to_string());
       state.update(context.scheduler);
    };
    context.scheduler.schedule_threaded(Box::new(mock_app), Some(Box::new(on_finish)));
    true
};

let new_callback_config = CallbackConfig::from_on_press(Box::new(start_button_callback));
scheduler.update_callback_config("my_button", new_callback_config);

run(root_widget, state_tree, scheduler);

50_scheduler_threaded

Working with the UI from threads using custom properties

Another way to manipulate the UI from a background thread is through custom properties. These will be discussed in detail on their own page, but we will show an example here. The upshot is that we will create a custom property, bind it to a widget property in the .ez file and then use that custom property in our threaded function. Every time we change it, the widget property it is bound to will update as well.

Thinking about our example with the progress bar, we could create a custom property called "my_progress" and bind it to the "value" property of the progress bar. Now, every time we update our custom property in our function, the progress bar will also update. Using custom properties can be more ergonomic if you already have a variable in your custom code, and you always want that variable to be reflected in the UI. Instead of constantly manually updating the UI when your app variable changes, you can just change your app variable to be a custom EzTerm property and save yourself the effort of updating the UI. Let's change the above example to use a custom property; we will first show the .ez file:

- Layout:
    mode: box
    orientation: vertical
    - Button:
        id: my_button
        text: Start
        auto_scale: true, true
        halign: center
    - Label:
        id: my_progress_label
        text: properties.my_progress
        auto_scale: true, true
        halign: center
    - ProgressBar:
        id: my_progress_bar
        value: properties.my_progress
        border: true

As you can see we bound the "my_progress" custom property to the progress bar and the label. We can bind a usize property to 'label.text' because every type of property can be converted to a String. For any other property than String, the property types must match. We now need to make sure that the custom property actually exists at run time, and we need to change our mock_app function to make use of it:

use ez_term::*;
use std::time::Duration;

let (root_widget, mut state_tree, mut scheduler) = load_ui();

// We must register our custom property!
scheduler.new_usize_property("my_progress", 0);

fn mock_app(mut context: ThreadedContext) {

   for x in 1..=5 {
       let my_progress = context.scheduler.get_property_mut("my_progress");
       my_progress.as_usize_mut().set(x*20);
       std::thread::sleep(Duration::from_secs(1)) };
}

let start_button_callback = |context: Context| {

    context.scheduler.schedule_threaded(Box::new(mock_app), None);
    true
};

let new_callback_config = CallbackConfig::from_on_press(Box::new(start_button_callback));
scheduler.update_callback_config("my_button", new_callback_config);

run(root_widget, state_tree, scheduler);

51_scheduler_threaded

Because we bound our label text to our custom property, we cannot manually update it to say "Finished!" any more, so we removed the on_finish closure. Of course we could just not bind the label text to "my_progress", but it was useful to see an example of binding any type of property to a string property, and scheduling a threaded task without an on_finish function.

Continue

The general tutorial continues with: Custom properties.

Tutorial Tutorial-Project-Structure
  Minimal example
EzLang
  EzLang basics
  EzLang Templates
  Ezlang Layout modes
   EzLang Box mode layouts
   EzLang Stack mode layouts
   EzLang Table mode layouts
   EzLang Float mode layouts
   EzLang Tab mode layouts
   EzLang Screen mode layouts
   EzLang Layout Scrolling
   EzLang Layout Views
  EzLang Widget overview
   EzLang Label
   EzLang Text Input
   EzLang Button
   EzLang Checkbox
   EzLang Radio button
   EzLang Dropdown
   EzLang Slider
   EzLang Canvas
  EzLang Property Binding
  EzLang Sizing
   EzLang Size hints
   EzLang Auto scaling
   EzLang Maths Sizing
   EzLang Manual Sizing
  EzLang Positioning
   EzLang Layout Mode Positioning
   EzLang Position Hints
   EzLang Position Maths
   EzLang Manual Position
   EzLang Adjusting Position
  EzLang Keyboard Selection
Scheduler
  Widget States and the State Tree
  The Scheduler Object
  Managing callbacks
   Callback Structure
   Callback Configs
   Callback: On keyboard enter
   Callback: On Left Mouse Click
   Callback: On Press
   Callback: On Select
   Callback: On Deselect
   Callback: On Right Mouse Click
   Callback: On Hover
   Callback: On Drag
   Callback: On Scroll Up
   Callback: On Scroll Down
   Callback: On Value Change
   Callback: Custom Key Binds
   Callback: Global Key Binds
   Callback: Property Binds
  Tasks
   Scheduled Single Exectution Tasks
   Scheduled Recurring Tasks
   Threaded Tasks
  Custom Properties
  Modals
  Programmatic Widgets
  Updating widgets
  Managing selection
Default global (key)binds
Performance
ExamplesLayout: Box Mode Nested
Layout: Box Mode Size Hints
Layout: Stack Mode
Layout: Table Mode Dynamic
Layout: Table Mode Static
Layout: Float Mode Manual
Layout: Float Mode Position hints
Layout: Screen Mode
Layout: Tab Mode
Layout: Scrolling
Layout: Views
Widget: Label
Widget: Text input
Widget: Button
Widget: Checkbox
Widget: Radio Button
Widget: Dropdown
Widget: Slider
Widget: Progress Bar
Widget: Canvas
Scheduler: Schedule Once
Scheduler: Schedule Once Callback
Scheduler: Schedule Recurring
Scheduler: Schedule Recurring Callback
Scheduler: Threaded Task State Tree
Scheduler: Threaded Task Custom Property
Scheduler: Create Widgets
Scheduler: Modal Popup
Reference Widgets
  Common Properties
  Label
  Text Input
  Button
  Checkbox
  Radio button
  Dropdown
  Slider
  Canvas
Scheduler
  Schedule once
  Schedule Recurring
  Schedule Threaded
  Cancel Task
  Cancel Recurring Task
  Create Widget
  Remove Widget
  Select Widget
  Deselect Widget
  Update Widget
  Force Redraw
  Open Modal
  Dismiss Modal
  Bind Global Key
  Remove Global Key
  Clear Global Keys
  Bind Property
  Create Custom Properties
  Get Property
  Get Property Mut
  Overwrite Callback Config
  Update Callback Config
  Exit
Clone this wiki locally