kcl-lib 0.2.144

KittyCAD Language implementation and tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! Types specific for modeling-app projects.

use anyhow::Result;
use indexmap::IndexMap;
use kittycad_modeling_cmds::units::UnitLength;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use validator::Validate;

use crate::settings::types::DefaultTrue;
use crate::settings::types::OnboardingStatus;
use crate::settings::types::ProjectCommandBarSettings;
use crate::settings::types::ProjectTextEditorSettings;
use crate::settings::types::is_default;

/// Project specific settings for the app.
/// These live in `project.toml` in the base of the project directory.
/// Updating the settings for the project in the app will update this file automatically.
/// Do not edit this file manually, as it may be overwritten by the app.
/// Manual edits can cause corruption of the settings file.
#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema, ts_rs::TS, PartialEq, Validate)]
#[ts(export)]
#[serde(rename_all = "snake_case")]
pub struct ProjectConfiguration {
    /// The settings for the project.
    #[serde(default)]
    #[validate(nested)]
    pub settings: PerProjectSettings,

    /// Settings for cloud-backed project metadata.
    #[serde(default, skip_serializing_if = "is_default")]
    #[validate(nested)]
    pub cloud: ProjectCloudSettings,
}

impl ProjectConfiguration {
    // TODO: remove this when we remove backwards compatibility with the old settings file.
    pub fn parse_and_validate(toml_str: &str) -> Result<Self> {
        let settings = toml::from_str::<Self>(toml_str)?;

        settings.validate()?;

        Ok(settings)
    }
}

/// High level project settings.
#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema, ts_rs::TS, PartialEq, Validate)]
#[ts(export)]
#[serde(rename_all = "snake_case")]
pub struct PerProjectSettings {
    /// Information about the project itself.
    /// Choices about how settings are merged have prevent me (lee) from easily
    /// moving this out of the settings structure.
    #[serde(default)]
    #[validate(nested)]
    pub meta: ProjectMetaSettings,

    /// The settings for the Design Studio.
    #[serde(default)]
    #[validate(nested)]
    pub app: ProjectAppSettings,
    /// Settings that affect the behavior while modeling.
    #[serde(default)]
    #[validate(nested)]
    pub modeling: ProjectModelingSettings,
    /// Settings that affect the behavior of the KCL text editor.
    #[serde(default)]
    #[validate(nested)]
    pub text_editor: ProjectTextEditorSettings,
    /// Settings that affect the behavior of the command bar.
    #[serde(default)]
    #[validate(nested)]
    pub command_bar: ProjectCommandBarSettings,
}

/// Information about the project.
#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema, ts_rs::TS, PartialEq, Validate)]
#[ts(export)]
#[serde(rename_all = "snake_case")]
pub struct ProjectMetaSettings {
    #[serde(default, skip_serializing_if = "is_default")]
    pub id: uuid::Uuid,
}

/// Cloud-backed project metadata.
#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema, ts_rs::TS, PartialEq, Validate)]
#[ts(export)]
#[serde(rename_all = "snake_case")]
pub struct ProjectCloudSettings {
    /// Environment-scoped cloud metadata keyed by environment name.
    /// TOML with dotted environment names should use quoted table names, for
    /// example `[cloud."zoo.dev"]`.
    #[serde(flatten, default, skip_serializing_if = "IndexMap::is_empty")]
    pub environments: IndexMap<String, ProjectCloudEnvironmentSettings>,
}

/// Cloud-backed metadata for a single environment.
#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema, ts_rs::TS, PartialEq, Validate)]
#[ts(export)]
#[serde(rename_all = "snake_case")]
pub struct ProjectCloudEnvironmentSettings {
    #[serde(default, skip_serializing_if = "is_default")]
    pub project_id: uuid::Uuid,
}

/// Project specific application settings.
// TODO: When we remove backwards compatibility with the old settings file, we can remove the
// aliases to camelCase (and projects plural) from everywhere.
#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema, ts_rs::TS, PartialEq, Validate)]
#[ts(export)]
#[serde(rename_all = "snake_case")]
pub struct ProjectAppSettings {
    /// The onboarding status of the app.
    #[serde(default, skip_serializing_if = "is_default")]
    pub onboarding_status: OnboardingStatus,
    /// When the user is idle, and this is true, the stream will be torn down.
    #[serde(default, skip_serializing_if = "is_default")]
    pub stream_idle_mode: bool,
    /// When the user is idle, and this is true, the stream will be torn down.
    #[serde(default, skip_serializing_if = "is_default")]
    pub allow_orbit_in_sketch_mode: bool,
    /// Whether to show the debug panel, which lets you see various states
    /// of the app to aid in development.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub show_debug_panel: Option<bool>,
    /// Zookeeper reasoning mode. Uses the app default if not set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub zookeeper_mode: Option<String>,
    /// Settings that affect the behavior of the command bar.
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub named_views: IndexMap<uuid::Uuid, NamedView>,
}

/// Project specific settings that affect the behavior while modeling.
#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema, ts_rs::TS, PartialEq, Validate)]
#[serde(rename_all = "snake_case")]
#[ts(export)]
pub struct ProjectModelingSettings {
    /// The default unit to use in modeling dimensions.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub base_unit: Option<UnitLength>,
    /// Highlight edges of 3D objects?
    #[serde(default, skip_serializing_if = "is_default")]
    pub highlight_edges: DefaultTrue,
    /// Whether or not Screen Space Ambient Occlusion (SSAO) is enabled.
    #[serde(default, skip_serializing_if = "is_default")]
    pub enable_ssao: DefaultTrue,
    /// When enabled, the grid will use a fixed size based on your selected units rather than automatically scaling with zoom level.
    /// If true, the grid cells will be fixed-size, where the width is your default length unit.
    /// If false, the grid will get larger as you zoom out, and smaller as you zoom in.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fixed_size_grid: Option<bool>,
    /// When enabled, tools like line, rectangle, etc. will snap to the grid.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub snap_to_grid: Option<bool>,
    /// The space between major grid lines, specified in the current unit.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub major_grid_spacing: Option<f64>,
    /// The number of minor grid lines per major grid line.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub minor_grids_per_major: Option<f64>,
    /// The number of snaps between minor grid lines. 1 means snapping to each minor grid line.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub snaps_per_minor: Option<f64>,
}

fn named_view_point_version_one() -> f64 {
    1.0
}

#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, ts_rs::TS, PartialEq)]
#[serde(rename_all = "snake_case")]
#[ts(export)]
pub struct NamedView {
    /// User defined name to identify the named view. A label.
    #[serde(default)]
    pub name: String,
    /// Engine camera eye off set
    #[serde(default)]
    pub eye_offset: f64,
    /// Engine camera vertical FOV
    #[serde(default)]
    pub fov_y: f64,
    // Engine camera is orthographic or perspective projection
    #[serde(default)]
    pub is_ortho: bool,
    /// Engine camera is orthographic camera scaling enabled
    #[serde(default)]
    pub ortho_scale_enabled: bool,
    /// Engine camera orthographic scaling factor
    #[serde(default)]
    pub ortho_scale_factor: f64,
    /// Engine camera position that the camera pivots around
    #[serde(default)]
    pub pivot_position: [f64; 3],
    /// Engine camera orientation in relation to the pivot position
    #[serde(default)]
    pub pivot_rotation: [f64; 4],
    /// Engine camera world coordinate system orientation
    #[serde(default)]
    pub world_coord_system: String,
    /// Version number of the view point if the engine camera API changes
    #[serde(default = "named_view_point_version_one")]
    pub version: f64,
}

#[cfg(test)]
mod tests {
    use indexmap::IndexMap;
    use pretty_assertions::assert_eq;
    use serde_json::Value;

    use super::NamedView;
    use super::PerProjectSettings;
    use super::ProjectAppSettings;
    use super::ProjectCloudEnvironmentSettings;
    use super::ProjectCloudSettings;
    use super::ProjectCommandBarSettings;
    use super::ProjectConfiguration;
    use super::ProjectMetaSettings;
    use super::ProjectModelingSettings;
    use super::ProjectTextEditorSettings;
    use crate::settings::types::UnitLength;

    #[test]
    fn test_project_settings_empty_file_parses() {
        let empty_settings_file = r#""#;

        let parsed = toml::from_str::<ProjectConfiguration>(empty_settings_file).unwrap();
        assert_eq!(parsed, ProjectConfiguration::default());

        // Write the file back out.
        let serialized = toml::to_string(&parsed).unwrap();
        assert_eq!(
            serialized,
            r#"[settings.meta]

[settings.app]

[settings.modeling]

[settings.text_editor]

[settings.command_bar]
"#
        );

        let parsed = ProjectConfiguration::parse_and_validate(empty_settings_file).unwrap();
        assert_eq!(parsed, ProjectConfiguration::default());
    }

    #[test]
    fn named_view_serde_json() {
        let json = r#"
        [
          {
            "name":"dog",
            "pivot_rotation":[0.53809947,0.0,0.0,0.8428814],
            "pivot_position":[0.5,0,0.5],
            "eye_offset":231.52048,
            "fov_y":45,
            "ortho_scale_factor":1.574129,
            "is_ortho":true,
            "ortho_scale_enabled":true,
            "world_coord_system":"RightHandedUpZ"
          }
    ]
    "#;
        // serde_json to a NamedView will produce default values
        let named_views: Vec<NamedView> = serde_json::from_str(json).unwrap();
        let version = named_views[0].version;
        assert_eq!(version, 1.0);
    }

    #[test]
    fn named_view_serde_json_string() {
        let json = r#"
        [
          {
            "name":"dog",
            "pivot_rotation":[0.53809947,0.0,0.0,0.8428814],
            "pivot_position":[0.5,0,0.5],
            "eye_offset":231.52048,
            "fov_y":45,
            "ortho_scale_factor":1.574129,
            "is_ortho":true,
            "ortho_scale_enabled":true,
            "world_coord_system":"RightHandedUpZ"
          }
    ]
    "#;

        // serde_json to string does not produce default values
        let named_views: Value = match serde_json::from_str(json) {
            Ok(x) => x,
            Err(_) => return,
        };
        println!("{}", named_views);
    }

    #[test]
    fn test_project_settings_named_views() {
        let conf = ProjectConfiguration {
            settings: PerProjectSettings {
                meta: ProjectMetaSettings { id: uuid::Uuid::nil() },
                app: ProjectAppSettings {
                    onboarding_status: Default::default(),
                    stream_idle_mode: false,
                    allow_orbit_in_sketch_mode: false,
                    show_debug_panel: Some(true),
                    zookeeper_mode: None,
                    named_views: IndexMap::from([
                        (
                            uuid::uuid!("323611ea-66e3-43c9-9d0d-1091ba92948c"),
                            NamedView {
                                name: String::from("Hello"),
                                eye_offset: 1236.4015,
                                fov_y: 45.0,
                                is_ortho: false,
                                ortho_scale_enabled: false,
                                ortho_scale_factor: 45.0,
                                pivot_position: [-100.0, 100.0, 100.0],
                                pivot_rotation: [-0.16391756, 0.9862819, -0.01956843, 0.0032552152],
                                world_coord_system: String::from("RightHandedUpZ"),
                                version: 1.0,
                            },
                        ),
                        (
                            uuid::uuid!("423611ea-66e3-43c9-9d0d-1091ba92948c"),
                            NamedView {
                                name: String::from("Goodbye"),
                                eye_offset: 1236.4015,
                                fov_y: 45.0,
                                is_ortho: false,
                                ortho_scale_enabled: false,
                                ortho_scale_factor: 45.0,
                                pivot_position: [-100.0, 100.0, 100.0],
                                pivot_rotation: [-0.16391756, 0.9862819, -0.01956843, 0.0032552152],
                                world_coord_system: String::from("RightHandedUpZ"),
                                version: 1.0,
                            },
                        ),
                    ]),
                },
                modeling: ProjectModelingSettings {
                    base_unit: Some(UnitLength::Yards),
                    highlight_edges: Default::default(),
                    enable_ssao: true.into(),
                    snap_to_grid: None,
                    major_grid_spacing: None,
                    minor_grids_per_major: None,
                    snaps_per_minor: None,
                    fixed_size_grid: None,
                },
                text_editor: ProjectTextEditorSettings {
                    text_wrapping: Some(false),
                    blinking_cursor: Some(false),
                },
                command_bar: ProjectCommandBarSettings {
                    include_settings: Some(false),
                },
            },
            cloud: ProjectCloudSettings::default(),
        };
        let serialized = toml::to_string(&conf).unwrap();
        let old_project_file = r#"[settings.meta]

[settings.app]
show_debug_panel = true

[settings.app.named_views.323611ea-66e3-43c9-9d0d-1091ba92948c]
name = "Hello"
eye_offset = 1236.4015
fov_y = 45.0
is_ortho = false
ortho_scale_enabled = false
ortho_scale_factor = 45.0
pivot_position = [-100.0, 100.0, 100.0]
pivot_rotation = [-0.16391756, 0.9862819, -0.01956843, 0.0032552152]
world_coord_system = "RightHandedUpZ"
version = 1.0

[settings.app.named_views.423611ea-66e3-43c9-9d0d-1091ba92948c]
name = "Goodbye"
eye_offset = 1236.4015
fov_y = 45.0
is_ortho = false
ortho_scale_enabled = false
ortho_scale_factor = 45.0
pivot_position = [-100.0, 100.0, 100.0]
pivot_rotation = [-0.16391756, 0.9862819, -0.01956843, 0.0032552152]
world_coord_system = "RightHandedUpZ"
version = 1.0

[settings.modeling]
base_unit = "yd"

[settings.text_editor]
text_wrapping = false
blinking_cursor = false

[settings.command_bar]
include_settings = false
"#;

        assert_eq!(serialized, old_project_file)
    }

    #[test]
    fn test_project_settings_cloud_metadata_round_trip() {
        let local_project_id = uuid::uuid!("e8f5178c-5227-4567-bb5a-f52b3caef5ea");
        let zoo_cloud_project_id = uuid::uuid!("04c988e3-ec37-48a4-b491-45c3668934f1");
        let dev_cloud_project_id = uuid::uuid!("e9632dae-19ca-49ea-bcc1-ee8e34ff9de3");

        let conf = ProjectConfiguration {
            settings: PerProjectSettings {
                meta: ProjectMetaSettings { id: local_project_id },
                ..Default::default()
            },
            cloud: ProjectCloudSettings {
                environments: IndexMap::from([
                    (
                        "zoo.dev".to_owned(),
                        ProjectCloudEnvironmentSettings {
                            project_id: zoo_cloud_project_id,
                        },
                    ),
                    (
                        "dev.zoo.dev".to_owned(),
                        ProjectCloudEnvironmentSettings {
                            project_id: dev_cloud_project_id,
                        },
                    ),
                ]),
            },
        };

        let serialized = toml::to_string(&conf).unwrap();
        assert!(serialized.contains(&format!(
            "[cloud.\"zoo.dev\"]\nproject_id = \"{zoo_cloud_project_id}\"\n"
        )));
        assert!(serialized.contains(&format!(
            "[cloud.\"dev.zoo.dev\"]\nproject_id = \"{dev_cloud_project_id}\"\n"
        )));
        assert!(serialized.contains(&format!("[settings.meta]\nid = \"{local_project_id}\"\n")));

        let parsed = ProjectConfiguration::parse_and_validate(&serialized).unwrap();
        assert_eq!(parsed, conf);
    }
}