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
4use std::{collections::HashMap, rc::Rc};
5
6use itertools::Itertools;
7use lsp_types::Url;
8use smol_str::SmolStr;
9
10use i_slint_compiler::{
11 expression_tree, langtype, literals, object_tree,
12 parser::{syntax_nodes, SyntaxKind, TextRange},
13};
14
15use slint::{SharedString, VecModel};
16
17use crate::{
18 common,
19 preview::{properties, ui},
20 util,
21};
22
23pub fn map_properties_to_ui(
24 document_cache: &common::DocumentCache,
25 properties: Option<properties::QueryPropertyResponse>,
26) -> Option<(
27 ui::ElementInformation,
28 HashMap<SmolStr, ui::PropertyDeclaration>,
29 ui::PropertyGroupModel,
30)> {
31 use std::cmp::Ordering;
32
33 let properties = &properties?;
34 let element = properties.element.as_ref()?;
35
36 let raw_source_uri = Url::parse(&properties.source_uri).ok()?;
37 let source_uri: SharedString = raw_source_uri.to_string().into();
38 let source_version = properties.source_version;
39
40 let mut property_groups: HashMap<(SmolStr, u32), Vec<ui::PropertyInformation>> = HashMap::new();
41
42 let mut declarations = HashMap::new();
43
44 fn property_group_from(
45 groups: &mut HashMap<(SmolStr, u32), Vec<ui::PropertyInformation>>,
46 name: SmolStr,
47 group_priority: u32,
48 property: ui::PropertyInformation,
49 ) {
50 let entry = groups.entry((name.clone(), group_priority));
51 entry.and_modify(|e| e.push(property.clone())).or_insert(vec![property]);
52 }
53
54 for pi in &properties.properties {
55 let defined_at =
56 map_property_definition(&pi.defined_at).unwrap_or(ui::PropertyDefinition {
57 definition_range: ui::Range { start: 0, end: 0 },
58 selection_range: ui::Range { start: 0, end: 0 },
59 expression_range: ui::Range { start: 0, end: 0 },
60 expression_value: String::new().into(),
61 });
62 let declared_at =
63 map_property_declaration(document_cache, &pi.declared_at, defined_at.clone())
64 .unwrap_or(ui::PropertyDeclaration {
65 defined_at,
66 source_path: String::new().into(),
67 source_version: -1,
68 range: ui::Range { start: 0, end: 0 },
69 });
70
71 declarations.insert(pi.name.clone(), declared_at);
72
73 let value = simplify_value(document_cache, pi);
74
75 property_group_from(
76 &mut property_groups,
77 pi.group.clone(),
78 pi.group_priority,
79 ui::PropertyInformation {
80 name: pi.name.as_str().into(),
81 type_name: pi.ty.to_string().into(),
82 value,
83 display_priority: i32::try_from(pi.priority).unwrap(),
84 },
85 );
86 }
87
88 let keys = property_groups
89 .keys()
90 .sorted_by(|a, b| match a.1.cmp(&b.1) {
91 Ordering::Less => Ordering::Less,
92 Ordering::Equal => a.0.cmp(&b.0),
93 Ordering::Greater => Ordering::Greater,
94 })
95 .cloned()
96 .collect::<Vec<_>>();
97
98 Some((
99 ui::ElementInformation {
100 id: element.id.as_str().into(),
101 type_name: element.type_name.as_str().into(),
102 source_uri,
103 source_version,
104 range: ui::to_ui_range(element.range)?,
105 },
106 declarations,
107 Rc::new(VecModel::from(
108 keys.iter()
109 .map(|k| ui::PropertyGroup {
110 group_name: k.0.as_str().into(),
111 properties: Rc::new(VecModel::from({
112 let mut v = property_groups.remove(k).unwrap();
113 v.sort_by(|a, b| match a.display_priority.cmp(&b.display_priority) {
114 Ordering::Less => Ordering::Less,
115 Ordering::Equal => a.name.cmp(&b.name),
116 Ordering::Greater => Ordering::Greater,
117 });
118 v
119 }))
120 .into(),
121 })
122 .collect::<Vec<_>>(),
123 ))
124 .into(),
125 ))
126}
127
128fn map_property_declaration(
129 document_cache: &common::DocumentCache,
130 declared_at: &Option<properties::DeclarationInformation>,
131 defined_at: ui::PropertyDefinition,
132) -> Option<ui::PropertyDeclaration> {
133 let da: &DeclarationInformation = declared_at.as_ref()?;
134 let source_version: i32 = document_cache.document_version_by_path(&da.path).unwrap_or(default:-1);
135 let pos: TextRange = TextRange::new(start:da.start_position, end:da.start_position);
136
137 Some(ui::PropertyDeclaration {
138 defined_at,
139 source_path: da.path.to_string_lossy().to_string().into(),
140 source_version,
141 range: ui::to_ui_range(pos)?,
142 })
143}
144
145fn map_property_definition(
146 defined_at: &Option<properties::DefinitionInformation>,
147) -> Option<ui::PropertyDefinition> {
148 let da: &DefinitionInformation = defined_at.as_ref()?;
149
150 Some(ui::PropertyDefinition {
151 definition_range: ui::to_ui_range(da.property_definition_range)?,
152 selection_range: ui::to_ui_range(da.selection_range)?,
153 expression_range: ui::to_ui_range(da.code_block_or_expression.text_range())?,
154 expression_value: da.code_block_or_expression.text().to_string().into(),
155 })
156}
157
158fn convert_number_literal(
159 node: &syntax_nodes::Expression,
160) -> Option<(f64, i_slint_compiler::expression_tree::Unit)> {
161 if let Some(unary: &UnaryOpExpression) = &node.UnaryOpExpression() {
162 let factor: f64 = match unary.first_token().unwrap().text() {
163 "-" => -1.0,
164 "+" => 1.0,
165 _ => return None,
166 };
167 convert_number_literal(&unary.Expression()).map(|(v: f64, u: Unit)| (factor * v, u))
168 } else {
169 let literal: SmolStr = node.child_text(SyntaxKind::NumberLiteral)?;
170 let expr: Expression = literals::parse_number_literal(literal).ok()?;
171
172 match expr {
173 i_slint_compiler::expression_tree::Expression::NumberLiteral(value: f64, unit: Unit) => {
174 Some((value, unit))
175 }
176 _ => None,
177 }
178 }
179}
180
181fn extract_color(
182 expression: &syntax_nodes::Expression,
183 kind: ui::PropertyValueKind,
184 value: &mut ui::PropertyValue,
185) -> bool {
186 if let Some(text: str) = expression.child_text(SyntaxKind::ColorLiteral) {
187 if let Some(color: Color) = ui::string_to_color(&text) {
188 value.display_string = text.as_str().into();
189 value.kind = kind;
190 value.value_brush = slint::Brush::SolidColor(color);
191 value.gradient_stops =
192 Rc::new(VecModel::from(vec![ui::GradientStop { color, position: 0.5 }])).into();
193 return true;
194 }
195 }
196 false
197}
198
199fn set_default_brush(
200 kind: ui::PropertyValueKind,
201 def_val: Option<&expression_tree::Expression>,
202 value: &mut ui::PropertyValue,
203) {
204 use expression_tree::Expression;
205 value.kind = kind;
206 if let Some(mut def_val: &Expression) = def_val {
207 if let Expression::Cast { from: &Box, .. } = def_val {
208 def_val = from;
209 }
210 if let Expression::NumberLiteral(v: &f64, _) = def_val {
211 value.value_brush = slint::Brush::SolidColor(slint::Color::from_argb_encoded(*v as _));
212 return;
213 }
214 }
215 value.brush_kind = ui::BrushKind::Solid;
216 let text: &'static str = "#00000000";
217 let color: Color = ui::string_to_color(text).unwrap();
218 value.gradient_stops =
219 Rc::new(VecModel::from(vec![ui::GradientStop { color, position: 0.5 }])).into();
220 value.display_string = text.into();
221 value.value_brush = slint::Brush::SolidColor(color);
222}
223
224fn extract_tr_data(tr_node: &syntax_nodes::AtTr, value: &mut ui::PropertyValue) {
225 let Some(text) = tr_node
226 .child_text(SyntaxKind::StringLiteral)
227 .and_then(|s| i_slint_compiler::literals::unescape_string(&s))
228 else {
229 return;
230 };
231
232 let context = tr_node
233 .TrContext()
234 .and_then(|n| n.child_text(SyntaxKind::StringLiteral))
235 .and_then(|s| literals::unescape_string(&s))
236 .unwrap_or_default();
237 let plural = tr_node
238 .TrPlural()
239 .and_then(|n| n.child_text(SyntaxKind::StringLiteral))
240 .and_then(|s| literals::unescape_string(&s))
241 .unwrap_or_default();
242 let plural_expression = tr_node
243 .TrPlural()
244 .and_then(|n| n.child_node(SyntaxKind::Expression))
245 .and_then(|e| e.child_node(SyntaxKind::QualifiedName))
246 .map(|n| object_tree::QualifiedTypeName::from_node(n.into()))
247 .map(|qtn| qtn.to_string());
248
249 // We have expressions -> Edit as code
250 if tr_node.Expression().next().is_none() && (plural.is_empty() || plural_expression.is_some()) {
251 value.kind = ui::PropertyValueKind::String;
252 value.is_translatable = true;
253 value.tr_context = context.as_str().into();
254 value.tr_plural = plural.as_str().into();
255 value.tr_plural_expression = plural_expression.unwrap_or_default().into();
256 value.value_string = text.as_str().into();
257 }
258}
259
260fn is_gradient_too_complex(expression: &syntax_nodes::AtGradient) -> bool {
261 let is_radial = expression
262 .child_token(SyntaxKind::Identifier)
263 .is_some_and(|t| t.text().trim().replace('_', "-") == "radial-gradient");
264
265 expression.Expression().any(|e| {
266 match e
267 .children_with_tokens()
268 .next()
269 .expect("An expression needs to contain at least one node or token")
270 {
271 i_slint_compiler::parser::NodeOrToken::Node(syntax_node) => match syntax_node.kind() {
272 SyntaxKind::QualifiedName => {
273 if is_radial && syntax_node.text().to_string().trim() == "circle" {
274 false
275 } else if let Some(first_identifier) =
276 syntax_node.child_token(SyntaxKind::Identifier)
277 {
278 first_identifier.text().trim() != "Colors"
279 } else {
280 true
281 }
282 }
283 _ => true,
284 },
285 i_slint_compiler::parser::NodeOrToken::Token(syntax_token) => {
286 !matches!(syntax_token.kind(), SyntaxKind::NumberLiteral | SyntaxKind::ColorLiteral)
287 }
288 }
289 })
290}
291
292#[derive(Default)]
293struct NumberValue {
294 value: f64,
295 unit: expression_tree::Unit,
296 normalized_value: f64,
297}
298
299fn extract_number_from_expression_tree(
300 expression: &expression_tree::Expression,
301) -> Option<NumberValue> {
302 match expression {
303 expression_tree::Expression::NumberLiteral(v, u) => {
304 Some(NumberValue { value: *v, unit: *u, normalized_value: u.normalize(*v) })
305 }
306 expression_tree::Expression::Cast { from, to } => {
307 if *to == langtype::Type::Float32 {
308 extract_number_from_expression_tree(from.as_ref())
309 } else {
310 None
311 }
312 }
313 expression_tree::Expression::BinaryExpression { lhs, rhs, op } => {
314 let lhs = extract_number_from_expression_tree(lhs.as_ref())?;
315 let rhs = extract_number_from_expression_tree(rhs.as_ref())?;
316
317 let value = match op {
318 '+' => Some(lhs.value + rhs.value),
319 '-' => Some(lhs.value - rhs.value),
320 '*' => Some(lhs.value * rhs.value),
321 '/' => Some(lhs.value / rhs.value),
322 _ => None,
323 };
324
325 value.map(|v| NumberValue {
326 value: v,
327 unit: lhs.unit,
328 normalized_value: lhs.unit.normalize(v),
329 })
330 }
331 _ => None,
332 }
333}
334
335fn extract_color_from_expression_tree(
336 expression: &expression_tree::Expression,
337) -> Option<slint::Color> {
338 match expression {
339 expression_tree::Expression::NumberLiteral(v: &f64, _) => {
340 Some(slint::Color::from_argb_encoded(*v as u32))
341 }
342 expression_tree::Expression::Cast { from: &Box, to: &Type } => {
343 if *to == langtype::Type::Color {
344 extract_color_from_expression_tree(expression:from.as_ref())
345 } else {
346 None
347 }
348 }
349 _ => None,
350 }
351}
352
353fn extract_gradient(
354 document_cache: &common::DocumentCache,
355 expression: &syntax_nodes::AtGradient,
356 value: &mut ui::PropertyValue,
357) {
358 if is_gradient_too_complex(expression) {
359 return;
360 }
361
362 let Some(resolved_expression) =
363 util::with_lookup_ctx(document_cache, expression.clone().into(), |ctx| {
364 expression_tree::Expression::from_at_gradient(expression.clone(), ctx)
365 })
366 else {
367 return;
368 };
369
370 fn parse_stops(
371 stops: &[(expression_tree::Expression, expression_tree::Expression)],
372 ) -> Vec<ui::GradientStop> {
373 stops
374 .iter()
375 .filter_map(|(c, p)| {
376 Some(ui::GradientStop {
377 color: extract_color_from_expression_tree(c)?,
378 position: extract_number_from_expression_tree(p)?.normalized_value as f32,
379 })
380 })
381 .collect::<Vec<_>>()
382 }
383
384 let stops = match resolved_expression {
385 expression_tree::Expression::LinearGradient { angle, stops } => {
386 let angle = extract_number_from_expression_tree(angle.as_ref());
387 value.value_float = angle.unwrap_or_default().normalized_value as f32;
388 value.display_string = "Linear Gradient".into();
389 value.brush_kind = ui::BrushKind::Linear;
390
391 parse_stops(&stops)
392 }
393 expression_tree::Expression::RadialGradient { stops } => {
394 value.display_string = "Radial Gradient".into();
395 value.brush_kind = ui::BrushKind::Radial;
396 parse_stops(&stops)
397 }
398
399 _ => vec![],
400 };
401
402 value.gradient_stops = Rc::new(VecModel::from(stops)).into();
403 value.value_brush = super::create_brush(
404 value.brush_kind,
405 value.value_float,
406 slint::Color::default(),
407 value.gradient_stops.clone(),
408 );
409 value.kind = ui::PropertyValueKind::Brush;
410}
411
412fn simplify_value(
413 document_cache: &common::DocumentCache,
414 prop_info: &properties::PropertyInformation,
415) -> ui::PropertyValue {
416 use i_slint_compiler::expression_tree::Unit;
417 use langtype::Type;
418
419 let code_block_or_expression =
420 prop_info.defined_at.as_ref().map(|da| da.code_block_or_expression.clone());
421 let expression = code_block_or_expression.as_ref().and_then(|cbe| cbe.expression());
422
423 let mut value = ui::PropertyValue {
424 code: code_block_or_expression
425 .as_ref()
426 .map(|cbe| cbe.text().to_string())
427 .unwrap_or_default()
428 .into(),
429 kind: ui::PropertyValueKind::Code,
430 ..Default::default()
431 };
432
433 let def_val = prop_info.default_value.as_ref();
434
435 match &prop_info.ty {
436 Type::Float32 => extract_value_with_unit(&expression, def_val, &[], &mut value),
437 Type::Duration => {
438 extract_value_with_unit(&expression, def_val, &[Unit::S, Unit::Ms], &mut value)
439 }
440 Type::PhysicalLength | Type::LogicalLength | Type::Rem => extract_value_with_unit(
441 &expression,
442 def_val,
443 &[Unit::Px, Unit::Cm, Unit::Mm, Unit::In, Unit::Pt, Unit::Phx, Unit::Rem],
444 &mut value,
445 ),
446 Type::Angle => extract_value_with_unit(
447 &expression,
448 def_val,
449 &[Unit::Deg, Unit::Grad, Unit::Turn, Unit::Rad],
450 &mut value,
451 ),
452 Type::Percent => {
453 extract_value_with_unit(&expression, def_val, &[Unit::Percent], &mut value)
454 }
455 Type::Int32 => {
456 if let Some(expression) = expression {
457 if let Some((v, unit)) = convert_number_literal(&expression) {
458 if unit == i_slint_compiler::expression_tree::Unit::None {
459 value.display_string = slint::format!("{v}");
460 value.kind = ui::PropertyValueKind::Integer;
461 value.value_int = v as i32;
462 }
463 }
464 } else if value.code.is_empty() {
465 value.kind = ui::PropertyValueKind::Integer;
466 }
467 }
468 Type::Color => {
469 if let Some(expression) = expression {
470 extract_color(&expression, ui::PropertyValueKind::Color, &mut value);
471 // TODO: Extract `Foo.bar` as Palette `Foo`, entry `bar`.
472 // This makes no sense right now, as we have no way to get any
473 // information on the palettes.
474 } else if value.code.is_empty() {
475 set_default_brush(ui::PropertyValueKind::Color, def_val, &mut value);
476 }
477 }
478 Type::Brush => {
479 if let Some(expression) = expression {
480 if let Some(gradient) = expression.AtGradient() {
481 extract_gradient(document_cache, &gradient, &mut value);
482 } else {
483 extract_color(&expression, ui::PropertyValueKind::Brush, &mut value);
484 }
485 } else if value.code.is_empty() {
486 set_default_brush(ui::PropertyValueKind::Brush, def_val, &mut value);
487 }
488 }
489 Type::Bool => {
490 if let Some(expression) = expression {
491 let qualified_name =
492 expression.QualifiedName().map(|qn| qn.text().to_string()).unwrap_or_default();
493 if ["true", "false"].contains(&qualified_name.as_str()) {
494 value.kind = ui::PropertyValueKind::Boolean;
495 value.value_bool = &qualified_name == "true";
496 }
497 } else if value.code.is_empty() {
498 if let Some(expression_tree::Expression::BoolLiteral(v)) = def_val {
499 value.value_bool = *v;
500 }
501 value.kind = ui::PropertyValueKind::Boolean;
502 }
503 }
504 Type::String => {
505 if let Some(expression) = &expression {
506 if let Some(text) = expression
507 .child_text(SyntaxKind::StringLiteral)
508 .and_then(|s| i_slint_compiler::literals::unescape_string(&s))
509 {
510 value.kind = ui::PropertyValueKind::String;
511 value.value_string = text.as_str().into();
512 } else if let Some(tr_node) = &expression.AtTr() {
513 extract_tr_data(tr_node, &mut value)
514 }
515 } else if value.code.is_empty() {
516 if let Some(expression_tree::Expression::StringLiteral(v)) = def_val {
517 value.value_string = v.as_str().into();
518 }
519 value.kind = ui::PropertyValueKind::String;
520 }
521 }
522 Type::Enumeration(enumeration) => {
523 value.kind = ui::PropertyValueKind::Enum;
524 value.value_string = enumeration.name.as_str().into();
525 value.default_selection = i32::try_from(enumeration.default_value).unwrap_or_default();
526 value.visual_items = Rc::new(VecModel::from(
527 enumeration
528 .values
529 .iter()
530 .map(|s| SharedString::from(s.as_str()))
531 .collect::<Vec<_>>(),
532 ))
533 .into();
534
535 if let Some(expression) = expression {
536 if let Some(text) = expression
537 .child_node(SyntaxKind::QualifiedName)
538 .map(|n| i_slint_compiler::object_tree::QualifiedTypeName::from_node(n.into()))
539 .map(|n| {
540 let n_str = n.to_string();
541 n_str
542 .strip_prefix(&format!("{}.", enumeration.name))
543 .map(|s| s.to_string())
544 .unwrap_or(n_str)
545 })
546 .map(|s| s.to_string())
547 {
548 value.value_int = enumeration
549 .values
550 .iter()
551 .position(|v| v == &text)
552 .and_then(|v| i32::try_from(v).ok())
553 .unwrap_or_default();
554 }
555 } else if let Some(expression_tree::Expression::EnumerationValue(v)) = def_val {
556 value.value_int = v.value as i32
557 }
558 }
559 _ => {}
560 }
561
562 value
563}
564
565fn extract_value_with_unit_impl(
566 expression: &Option<syntax_nodes::Expression>,
567 def_val: Option<&expression_tree::Expression>,
568 code: &str,
569 units: &[i_slint_compiler::expression_tree::Unit],
570) -> Option<(ui::PropertyValueKind, f32, i32, String)> {
571 if let Some(expression) = expression {
572 if let Some((value, unit)) = convert_number_literal(expression) {
573 let index = units.iter().position(|u| u == &unit).or_else(|| {
574 (units.is_empty() && unit == i_slint_compiler::expression_tree::Unit::None)
575 .then_some(0_usize)
576 })?;
577
578 return Some((
579 ui::PropertyValueKind::Float,
580 value as f32,
581 index as i32,
582 unit.to_string(),
583 ));
584 }
585 } else if code.is_empty() {
586 if let Some(expression_tree::Expression::NumberLiteral(value, unit)) = def_val {
587 let index = units.iter().position(|u| u == unit).unwrap_or(0);
588 return Some((
589 ui::PropertyValueKind::Float,
590 *value as f32,
591 index as i32,
592 String::new(),
593 ));
594 } else {
595 // FIXME: if def_vale is Some but not a NumberLiteral, we should not show "0"
596 return Some((ui::PropertyValueKind::Float, 0.0, 0, String::new()));
597 }
598 }
599
600 None
601}
602
603fn extract_value_with_unit(
604 expression: &Option<syntax_nodes::Expression>,
605 def_val: Option<&expression_tree::Expression>,
606 units: &[expression_tree::Unit],
607 value: &mut ui::PropertyValue,
608) {
609 let Some((kind: PropertyValueKind, v: f32, index: i32, unit: String)) =
610 extract_value_with_unit_impl(expression, def_val, &value.code, units)
611 else {
612 return;
613 };
614
615 value.display_string = slint::format!("{v}{unit}");
616 value.kind = kind;
617 value.value_float = v;
618 value.visual_items = ui::unit_model(units);
619 value.value_int = index
620}
621
622#[cfg(test)]
623mod tests {
624 use slint::{Model, SharedString};
625
626 use crate::{
627 common,
628 preview::{properties, ui},
629 test::loaded_document_cache,
630 };
631
632 fn properties_at_position(
633 source: &str,
634 line: u32,
635 character: u32,
636 ) -> Option<(
637 common::ElementRcNode,
638 Vec<properties::PropertyInformation>,
639 common::DocumentCache,
640 lsp_types::Url,
641 )> {
642 let (dc, url, _) = loaded_document_cache(source.to_string());
643 if let Some((e, p)) =
644 properties::tests::properties_at_position_in_cache(line, character, &dc, &url)
645 {
646 Some((e, p, dc, url))
647 } else {
648 None
649 }
650 }
651
652 fn property_conversion_test(contents: &str, property_line: u32) -> ui::PropertyValue {
653 let (_, pi, dc, _) = properties_at_position(contents, property_line, 30).unwrap();
654 let test1 = pi.iter().find(|pi| pi.name == "test1").unwrap();
655 super::simplify_value(&dc, test1)
656 }
657
658 #[test]
659 fn test_property_bool() {
660 let result =
661 property_conversion_test(r#"export component Test { in property <bool> test1; }"#, 0);
662 assert_eq!(result.kind, ui::PropertyValueKind::Boolean);
663 assert!(!result.value_bool);
664 assert!(result.code.is_empty());
665
666 let result = property_conversion_test(
667 r#"export component Test { in property <bool> test1: true; }"#,
668 0,
669 );
670 assert_eq!(result.kind, ui::PropertyValueKind::Boolean);
671 assert!(result.value_bool);
672 assert!(!result.code.is_empty());
673
674 let result = property_conversion_test(
675 r#"export component Test { in property <bool> test1: false; }"#,
676 0,
677 );
678 assert_eq!(result.kind, ui::PropertyValueKind::Boolean);
679 assert!(!result.value_bool);
680 assert!(!result.code.is_empty());
681
682 let result = property_conversion_test(
683 r#"export component Test { in property <bool> test1: 1.1.round() == 1.1.floor(); }"#,
684 0,
685 );
686 assert_eq!(result.kind, ui::PropertyValueKind::Code);
687 assert!(!result.value_bool);
688 assert!(!result.code.is_empty());
689 }
690
691 #[test]
692 fn test_property_string() {
693 let result =
694 property_conversion_test(r#"export component Test { in property <string> test1; }"#, 0);
695 assert_eq!(result.kind, ui::PropertyValueKind::String);
696 assert!(!result.is_translatable);
697 assert_eq!(result.tr_context, "");
698 assert_eq!(result.tr_plural, "");
699 assert!(!result.value_bool);
700 assert!(result.code.is_empty());
701
702 let result = property_conversion_test(
703 r#"export component Test { in property <string> test1: ""; }"#,
704 0,
705 );
706 assert_eq!(result.kind, ui::PropertyValueKind::String);
707 assert!(!result.is_translatable);
708 assert_eq!(result.tr_context, "");
709 assert_eq!(result.tr_plural, "");
710 assert!(!result.value_bool);
711 assert!(!result.code.is_empty());
712
713 let result = property_conversion_test(
714 r#"export component Test { in property <string> test1: "string"; }"#,
715 0,
716 );
717 assert_eq!(result.kind, ui::PropertyValueKind::String);
718 assert!(!result.is_translatable);
719 assert_eq!(result.tr_context, "");
720 assert_eq!(result.tr_plural, "");
721 assert!(!result.value_bool);
722 assert!(!result.code.is_empty());
723
724 let result = property_conversion_test(
725 r#"export component Test { in property <string> test1: "" + "test"); }"#,
726 0,
727 );
728 assert_eq!(result.kind, ui::PropertyValueKind::Code);
729 assert!(!result.is_translatable);
730 assert_eq!(result.tr_context, "");
731 assert_eq!(result.tr_plural, "");
732 assert!(!result.value_bool);
733 assert!(!result.code.is_empty());
734 }
735
736 #[test]
737 fn test_property_tr_string() {
738 let result = property_conversion_test(
739 r#"export component Test { in property <string> test1: @tr("Context" => "test"); }"#,
740 0,
741 );
742 assert_eq!(result.kind, ui::PropertyValueKind::String);
743 assert_eq!(result.value_string, "test");
744 assert!(result.is_translatable);
745 assert_eq!(result.tr_context, "Context");
746 assert_eq!(result.tr_plural, "");
747 assert!(!result.code.is_empty());
748
749 let result = property_conversion_test(
750 r#"export component Test {
751 property <int> test: 42;
752 in property <string> test1: @tr("{n} string" | "{n} strings" % test);
753}"#,
754 2,
755 );
756 assert_eq!(result.kind, ui::PropertyValueKind::String);
757 assert!(result.is_translatable);
758 assert_eq!(result.tr_context, "");
759 assert_eq!(result.tr_plural, "{n} strings");
760 assert_eq!(result.tr_plural_expression, "test");
761 assert_eq!(result.value_string, "{n} string");
762 assert!(!result.code.is_empty());
763
764 let result = property_conversion_test(
765 r#"export component Test {
766 property <int> test: 42;
767 in property <string> test1: @tr("{n} string" | "{n} strings" % self.test);
768}"#,
769 2,
770 );
771 assert_eq!(result.kind, ui::PropertyValueKind::String);
772 assert!(result.is_translatable);
773 assert_eq!(result.tr_context, "");
774 assert_eq!(result.tr_plural, "{n} strings");
775 assert_eq!(result.tr_plural_expression, "self.test");
776 assert_eq!(result.value_string, "{n} string");
777 assert!(!result.code.is_empty());
778
779 // `15` is not a qualified name
780 let result = property_conversion_test(
781 r#"export component Test { in property <string> test1: @tr("{n} string" | "{n} strings" % 15); }"#,
782 0,
783 );
784 assert_eq!(result.kind, ui::PropertyValueKind::Code);
785 assert!(!result.is_translatable);
786 assert_eq!(result.tr_context, "");
787 assert_eq!(result.tr_plural, "");
788 assert_eq!(result.value_string, "");
789 assert!(!result.code.is_empty());
790
791 let result = property_conversion_test(
792 r#"export component Test { in property <string> test1: @tr("" + "test"); }"#,
793 0,
794 );
795 assert_eq!(result.kind, ui::PropertyValueKind::Code);
796 assert!(!result.is_translatable);
797 assert_eq!(result.tr_context, "");
798 assert_eq!(result.tr_plural, "");
799 assert_eq!(result.value_string, "");
800 assert!(!result.code.is_empty());
801 let result = property_conversion_test(
802 r#"export component Test { in property <string> test1: @tr("width {}", self.width()); }"#,
803 0,
804 );
805 assert_eq!(result.kind, ui::PropertyValueKind::Code);
806 assert!(!result.is_translatable);
807 assert_eq!(result.tr_context, "");
808 assert_eq!(result.tr_plural, "");
809 assert_eq!(result.value_string, "");
810 assert!(!result.code.is_empty());
811 }
812
813 #[test]
814 fn test_property_enum() {
815 let result = property_conversion_test(
816 r#"export component Test { in property <ImageFit> test1: ImageFit.preserve; }"#,
817 0,
818 );
819 assert_eq!(result.kind, ui::PropertyValueKind::Enum);
820 assert_eq!(result.value_string, "ImageFit");
821 assert_eq!(result.value_int, 3);
822 assert_eq!(result.default_selection, 0);
823 assert!(!result.is_translatable);
824
825 assert_eq!(result.visual_items.row_count(), 4);
826
827 let result = property_conversion_test(
828 r#"export component Test { in property <ImageFit> test1: ImageFit . /* abc */ preserve; }"#,
829 0,
830 );
831 assert_eq!(result.kind, ui::PropertyValueKind::Enum);
832 assert_eq!(result.value_string, "ImageFit");
833 assert_eq!(result.value_int, 3);
834 assert_eq!(result.default_selection, 0);
835 assert!(!result.is_translatable);
836
837 assert_eq!(result.visual_items.row_count(), 4);
838
839 let result = property_conversion_test(
840 r#"export component Test { in property <ImageFit> test1: /* abc */ preserve; }"#,
841 0,
842 );
843 assert_eq!(result.kind, ui::PropertyValueKind::Enum);
844 assert_eq!(result.value_string, "ImageFit");
845 assert_eq!(result.value_int, 3);
846 assert_eq!(result.default_selection, 0);
847 assert!(!result.is_translatable);
848
849 assert_eq!(result.visual_items.row_count(), 4);
850
851 let result = property_conversion_test(
852 r#"enum Foobar { foo, bar }
853export component Test { in property <Foobar> test1: Foobar.bar; }"#,
854 1,
855 );
856 assert_eq!(result.kind, ui::PropertyValueKind::Enum);
857 assert_eq!(result.value_string, "Foobar");
858 assert_eq!(result.value_int, 1);
859 assert_eq!(result.default_selection, 0);
860 assert!(!result.is_translatable);
861
862 assert_eq!(result.visual_items.row_count(), 2);
863 assert_eq!(result.visual_items.row_data(0), Some(SharedString::from("foo")));
864 assert_eq!(result.visual_items.row_data(1), Some(SharedString::from("bar")));
865
866 let result = property_conversion_test(
867 r#"enum Foobar { foo, bar }
868export component Test { in property <Foobar> test1; }"#,
869 1,
870 );
871 assert_eq!(result.kind, ui::PropertyValueKind::Enum);
872 assert_eq!(result.value_string, "Foobar");
873 assert_eq!(result.value_int, 0); // default
874 assert_eq!(result.default_selection, 0);
875 assert!(!result.is_translatable);
876
877 assert_eq!(result.visual_items.row_count(), 2);
878 assert_eq!(result.visual_items.row_data(0), Some(SharedString::from("foo")));
879 assert_eq!(result.visual_items.row_data(1), Some(SharedString::from("bar")));
880 }
881
882 #[test]
883 fn test_property_float() {
884 let result =
885 property_conversion_test(r#"export component Test { in property <float> test1; }"#, 0);
886 assert_eq!(result.kind, ui::PropertyValueKind::Float);
887 assert_eq!(result.value_float, 0.0);
888
889 let result = property_conversion_test(
890 r#"export component Test { in property <float> test1: 42.0; }"#,
891 1,
892 );
893 assert_eq!(result.kind, ui::PropertyValueKind::Float);
894 assert_eq!(result.value_float, 42.0);
895
896 let result = property_conversion_test(
897 r#"export component Test { in property <float> test1: +42.0; }"#,
898 1,
899 );
900 assert_eq!(result.kind, ui::PropertyValueKind::Float);
901 assert_eq!(result.value_float, 42.0);
902
903 let result = property_conversion_test(
904 r#"export component Test { in property <float> test1: -42.0; }"#,
905 1,
906 );
907 assert_eq!(result.kind, ui::PropertyValueKind::Float);
908 assert_eq!(result.value_float, -42.0);
909
910 let result = property_conversion_test(
911 r#"export component Test { in property <float> test1: 42.0 * 23.0; }"#,
912 0,
913 );
914 assert_eq!(result.kind, ui::PropertyValueKind::Code);
915 assert_eq!(result.value_float, 0.0);
916 }
917
918 #[test]
919 fn test_property_integer() {
920 let result =
921 property_conversion_test(r#"export component Test { in property <int> test1; }"#, 0);
922 assert_eq!(result.kind, ui::PropertyValueKind::Integer);
923 assert_eq!(result.value_int, 0);
924
925 let result = property_conversion_test(
926 r#"export component Test { in property <int> test1: 42; }"#,
927 1,
928 );
929 assert_eq!(result.kind, ui::PropertyValueKind::Integer);
930 assert_eq!(result.value_int, 42);
931
932 let result = property_conversion_test(
933 r#"export component Test { in property <int> test1: +42; }"#,
934 1,
935 );
936 assert_eq!(result.kind, ui::PropertyValueKind::Integer);
937 assert_eq!(result.value_int, 42);
938
939 let result = property_conversion_test(
940 r#"export component Test { in property <int> test1: -42; }"#,
941 1,
942 );
943 assert_eq!(result.kind, ui::PropertyValueKind::Integer);
944 assert_eq!(result.value_int, -42);
945
946 let result = property_conversion_test(
947 r#"export component Test { in property <int> test1: 42 * 23; }"#,
948 0,
949 );
950 assert_eq!(result.kind, ui::PropertyValueKind::Code);
951 assert_eq!(result.value_int, 0);
952 }
953
954 #[test]
955 fn test_property_color() {
956 let result =
957 property_conversion_test(r#"export component Test { in property <color> test1; }"#, 0);
958 assert_eq!(result.kind, ui::PropertyValueKind::Color);
959 assert!(matches!(result.value_brush, slint::Brush::SolidColor(_)));
960 assert_eq!(result.value_brush.color().red(), 0);
961 assert_eq!(result.value_brush.color().green(), 0);
962 assert_eq!(result.value_brush.color().blue(), 0);
963 assert_eq!(result.value_brush.color().alpha(), 0);
964
965 let result = property_conversion_test(
966 r#"export component Test { in property <color> test1: #10203040; }"#,
967 1,
968 );
969 assert_eq!(result.kind, ui::PropertyValueKind::Color);
970 assert!(matches!(result.value_brush, slint::Brush::SolidColor(_)));
971 assert_eq!(result.value_brush.color().red(), 0x10);
972 assert_eq!(result.value_brush.color().green(), 0x20);
973 assert_eq!(result.value_brush.color().blue(), 0x30);
974 assert_eq!(result.value_brush.color().alpha(), 0x40);
975
976 let result = property_conversion_test(
977 r#"export component Test { in property <color> test1: #10203040.darker(0.5); }"#,
978 1,
979 );
980 assert_eq!(result.kind, ui::PropertyValueKind::Code);
981
982 let result = property_conversion_test(
983 r#"export component Test { in property <color> test1: Colors.red; }"#,
984 0,
985 );
986 assert_eq!(result.kind, ui::PropertyValueKind::Code);
987 }
988
989 #[test]
990 fn test_property_brush() {
991 let result =
992 property_conversion_test(r#"export component Test { in property <brush> test1; }"#, 0);
993 assert_eq!(result.kind, ui::PropertyValueKind::Brush);
994 assert!(matches!(result.value_brush, slint::Brush::SolidColor(_)));
995 assert_eq!(result.value_brush.color().red(), 0);
996 assert_eq!(result.value_brush.color().green(), 0);
997 assert_eq!(result.value_brush.color().blue(), 0);
998 assert_eq!(result.value_brush.color().alpha(), 0);
999
1000 let result = property_conversion_test(
1001 r#"export component Test { in property <brush> test1: #10203040; }"#,
1002 1,
1003 );
1004 assert_eq!(result.kind, ui::PropertyValueKind::Brush);
1005 assert!(matches!(result.value_brush, slint::Brush::SolidColor(_)));
1006 assert_eq!(result.value_brush.color().red(), 0x10);
1007 assert_eq!(result.value_brush.color().green(), 0x20);
1008 assert_eq!(result.value_brush.color().blue(), 0x30);
1009 assert_eq!(result.value_brush.color().alpha(), 0x40);
1010
1011 let result = property_conversion_test(
1012 r#"export component Test { in property <brush> test1: #10203040.darker(0.5); }"#,
1013 1,
1014 );
1015 assert_eq!(result.kind, ui::PropertyValueKind::Code);
1016
1017 let result = property_conversion_test(
1018 r#"export component Test { in property <brush> test1: Colors.red; }"#,
1019 0,
1020 );
1021 assert_eq!(result.kind, ui::PropertyValueKind::Code);
1022
1023 let result = property_conversion_test(
1024 r#"export component Test { in property <brush> test1: @linear-gradient(90deg, #3f87a6 0%, #ebf8e1 50%, #f69d3c 100%); }"#,
1025 1,
1026 );
1027 assert_eq!(result.kind, ui::PropertyValueKind::Brush);
1028
1029 let result = property_conversion_test(
1030 r#"export component Test { in property <brush> test1: @radial-gradient(circle, #f00 0%, #0f0 50%, #00f 100%); }"#,
1031 1,
1032 );
1033 assert_eq!(result.kind, ui::PropertyValueKind::Brush);
1034
1035 let result = property_conversion_test(
1036 r#"export component Test { in property <brush> test1: @linear-gradient(90deg, #3f87a6 0%, #ebf8e1 50% - 10%, #f69d3c 100%); }"#,
1037 1,
1038 );
1039 assert_eq!(result.kind, ui::PropertyValueKind::Code);
1040
1041 let result = property_conversion_test(
1042 r#"export component Test { in property <brush> test1: @radial-gradient(circle, #f00 0%, #0f0 50% - 10%, #00f 100%); }"#,
1043 1,
1044 );
1045 assert_eq!(result.kind, ui::PropertyValueKind::Code);
1046 }
1047
1048 #[test]
1049 fn test_property_units() {
1050 let result =
1051 property_conversion_test(r#"export component Test { in property <length> test1; }"#, 0);
1052 assert_eq!(result.kind, ui::PropertyValueKind::Float);
1053 assert_eq!(result.default_selection, 0);
1054 assert_eq!(result.value_int, 0);
1055 assert_eq!(result.visual_items.row_data(result.value_int as usize), Some("px".into()));
1056 let length_row_count = result.visual_items.row_count();
1057 assert!(length_row_count > 2);
1058
1059 let result = property_conversion_test(
1060 r#"export component Test { in property <duration> test1: 25s; }"#,
1061 1,
1062 );
1063 assert_eq!(result.kind, ui::PropertyValueKind::Float);
1064 assert_eq!(result.value_float, 25.0);
1065 assert_eq!(result.default_selection, 0);
1066 assert_eq!(result.visual_items.row_data(result.value_int as usize), Some("s".into()));
1067 assert_eq!(result.visual_items.row_count(), 2); // ms, s
1068
1069 let result = property_conversion_test(
1070 r#"export component Test { in property <physical-length> test1: 1.5phx; }"#,
1071 1,
1072 );
1073 assert_eq!(result.kind, ui::PropertyValueKind::Float);
1074 assert_eq!(result.value_float, 1.5);
1075 assert_eq!(result.default_selection, 0);
1076 assert_eq!(result.visual_items.row_data(result.value_int as usize), Some("phx".into()));
1077 assert!(result.visual_items.row_count() > 1); // More than just physical length
1078
1079 let result = property_conversion_test(
1080 r#"export component Test { in property <angle> test1: 1.5turns + 1.3deg; }"#,
1081 0,
1082 );
1083 assert_eq!(result.kind, ui::PropertyValueKind::Code);
1084 }
1085
1086 #[test]
1087 fn test_property_with_default_values() {
1088 let source = r#"
1089import { Button } from "std-widgets.slint";
1090component MyButton inherits Button {
1091 text: "Ok";
1092 in property <color> color: red;
1093 in property alias <=> self.xxx;
1094 property <length> xxx: 45cm;
1095}
1096export component X {
1097 MyButton {
1098 /*CURSOR*/
1099 }
1100}
1101 "#;
1102
1103 let (dc, url, _diag) = loaded_document_cache(source.to_string());
1104 let element = dc
1105 .element_at_offset(&url, (source.find("/*CURSOR*/").expect("cursor") as u32).into())
1106 .unwrap();
1107 let pi = super::properties::get_properties(&element, super::properties::LayoutKind::None);
1108
1109 let prop = pi.iter().find(|pi| pi.name == "visible").unwrap();
1110 let result = super::simplify_value(&dc, prop);
1111 assert_eq!(result.kind, ui::PropertyValueKind::Boolean);
1112 assert!(result.value_bool);
1113
1114 let prop = pi.iter().find(|pi| pi.name == "enabled").unwrap();
1115 let result = super::simplify_value(&dc, prop);
1116 assert_eq!(result.kind, ui::PropertyValueKind::Boolean);
1117 assert!(result.value_bool);
1118
1119 let prop = pi.iter().find(|pi| pi.name == "text").unwrap();
1120 let result = super::simplify_value(&dc, prop);
1121 assert_eq!(result.kind, ui::PropertyValueKind::String);
1122 assert_eq!(result.value_string, "Ok");
1123
1124 let prop = pi.iter().find(|pi| pi.name == "alias").unwrap();
1125 let result = super::simplify_value(&dc, prop);
1126 assert_eq!(result.kind, ui::PropertyValueKind::Float);
1127 assert_eq!(result.value_float, 45.);
1128 assert_eq!(result.visual_items.row_data(result.value_int as usize).unwrap(), "cm");
1129
1130 let prop = pi.iter().find(|pi| pi.name == "color").unwrap();
1131 let result = super::simplify_value(&dc, prop);
1132 assert_eq!(result.kind, ui::PropertyValueKind::Color);
1133 assert_eq!(
1134 result.value_brush,
1135 slint::Brush::SolidColor(slint::Color::from_rgb_u8(255, 0, 0))
1136 );
1137 }
1138
1139 #[test]
1140 fn test_property_with_default_values_loop() {
1141 let source = r#"
1142component Abc {
1143 // This should be an error, not a infinite loop/hang
1144 in property <length> some_loop <=> r.border-width;
1145 r:= Rectangle {
1146 property <length> some_loop <=> root.some_loop;
1147 border-width <=> some_loop;
1148 }
1149}
1150export component X {
1151 Abc {
1152 /*CURSOR*/
1153 }
1154}
1155 "#;
1156
1157 let (dc, url, _diag) = loaded_document_cache(source.to_string());
1158
1159 let element = dc
1160 .element_at_offset(&url, (source.find("/*CURSOR*/").expect("cursor") as u32).into())
1161 .unwrap();
1162 let pi = super::properties::get_properties(&element, super::properties::LayoutKind::None);
1163
1164 let prop = pi.iter().find(|pi| pi.name == "visible").unwrap();
1165 let result = super::simplify_value(&dc, prop);
1166 assert_eq!(result.kind, ui::PropertyValueKind::Boolean);
1167 assert!(result.value_bool);
1168 }
1169}
1170