Skip to main content

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    compute_animation_details: fn(
75        StrongRef,
76    )
77        -> (PropertyAnimation, Option<i_slint_core::animations::Instant>),
78) {
79    let weak_1 = component_strong.to_weak();
80    let weak_2 = weak_1.clone();
81    property.set_animated_binding(
82        move || binding(<StrongRef as StrongItemTreeRef>::from_weak(&weak_1).unwrap()),
83        move || {
84            compute_animation_details(<StrongRef as StrongItemTreeRef>::from_weak(&weak_2).unwrap())
85        },
86    )
87}
88
89pub fn set_property_state_binding<StrongRef: StrongItemTreeRef + 'static>(
90    property: Pin<&Property<StateInfo>>,
91    component_strong: &StrongRef,
92    binding: fn(StrongRef) -> i32,
93) {
94    let weak = component_strong.to_weak();
95    re_exports::set_state_binding(property, move || {
96        binding(<StrongRef as StrongItemTreeRef>::from_weak(&weak).unwrap())
97    })
98}
99
100pub fn set_callback_handler<
101    Arg: ?Sized + 'static,
102    Ret: Default + 'static,
103    StrongRef: StrongItemTreeRef + 'static,
104>(
105    callback: Pin<&Callback<Arg, Ret>>,
106    component_strong: &StrongRef,
107    handler: fn(StrongRef, &Arg) -> Ret,
108) {
109    let weak = component_strong.to_weak();
110    callback.set_handler(move |arg| {
111        handler(<StrongRef as StrongItemTreeRef>::from_weak(&weak).unwrap(), arg)
112    })
113}
114
115pub fn debug(s: SharedString) {
116    #[cfg(feature = "log")]
117    log::debug!("{s}");
118    #[cfg(not(feature = "log"))]
119    i_slint_core::debug_log!("{s}");
120}
121
122pub fn ensure_backend() -> Result<(), crate::PlatformError> {
123    i_slint_backend_selector::with_platform(|_b| {
124        // Nothing to do, just make sure a backend was created
125        Ok(())
126    })
127}
128
129/// Creates a new window to render components in.
130pub fn create_window_adapter()
131-> Result<alloc::rc::Rc<dyn i_slint_core::window::WindowAdapter>, crate::PlatformError> {
132    i_slint_backend_selector::with_platform(|b| b.create_window_adapter())
133}
134
135/// Wrapper around i_slint_core::translations::translate for the generated code
136pub fn translate(
137    origin: SharedString,
138    context: SharedString,
139    domain: SharedString,
140    args: Slice<SharedString>,
141    n: i32,
142    plural: SharedString,
143) -> SharedString {
144    i_slint_core::translations::translate(&origin, &context, &domain, args.as_slice(), n, &plural)
145}
146
147#[cfg(feature = "gettext")]
148pub fn init_translations(domain: &str, dirname: impl Into<std::path::PathBuf>) {
149    i_slint_core::translations::gettext_bindtextdomain(domain, dirname.into()).unwrap()
150}
151
152pub fn use_24_hour_format() -> bool {
153    i_slint_core::date_time::use_24_hour_format()
154}
155
156/// internal re_exports used by the macro generated
157pub mod re_exports {
158    pub use alloc::boxed::Box;
159    pub use alloc::rc::{Rc, Weak};
160    pub use alloc::string::String;
161    pub use alloc::{vec, vec::Vec};
162    pub use const_field_offset::{self, FieldOffsets, PinnedDrop};
163    pub use core::iter::FromIterator;
164    pub use core::option::{Option, Option::*};
165    pub use core::result::{Result, Result::*};
166    pub use i_slint_core::styled_text::{StyledText, escape_markdown, parse_markdown};
167    // This one is empty when Qt is not available, which triggers a warning
168    pub use euclid::approxeq::ApproxEq;
169    #[allow(unused_imports)]
170    pub use i_slint_backend_selector::native_widgets::*;
171    pub use i_slint_core::accessibility::{
172        AccessibilityAction, AccessibleStringProperty, SupportedAccessibilityAction,
173    };
174    pub use i_slint_core::animations::{EasingCurve, animation_tick, current_tick};
175    pub use i_slint_core::api::LogicalPosition;
176    pub use i_slint_core::callbacks::Callback;
177    pub use i_slint_core::date_time::*;
178    pub use i_slint_core::detect_operating_system;
179    pub use i_slint_core::graphics::*;
180    pub use i_slint_core::input::{
181        FocusEvent, FocusReason, InputEventResult, KeyEvent, KeyEventResult, KeyboardModifiers,
182        MouseEvent, key_codes::Key,
183    };
184    pub use i_slint_core::item_tree::{
185        IndexRange, ItemTree, ItemTreeRefPin, ItemTreeVTable, ItemTreeWeak, register_item_tree,
186        unregister_item_tree,
187    };
188    pub use i_slint_core::item_tree::{
189        ItemTreeNode, ItemVisitorRefMut, ItemVisitorVTable, ItemWeak, TraversalOrder,
190        VisitChildrenResult, visit_item_tree,
191    };
192    pub use i_slint_core::items::{Transform, *};
193    pub use i_slint_core::layout::*;
194    pub use i_slint_core::lengths::{
195        LogicalLength, LogicalPoint, LogicalRect, logical_position_to_api,
196    };
197    pub use i_slint_core::menus::{Menu, MenuFromItemTree, MenuVTable};
198    pub use i_slint_core::model::*;
199    pub use i_slint_core::properties::{
200        ChangeTracker, Property, PropertyTracker, StateInfo, set_state_binding,
201    };
202    pub use i_slint_core::slice::Slice;
203    pub use i_slint_core::string::shared_string_from_number;
204    pub use i_slint_core::string::shared_string_from_number_fixed;
205    pub use i_slint_core::string::shared_string_from_number_precision;
206    pub use i_slint_core::timers::{Timer, TimerMode};
207    pub use i_slint_core::translations::{
208        set_bundled_languages, translate_from_bundle, translate_from_bundle_with_plural,
209    };
210    pub use i_slint_core::window::{
211        InputMethodRequest, WindowAdapter, WindowAdapterRc, WindowInner,
212    };
213    pub use i_slint_core::{Color, Coord, SharedString, SharedVector, format};
214    pub use i_slint_core::{ItemTreeVTable_static, MenuVTable_static};
215    pub use num_traits::float::Float;
216    pub use num_traits::ops::euclid::Euclid;
217    pub use once_cell::race::OnceBox;
218    pub use once_cell::unsync::OnceCell;
219    pub use pin_weak::rc::PinWeak;
220    pub use unicode_segmentation::UnicodeSegmentation;
221    pub use vtable::{self, *};
222
223    #[cfg(feature = "live-preview")]
224    pub use slint_interpreter::live_preview;
225}