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//
17// The functions generic over `StrongItemTreeRef` serve global components;
18// regular components use the `*_erased` functions from `re_exports`, which
19// are not monomorphized per component.
20
21pub trait StrongItemTreeRef: Sized {
22    type Weak: Clone + 'static;
23    fn to_weak(&self) -> Self::Weak;
24    fn from_weak(weak: &Self::Weak) -> Option<Self>;
25}
26
27impl<C: 'static> StrongItemTreeRef for Pin<Rc<C>> {
28    type Weak = PinWeak<C>;
29    fn to_weak(&self) -> Self::Weak {
30        PinWeak::downgrade(self.clone())
31    }
32    fn from_weak(weak: &Self::Weak) -> Option<Self> {
33        weak.upgrade()
34    }
35}
36
37pub fn set_property_binding<
38    T: Clone + Default + 'static,
39    StrongRef: StrongItemTreeRef + 'static,
40>(
41    property: Pin<&Property<T>>,
42    component_strong: &StrongRef,
43    binding: fn(StrongRef) -> T,
44) {
45    let weak = component_strong.to_weak();
46    property.set_binding(move || {
47        <StrongRef as StrongItemTreeRef>::from_weak(&weak).map(binding).unwrap_or_default()
48    })
49}
50
51pub fn set_animated_property_binding<
52    T: Clone + i_slint_core::properties::InterpolatedPropertyValue + 'static,
53    StrongRef: StrongItemTreeRef + 'static,
54>(
55    property: Pin<&Property<T>>,
56    component_strong: &StrongRef,
57    binding: fn(StrongRef) -> T,
58    compute_animation_details: fn(
59        StrongRef,
60    )
61        -> (PropertyAnimation, Option<i_slint_core::animations::Instant>),
62) {
63    let weak_1 = component_strong.to_weak();
64    let weak_2 = weak_1.clone();
65    property.set_animated_binding(
66        move || binding(<StrongRef as StrongItemTreeRef>::from_weak(&weak_1).unwrap()),
67        move || {
68            compute_animation_details(<StrongRef as StrongItemTreeRef>::from_weak(&weak_2).unwrap())
69        },
70    )
71}
72
73pub fn set_property_state_binding<StrongRef: StrongItemTreeRef + 'static>(
74    property: Pin<&Property<StateInfo>>,
75    component_strong: &StrongRef,
76    binding: fn(StrongRef) -> i32,
77) {
78    let weak = component_strong.to_weak();
79    re_exports::set_state_binding(property, move || {
80        binding(<StrongRef as StrongItemTreeRef>::from_weak(&weak).unwrap())
81    })
82}
83
84pub fn set_callback_handler<
85    Arg: ?Sized + 'static,
86    Ret: Default + 'static,
87    StrongRef: StrongItemTreeRef + 'static,
88>(
89    callback: Pin<&Callback<Arg, Ret>>,
90    component_strong: &StrongRef,
91    handler: fn(StrongRef, &Arg) -> Ret,
92) {
93    let weak = component_strong.to_weak();
94    callback.set_handler(move |arg| {
95        handler(<StrongRef as StrongItemTreeRef>::from_weak(&weak).unwrap(), arg)
96    })
97}
98
99pub fn debug(s: SharedString) {
100    i_slint_core::debug_log::log_message(i_slint_core::debug_log::LogMessage::new(
101        i_slint_core::debug_log::LogMessageSource::SlintCode,
102        None,
103        format_args!("{s}"),
104    ));
105}
106
107pub fn ensure_backend() -> Result<(), crate::PlatformError> {
108    i_slint_backend_selector::with_platform(|_b| {
109        // Nothing to do, just make sure a backend was created
110        Ok(())
111    })
112}
113
114/// Creates a new window to render components in.
115pub fn create_window_adapter()
116-> Result<alloc::rc::Rc<dyn i_slint_core::window::WindowAdapter>, crate::PlatformError> {
117    i_slint_backend_selector::with_platform(|b| b.create_window_adapter())
118}
119
120/// Wrapper around i_slint_core::translations::translate for the generated code
121pub fn translate(
122    origin: SharedString,
123    context: SharedString,
124    domain: SharedString,
125    args: Slice<SharedString>,
126    n: i32,
127    plural: SharedString,
128) -> SharedString {
129    i_slint_core::translations::translate(&origin, &context, &domain, args.as_slice(), n, &plural)
130}
131
132#[cfg(feature = "gettext")]
133pub fn init_translations(domain: &str, dirname: impl Into<std::path::PathBuf>) {
134    i_slint_core::translations::gettext_bindtextdomain(domain, dirname.into()).unwrap()
135}
136
137pub fn use_24_hour_format() -> bool {
138    i_slint_core::date_time::use_24_hour_format()
139}
140
141/// internal re_exports used by the macro generated
142pub mod re_exports {
143    pub use alloc::boxed::Box;
144    pub use alloc::rc::{Rc, Weak};
145    pub use alloc::string::String;
146    pub use alloc::{vec, vec::Vec};
147    pub use const_field_offset::{self, FieldOffsets, PinnedDrop};
148    pub use core::iter::FromIterator;
149    pub use core::option::{Option, Option::*};
150    pub use core::result::{Result, Result::*};
151    pub use i_slint_core::styled_text::{
152        StyledText, color_to_styled_text, parse_markdown, string_to_styled_text,
153    };
154    // This one is empty when Qt is not available, which triggers a warning
155    pub use euclid::approxeq::ApproxEq;
156    #[allow(unused_imports)]
157    pub use i_slint_backend_selector::native_widgets::*;
158    pub use i_slint_common::TranslationsBundled;
159    pub use i_slint_core::accessibility::{
160        AccessibilityAction, AccessibleStringProperty, SupportedAccessibilityAction,
161    };
162    pub use i_slint_core::animations::{EasingCurve, animation_tick, current_tick};
163    pub use i_slint_core::api::LogicalPosition;
164    pub use i_slint_core::callbacks::Callback;
165    pub use i_slint_core::context::SlintContext;
166    pub use i_slint_core::cursor::MouseCursorInner;
167    pub use i_slint_core::data_transfer::DataTransfer;
168    pub use i_slint_core::date_time::*;
169    pub use i_slint_core::detect_operating_system;
170    pub use i_slint_core::graphics::*;
171    pub use i_slint_core::input::{
172        FocusEvent, FocusReason, InputEventResult, KeyEvent, KeyEventResult, KeyboardModifiers,
173        Keys, MouseEvent, key_codes::Key, make_keys,
174    };
175    pub use i_slint_core::item_tree::{
176        IndexRange, ItemTree, ItemTreeRc, ItemTreeRefPin, ItemTreeVTable, ItemTreeWeak,
177        ensure_item_tree_instantiated, register_item_tree, unregister_item_tree,
178    };
179    pub use i_slint_core::item_tree::{
180        ItemTreeNode, ItemVisitorRefMut, ItemVisitorVTable, ItemWeak, TraversalOrder,
181        VisitChildrenResult, visit_item_tree,
182    };
183    pub use i_slint_core::items::{Transform, *};
184    pub use i_slint_core::layout::*;
185    pub use i_slint_core::lengths::{
186        LogicalLength, LogicalPoint, LogicalRect, logical_position_to_api,
187    };
188    pub use i_slint_core::macos_bring_all_windows_to_front;
189    pub use i_slint_core::menus::{Menu, MenuFromItemTree, MenuVTable};
190    pub use i_slint_core::model::*;
191    pub use i_slint_core::open_url;
192    pub use i_slint_core::properties::{
193        ChangeTracker, Property, PropertyTracker, StateInfo, change_tracker_init_erased,
194        set_animated_property_binding_erased, set_callback_handler_erased,
195        set_property_binding_erased, set_property_state_binding_erased, set_state_binding,
196    };
197    pub use i_slint_core::slice::Slice;
198    pub use i_slint_core::string::shared_string_from_number;
199    pub use i_slint_core::string::shared_string_from_number_fixed;
200    pub use i_slint_core::string::shared_string_from_number_precision;
201    pub use i_slint_core::string::shared_string_from_number_unlocalized;
202    pub use i_slint_core::timers::{Timer, TimerMode};
203    pub use i_slint_core::translations::{
204        set_bundled_languages, translate_from_bundle, translate_from_bundle_with_plural,
205    };
206    pub use i_slint_core::window::{
207        InputMethodRequest, WindowAdapter, WindowAdapterRc, WindowInner, WindowKind, accent_color,
208        context_for_root,
209    };
210    pub use i_slint_core::{
211        Color, Coord, SharedString, SharedVector, format, string::ToSharedString,
212        string::string_to_float,
213    };
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 i_slint_live_preview::live_component as live_preview;
225}