Skip to main content

slint/
private_unstable_api.rs

1// Copyright © SixtyFPS GmbH <info@slint.dev>
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    i_slint_core::debug_log::log_message(i_slint_core::debug_log::LogMessage::new(
117        i_slint_core::debug_log::LogMessageSource::SlintCode,
118        None,
119        format_args!("{s}"),
120    ));
121}
122
123pub fn ensure_backend() -> Result<(), crate::PlatformError> {
124    i_slint_backend_selector::with_platform(|_b| {
125        // Nothing to do, just make sure a backend was created
126        Ok(())
127    })
128}
129
130/// Creates a new window to render components in.
131pub fn create_window_adapter()
132-> Result<alloc::rc::Rc<dyn i_slint_core::window::WindowAdapter>, crate::PlatformError> {
133    i_slint_backend_selector::with_platform(|b| b.create_window_adapter())
134}
135
136/// Wrapper around i_slint_core::translations::translate for the generated code
137pub fn translate(
138    origin: SharedString,
139    context: SharedString,
140    domain: SharedString,
141    args: Slice<SharedString>,
142    n: i32,
143    plural: SharedString,
144) -> SharedString {
145    i_slint_core::translations::translate(&origin, &context, &domain, args.as_slice(), n, &plural)
146}
147
148#[cfg(feature = "gettext")]
149pub fn init_translations(domain: &str, dirname: impl Into<std::path::PathBuf>) {
150    i_slint_core::translations::gettext_bindtextdomain(domain, dirname.into()).unwrap()
151}
152
153pub fn use_24_hour_format() -> bool {
154    i_slint_core::date_time::use_24_hour_format()
155}
156
157/// internal re_exports used by the macro generated
158pub mod re_exports {
159    pub use alloc::boxed::Box;
160    pub use alloc::rc::{Rc, Weak};
161    pub use alloc::string::String;
162    pub use alloc::{vec, vec::Vec};
163    pub use const_field_offset::{self, FieldOffsets, PinnedDrop};
164    pub use core::iter::FromIterator;
165    pub use core::option::{Option, Option::*};
166    pub use core::result::{Result, Result::*};
167    pub use i_slint_core::styled_text::{
168        StyledText, color_to_styled_text, parse_markdown, string_to_styled_text,
169    };
170    // This one is empty when Qt is not available, which triggers a warning
171    pub use euclid::approxeq::ApproxEq;
172    #[allow(unused_imports)]
173    pub use i_slint_backend_selector::native_widgets::*;
174    pub use i_slint_common::TranslationsBundled;
175    pub use i_slint_core::accessibility::{
176        AccessibilityAction, AccessibleStringProperty, SupportedAccessibilityAction,
177    };
178    pub use i_slint_core::animations::{EasingCurve, animation_tick, current_tick};
179    pub use i_slint_core::api::LogicalPosition;
180    pub use i_slint_core::callbacks::Callback;
181    pub use i_slint_core::context::SlintContext;
182    pub use i_slint_core::data_transfer::DataTransfer;
183    pub use i_slint_core::date_time::*;
184    pub use i_slint_core::detect_operating_system;
185    pub use i_slint_core::graphics::*;
186    pub use i_slint_core::input::{
187        FocusEvent, FocusReason, InputEventResult, KeyEvent, KeyEventResult, KeyboardModifiers,
188        Keys, MouseEvent, key_codes::Key, make_keys,
189    };
190    pub use i_slint_core::item_tree::{
191        IndexRange, ItemTree, ItemTreeRefPin, ItemTreeVTable, ItemTreeWeak,
192        ensure_item_tree_instantiated, register_item_tree, unregister_item_tree,
193    };
194    pub use i_slint_core::item_tree::{
195        ItemTreeNode, ItemVisitorRefMut, ItemVisitorVTable, ItemWeak, TraversalOrder,
196        VisitChildrenResult, visit_item_tree,
197    };
198    pub use i_slint_core::items::{Transform, *};
199    pub use i_slint_core::layout::*;
200    pub use i_slint_core::lengths::{
201        LogicalLength, LogicalPoint, LogicalRect, logical_position_to_api,
202    };
203    pub use i_slint_core::macos_bring_all_windows_to_front;
204    pub use i_slint_core::menus::{Menu, MenuFromItemTree, MenuVTable};
205    pub use i_slint_core::model::*;
206    pub use i_slint_core::open_url;
207    pub use i_slint_core::properties::{
208        ChangeTracker, Property, PropertyTracker, StateInfo, set_state_binding,
209    };
210    pub use i_slint_core::slice::Slice;
211    pub use i_slint_core::string::shared_string_from_number;
212    pub use i_slint_core::string::shared_string_from_number_fixed;
213    pub use i_slint_core::string::shared_string_from_number_precision;
214    pub use i_slint_core::timers::{Timer, TimerMode};
215    pub use i_slint_core::translations::{
216        set_bundled_languages, translate_from_bundle, translate_from_bundle_with_plural,
217    };
218    pub use i_slint_core::window::{
219        InputMethodRequest, WindowAdapter, WindowAdapterRc, WindowInner, WindowKind, accent_color,
220        context_for_root,
221    };
222    pub use i_slint_core::{
223        Color, Coord, SharedString, SharedVector, format, string::ToSharedString,
224        string::string_to_float,
225    };
226    pub use i_slint_core::{ItemTreeVTable_static, MenuVTable_static};
227    pub use num_traits::float::Float;
228    pub use num_traits::ops::euclid::Euclid;
229    pub use once_cell::race::OnceBox;
230    pub use once_cell::unsync::OnceCell;
231    pub use pin_weak::rc::PinWeak;
232    pub use unicode_segmentation::UnicodeSegmentation;
233    pub use vtable::{self, *};
234
235    #[cfg(feature = "live-preview")]
236    pub use i_slint_live_preview::live_component as live_preview;
237}