slint/
private_unstable_api.rs

1// Copyright © SixtyFPS GmbH <[email protected]>
2// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
3
4//! Module containing the private api that is used by the generated code.
5//!
6//! This is internal API that shouldn't be used because compatibility is not
7//! guaranteed
8#![doc(hidden)]
9
10use core::pin::Pin;
11use re_exports::*;
12
13// Helper functions called from generated code to reduce code bloat from
14// extra copies of the original functions for each call site due to
15// the impl Fn() they are taking.
16
17pub trait StrongItemTreeRef: Sized {
18    type Weak: Clone + 'static;
19    fn to_weak(&self) -> Self::Weak;
20    fn from_weak(weak: &Self::Weak) -> Option<Self>;
21}
22
23impl<C: 'static> StrongItemTreeRef for VRc<ItemTreeVTable, C> {
24    type Weak = VWeak<ItemTreeVTable, C>;
25    fn to_weak(&self) -> Self::Weak {
26        VRc::downgrade(self)
27    }
28    fn from_weak(weak: &Self::Weak) -> Option<Self> {
29        weak.upgrade()
30    }
31}
32
33impl<C: 'static> StrongItemTreeRef for VRcMapped<ItemTreeVTable, C> {
34    type Weak = VWeakMapped<ItemTreeVTable, C>;
35    fn to_weak(&self) -> Self::Weak {
36        VRcMapped::downgrade(self)
37    }
38    fn from_weak(weak: &Self::Weak) -> Option<Self> {
39        weak.upgrade()
40    }
41}
42
43impl<C: 'static> StrongItemTreeRef for Pin<Rc<C>> {
44    type Weak = PinWeak<C>;
45    fn to_weak(&self) -> Self::Weak {
46        PinWeak::downgrade(self.clone())
47    }
48    fn from_weak(weak: &Self::Weak) -> Option<Self> {
49        weak.upgrade()
50    }
51}
52
53pub fn set_property_binding<
54    T: Clone + Default + 'static,
55    StrongRef: StrongItemTreeRef + 'static,
56>(
57    property: Pin<&Property<T>>,
58    component_strong: &StrongRef,
59    binding: fn(StrongRef) -> T,
60) {
61    let weak = component_strong.to_weak();
62    property.set_binding(move || {
63        <StrongRef as StrongItemTreeRef>::from_weak(&weak).map(binding).unwrap_or_default()
64    })
65}
66
67pub fn set_animated_property_binding<
68    T: Clone + i_slint_core::properties::InterpolatedPropertyValue + 'static,
69    StrongRef: StrongItemTreeRef + 'static,
70>(
71    property: Pin<&Property<T>>,
72    component_strong: &StrongRef,
73    binding: fn(StrongRef) -> T,
74    animation_data: PropertyAnimation,
75) {
76    let weak = component_strong.to_weak();
77    property.set_animated_binding(
78        move || binding(<StrongRef as StrongItemTreeRef>::from_weak(&weak).unwrap()),
79        animation_data,
80    )
81}
82
83pub fn set_animated_property_binding_for_transition<
84    T: Clone + i_slint_core::properties::InterpolatedPropertyValue + 'static,
85    StrongRef: StrongItemTreeRef + 'static,
86>(
87    property: Pin<&Property<T>>,
88    component_strong: &StrongRef,
89    binding: fn(StrongRef) -> T,
90    compute_animation_details: fn(
91        StrongRef,
92    ) -> (PropertyAnimation, i_slint_core::animations::Instant),
93) {
94    let weak_1 = component_strong.to_weak();
95    let weak_2 = weak_1.clone();
96    property.set_animated_binding_for_transition(
97        move || binding(<StrongRef as StrongItemTreeRef>::from_weak(&weak_1).unwrap()),
98        move || {
99            compute_animation_details(<StrongRef as StrongItemTreeRef>::from_weak(&weak_2).unwrap())
100        },
101    )
102}
103
104pub fn set_property_state_binding<StrongRef: StrongItemTreeRef + 'static>(
105    property: Pin<&Property<StateInfo>>,
106    component_strong: &StrongRef,
107    binding: fn(StrongRef) -> i32,
108) {
109    let weak = component_strong.to_weak();
110    re_exports::set_state_binding(property, move || {
111        binding(<StrongRef as StrongItemTreeRef>::from_weak(&weak).unwrap())
112    })
113}
114
115pub fn set_callback_handler<
116    Arg: ?Sized + 'static,
117    Ret: Default + 'static,
118    StrongRef: StrongItemTreeRef + 'static,
119>(
120    callback: Pin<&Callback<Arg, Ret>>,
121    component_strong: &StrongRef,
122    handler: fn(StrongRef, &Arg) -> Ret,
123) {
124    let weak = component_strong.to_weak();
125    callback.set_handler(move |arg| {
126        handler(<StrongRef as StrongItemTreeRef>::from_weak(&weak).unwrap(), arg)
127    })
128}
129
130pub fn debug(s: SharedString) {
131    #[cfg(feature = "log")]
132    log::debug!("{s}");
133    #[cfg(not(feature = "log"))]
134    i_slint_core::debug_log!("{s}");
135}
136
137pub fn ensure_backend() -> Result<(), crate::PlatformError> {
138    i_slint_backend_selector::with_platform(|_b| {
139        // Nothing to do, just make sure a backend was created
140        Ok(())
141    })
142}
143
144/// Creates a new window to render components in.
145pub fn create_window_adapter(
146) -> Result<alloc::rc::Rc<dyn i_slint_core::window::WindowAdapter>, crate::PlatformError> {
147    i_slint_backend_selector::with_platform(|b| b.create_window_adapter())
148}
149
150/// Wrapper around i_slint_core::translations::translate for the generated code
151pub fn translate(
152    origin: SharedString,
153    context: SharedString,
154    domain: SharedString,
155    args: Slice<SharedString>,
156    n: i32,
157    plural: SharedString,
158) -> SharedString {
159    i_slint_core::translations::translate(&origin, &context, &domain, args.as_slice(), n, &plural)
160}
161
162#[cfg(feature = "gettext")]
163pub fn init_translations(domain: &str, dirname: impl Into<std::path::PathBuf>) {
164    i_slint_core::translations::gettext_bindtextdomain(domain, dirname.into()).unwrap()
165}
166
167pub fn use_24_hour_format() -> bool {
168    i_slint_core::date_time::use_24_hour_format()
169}
170
171/// internal re_exports used by the macro generated
172pub mod re_exports {
173    pub use alloc::boxed::Box;
174    pub use alloc::rc::{Rc, Weak};
175    pub use alloc::string::String;
176    pub use alloc::{vec, vec::Vec};
177    pub use const_field_offset::{self, FieldOffsets, PinnedDrop};
178    pub use core::iter::FromIterator;
179    pub use core::option::{Option, Option::*};
180    pub use core::result::{Result, Result::*};
181    pub use i_slint_core::format;
182    // This one is empty when Qt is not available, which triggers a warning
183    pub use euclid::approxeq::ApproxEq;
184    #[allow(unused_imports)]
185    pub use i_slint_backend_selector::native_widgets::*;
186    pub use i_slint_core::accessibility::{
187        AccessibilityAction, AccessibleStringProperty, SupportedAccessibilityAction,
188    };
189    pub use i_slint_core::animations::{animation_tick, EasingCurve};
190    pub use i_slint_core::api::LogicalPosition;
191    pub use i_slint_core::callbacks::Callback;
192    pub use i_slint_core::date_time::*;
193    pub use i_slint_core::detect_operating_system;
194    pub use i_slint_core::graphics::*;
195    pub use i_slint_core::input::{
196        key_codes::Key, FocusEvent, FocusReason, InputEventResult, KeyEvent, KeyEventResult,
197        KeyboardModifiers, MouseEvent,
198    };
199    pub use i_slint_core::item_tree::{
200        register_item_tree, unregister_item_tree, IndexRange, ItemTree, ItemTreeRefPin,
201        ItemTreeVTable, ItemTreeWeak,
202    };
203    pub use i_slint_core::item_tree::{
204        visit_item_tree, ItemTreeNode, ItemVisitorRefMut, ItemVisitorVTable, ItemWeak,
205        TraversalOrder, VisitChildrenResult,
206    };
207    pub use i_slint_core::items::*;
208    pub use i_slint_core::layout::*;
209    pub use i_slint_core::lengths::{
210        logical_position_to_api, LogicalLength, LogicalPoint, LogicalRect,
211    };
212    pub use i_slint_core::menus::{Menu, MenuFromItemTree, MenuVTable};
213    pub use i_slint_core::model::*;
214    pub use i_slint_core::properties::{
215        set_state_binding, ChangeTracker, Property, PropertyTracker, StateInfo,
216    };
217    pub use i_slint_core::slice::Slice;
218    pub use i_slint_core::string::shared_string_from_number;
219    pub use i_slint_core::string::shared_string_from_number_fixed;
220    pub use i_slint_core::string::shared_string_from_number_precision;
221    pub use i_slint_core::timers::{Timer, TimerMode};
222    pub use i_slint_core::translations::{
223        set_bundled_languages, translate_from_bundle, translate_from_bundle_with_plural,
224    };
225    pub use i_slint_core::window::{
226        InputMethodRequest, WindowAdapter, WindowAdapterRc, WindowInner,
227    };
228    pub use i_slint_core::{Color, Coord, SharedString, SharedVector};
229    pub use i_slint_core::{ItemTreeVTable_static, MenuVTable_static};
230    pub use num_traits::float::Float;
231    pub use num_traits::ops::euclid::Euclid;
232    pub use once_cell::race::OnceBox;
233    pub use once_cell::unsync::OnceCell;
234    pub use pin_weak::rc::PinWeak;
235    pub use unicode_segmentation::UnicodeSegmentation;
236    pub use vtable::{self, *};
237}