makepad_platform/
cx.rs

1use {
2    makepad_futures::{executor, executor::{Executor, Spawner}},
3    std::{
4        collections::{
5            HashMap,
6            HashSet,
7        },
8        any::{Any, TypeId},
9        rc::Rc,
10        rc::Weak,
11        cell::RefCell,
12    },
13    crate::{
14        action::{ActionSend,ACTION_SENDER_GLOBAL},
15        makepad_live_compiler::{
16            LiveRegistry,
17            LiveFileChange
18        },
19        makepad_shader_compiler::ShaderRegistry,
20        draw_shader::CxDrawShaders,
21        draw_matrix::CxDrawMatrixPool,
22        os::CxOs,
23        debug::Debug,
24        display_context::DisplayContext,
25        performance_stats::PerformanceStats,
26        event::{
27            DrawEvent,
28            CxFingers,
29            CxDragDrop,
30            Event,
31            Trigger,
32            CxKeyboard,
33            NextFrame,
34        },
35        studio::StudioScreenshotRequest,
36        action::ActionsBuf,
37        cx_api::CxOsOp,
38        area::Area,
39        gpu_info::GpuInfo,
40        window::CxWindowPool,
41        draw_list::CxDrawListPool,
42        web_socket::WebSocket,
43        pass::CxPassPool,
44        texture::{CxTexturePool,TextureFormat,Texture,TextureUpdated},
45        geometry::{
46            Geometry,
47            CxGeometryPool,
48            GeometryFingerprint
49        },
50    }
51};
52
53//pub use makepad_shader_compiler::makepad_derive_live::*;
54//pub use makepad_shader_compiler::makepad_math::*;
55 
56pub struct Cx {
57    pub (crate) os_type: OsType,
58    pub in_makepad_studio: bool,
59    pub demo_time_repaint: bool,
60    pub (crate) gpu_info: GpuInfo,
61    pub (crate) xr_capabilities: XrCapabilities,
62    pub (crate) cpu_cores: usize,
63    pub null_texture: Texture,
64    pub windows: CxWindowPool,
65    pub passes: CxPassPool,
66    pub draw_lists: CxDrawListPool,
67    pub draw_matrices: CxDrawMatrixPool,
68    pub textures: CxTexturePool,
69    pub (crate) geometries: CxGeometryPool,
70    pub (crate) geometries_refs: HashMap<GeometryFingerprint, Weak<Geometry >>, 
71    
72    pub draw_shaders: CxDrawShaders,
73    
74    pub new_draw_event: DrawEvent,
75    
76    pub redraw_id: u64,
77    
78    pub (crate) repaint_id: u64,
79    pub (crate) event_id: u64,
80    pub (crate) timer_id: u64,
81    pub (crate) next_frame_id: u64,
82    
83    pub keyboard: CxKeyboard,
84    pub fingers: CxFingers,
85    pub (crate) ime_area: Area,
86    pub (crate) drag_drop: CxDragDrop,
87    
88    pub (crate) platform_ops: Vec<CxOsOp>,
89    
90    pub (crate) new_next_frames: HashSet<NextFrame>,
91    
92    pub new_actions: ActionsBuf,
93    
94    pub (crate) dependencies: HashMap<String, CxDependency>,
95    
96    pub (crate) triggers: HashMap<Area, Vec<Trigger >>,
97    
98    pub live_registry: Rc<RefCell<LiveRegistry >>,
99
100    pub (crate) live_file_change_receiver: std::sync::mpsc::Receiver<Vec<LiveFileChange>>,
101    pub (crate) live_file_change_sender: std::sync::mpsc::Sender<Vec<LiveFileChange >>,
102    
103    pub (crate) action_receiver: std::sync::mpsc::Receiver<ActionSend>,
104    
105    pub shader_registry: ShaderRegistry,
106    
107    pub os: CxOs,
108    // (cratethis cuts the compiletime of an end-user application in half
109    pub (crate) event_handler: Option<Box<dyn FnMut(&mut Cx, &Event) >>,
110    
111    pub (crate) globals: Vec<(TypeId, Box<dyn Any>)>,
112
113    pub (crate) self_ref: Option<Rc<RefCell<Cx>>>,
114    pub (crate) in_draw_event: bool,
115
116    pub display_context: DisplayContext,
117    
118    pub debug: Debug,
119
120    #[allow(dead_code)]
121    pub(crate) executor: Option<Executor>,
122    pub(crate) spawner: Spawner,
123    
124    pub(crate) studio_web_socket: Option<WebSocket>,
125    pub(crate) studio_http: String,
126    
127    pub performance_stats: PerformanceStats,
128    pub(crate) screenshot_requests: Vec<StudioScreenshotRequest>,
129    /// Event ID that triggered a widget query cache invalidation.
130    /// When Some(event_id), indicates that widgets should clear their query caches
131    /// on the next event loop cycle. This ensures all views process the cache clear
132    /// before it's reset to None.
133    /// 
134    /// This is primarily used when adaptive views change their active variant,
135    /// as the widget hierarchy changes require parent views to rebuild their widget queries.
136    pub widget_query_invalidation_event: Option<u64>,
137}
138
139#[derive(Clone)]
140pub struct CxRef(pub Rc<RefCell<Cx>>);
141
142pub struct CxDependency {
143    pub data: Option<Result<Rc<Vec<u8>>, String >>
144}
145#[derive(Clone, Debug)]
146pub struct AndroidParams {
147    pub cache_path: String,
148    pub density: f64,
149    pub is_emulator: bool,
150    pub has_xr_mode: bool,
151    pub android_version: String,
152    pub build_number: String,
153    pub kernel_version: String
154}
155
156#[derive(Clone, Debug)]
157pub struct OpenHarmonyParams {
158    pub files_dir:String,
159    pub cache_dir:String,
160    pub temp_dir:String,
161    pub device_type: String,
162    pub os_full_name: String,
163    pub display_density: f64,
164}
165
166#[derive(Clone, Debug)]
167pub struct WebParams {
168    pub protocol: String,
169    pub host: String,
170    pub hostname: String,
171    pub pathname: String,
172    pub search: String,
173    pub hash: String
174}
175
176#[derive(Clone, Debug)]
177pub struct LinuxWindowParams {
178    pub custom_window_chrome: bool,
179}
180
181#[derive(Clone, Debug)]
182pub enum OsType {
183    Unknown,
184    Windows,
185    Macos,
186    Ios,
187    Android(AndroidParams),
188    OpenHarmony(OpenHarmonyParams),
189    LinuxWindow (LinuxWindowParams),
190    LinuxDirect,
191    Web(WebParams)
192}
193
194#[derive(Default)]
195pub struct XrCapabilities {
196    pub ar_supported: bool,
197    pub vr_supported: bool,
198}
199
200impl OsType {
201    pub fn is_single_window(&self)->bool{
202        match self{
203            OsType::Web(_) => true,
204            OsType::Ios=>true,
205            OsType::Android(_) => true,
206            OsType::LinuxDirect=> true,
207            _=> false
208        }
209    }
210    pub fn is_web(&self) -> bool {
211        match self {
212            OsType::Web(_) => true,
213            _ => false
214        }
215    }
216    
217    pub fn has_xr_mode(&self) -> bool {
218        match self {
219            OsType::Android(o) => o.has_xr_mode,
220            _ => false
221        }
222    }
223    
224    pub fn get_cache_dir(&self)->Option<String>{
225        if let OsType::Android(params) = self {
226            Some(params.cache_path.clone())
227        }
228        else if let OsType::OpenHarmony(params) = self {
229            Some(params.cache_dir.clone())
230        }
231        else {
232            None
233        }
234    }
235}
236
237impl Cx {
238    pub fn new(event_handler: Box<dyn FnMut(&mut Cx, &Event)>) -> Self {
239        //#[cfg(any(target_arch = "wasm32", target_os = "android"))]
240        //crate::makepad_error_log::set_panic_hook();
241        // the null texture
242        let mut textures = CxTexturePool::default();
243        let null_texture = textures.alloc(TextureFormat::VecBGRAu8_32 {
244            width: 4,
245            height: 4,
246            data: Some(vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
247            updated: TextureUpdated::Full,
248        });
249        
250        let (executor, spawner) = executor::new_executor_and_spawner();
251        let (live_file_change_sender, live_file_change_receiver) = std::sync::mpsc::channel();
252        let (action_sender, action_receiver) = std::sync::mpsc::channel();
253        if let Ok(mut sender) = ACTION_SENDER_GLOBAL.lock(){
254            *sender = Some(action_sender);
255        }
256        
257        Self {
258            demo_time_repaint: false,
259            null_texture,
260            cpu_cores: 8,
261            in_makepad_studio: false,
262            in_draw_event: false,
263            os_type: OsType::Unknown,
264            gpu_info: Default::default(),
265            xr_capabilities: Default::default(),
266            
267            windows: Default::default(),
268            passes: Default::default(),
269            draw_lists: Default::default(),
270            draw_matrices: Default::default(),
271            geometries: Default::default(),
272            textures,
273            geometries_refs: Default::default(),
274            
275            draw_shaders: Default::default(),
276            
277            new_draw_event: Default::default(),
278            new_actions: Default::default(),
279            
280            redraw_id: 1,
281            event_id: 1,
282            repaint_id: 1,
283            timer_id: 1,
284            next_frame_id: 1,
285            
286            keyboard: Default::default(),
287            fingers: Default::default(),
288            drag_drop: Default::default(),
289            ime_area: Default::default(),
290            platform_ops: Default::default(),
291            studio_web_socket: None,
292            studio_http: "".to_string(),
293            new_next_frames: Default::default(),
294            
295            screenshot_requests: Default::default(),
296            
297            dependencies: Default::default(),
298            
299            triggers: Default::default(),
300            
301            live_registry: Rc::new(RefCell::new(LiveRegistry::default())),
302            
303            live_file_change_receiver,
304            live_file_change_sender,
305            action_receiver,
306            
307            shader_registry: ShaderRegistry::new(true),
308            
309            os: CxOs::default(),
310            
311            event_handler: Some(event_handler),
312            
313            debug: Default::default(),
314            
315            globals: Default::default(),
316
317            executor: Some(executor),
318            spawner,
319
320            self_ref: None,
321            performance_stats: Default::default(),
322
323            display_context: Default::default(),
324
325            widget_query_invalidation_event: None,
326        }
327    }
328}