qleany 1.7.3

Architecture generator for Rust and C++/Qt applications.
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
//! Feature handlers module
//!
//! This module contains functions for feature management including
//! event subscriptions, list operations, form handling, and callbacks.

use std::sync::Arc;

use common::direct_access::workspace::WorkspaceRelationshipField;
use common::event::{DirectAccessEntity, EntityEvent, HandlingManifestEvent, Origin};
use direct_access::UpdateFeatureDto;
use slint::ComponentHandle;

use crate::app_context::AppContext;
use crate::commands::{feature_commands, undo_redo_commands, workspace_commands};
use crate::event_hub_client::EventHubClient;
use crate::{App, AppState, FeaturesTabState, ListItem};

use super::use_case_handlers::{clear_use_case_form, clear_use_case_list, fill_use_case_list};

pub fn create_new_undo_stack(app: &App, app_context: &Arc<AppContext>) {
    let ctx = Arc::clone(app_context);
    let app_weak = app.as_weak();

    if let Some(app) = app_weak.upgrade() {
        let stack_id = ctx.undo_redo_manager.lock().unwrap().create_new_stack();
        log::info!("New undo stack created with ID: {}", stack_id);
        app.global::<FeaturesTabState>()
            .set_features_undo_stack_id(stack_id as i32);
    }
}

pub fn delete_undo_stack(app: &App, app_context: &Arc<AppContext>) {
    let ctx = Arc::clone(app_context);
    let app_weak = app.as_weak();

    if let Some(app) = app_weak.upgrade() {
        let stack_id = app
            .global::<FeaturesTabState>()
            .get_features_undo_stack_id() as u64;
        let result = ctx.undo_redo_manager.lock().unwrap().delete_stack(stack_id);
        match result {
            Ok(()) => {
                log::info!("Undo stack with ID {} deleted", stack_id);
                app.global::<FeaturesTabState>()
                    .set_features_undo_stack_id(-1);
            }
            Err(e) => {
                log::error!("Failed to delete undo stack {}: {}", stack_id, e);
            }
        }
    }
}

pub fn subscribe_close_manifest_event(
    event_hub_client: &EventHubClient,
    app: &App,
    app_context: &Arc<AppContext>,
) {
    event_hub_client.subscribe(Origin::HandlingManifest(HandlingManifestEvent::Close), {
        let ctx = Arc::clone(app_context);
        let app_weak = app.as_weak();
        move |event| {
            log::info!("Manifest closed event received: {:?}", event);
            let ctx = Arc::clone(&ctx);
            let app_weak = app_weak.clone();

            // Use invoke_from_event_loop to safely update UI from background thread
            let _ = slint::invoke_from_event_loop(move || {
                if let Some(app) = app_weak.upgrade() {
                    clear_feature_list(&app, &ctx);
                    clear_use_case_list(&app, &ctx);
                    delete_undo_stack(&app, &ctx);
                }
            });
        }
    });
}

pub fn subscribe_new_manifest_event(
    event_hub_client: &EventHubClient,
    app: &App,
    app_context: &Arc<AppContext>,
) {
    event_hub_client.subscribe(Origin::HandlingManifest(HandlingManifestEvent::Create), {
        let ctx = Arc::clone(app_context);
        let app_weak = app.as_weak();
        move |_event| {
            log::info!("New manifest created event received");
            let ctx = Arc::clone(&ctx);
            let app_weak = app_weak.clone();

            let _ = slint::invoke_from_event_loop(move || {
                if let Some(app) = app_weak.upgrade()
                    && app.global::<AppState>().get_manifest_is_open()
                {
                    fill_feature_list(&app, &ctx);
                    fill_use_case_list(&app, &ctx);
                    create_new_undo_stack(&app, &ctx);
                }
            });
        }
    });
}

pub fn subscribe_load_manifest_event(
    event_hub_client: &EventHubClient,
    app: &App,
    app_context: &Arc<AppContext>,
) {
    event_hub_client.subscribe(Origin::HandlingManifest(HandlingManifestEvent::Load), {
        let ctx = Arc::clone(app_context);
        let app_weak = app.as_weak();
        move |_event| {
            log::info!("Manifest loaded event received");
            let ctx = Arc::clone(&ctx);
            let app_weak = app_weak.clone();

            let _ = slint::invoke_from_event_loop(move || {
                if let Some(app) = app_weak.upgrade() {
                    log::info!("Refreshing feature and use case lists after manifest load");
                    if app.global::<AppState>().get_manifest_is_open() {
                        log::info!("Manifest is open, scheduling list refresh");
                        fill_feature_list(&app, &ctx);
                        fill_use_case_list(&app, &ctx);
                        log::info!("Feature and Use Case lists refreshed after manifest load");
                        create_new_undo_stack(&app, &ctx);
                    }
                }
            });
        }
    });
}

/// Subscribe to Workspace update events to refresh feature_cr_list
pub fn subscribe_workspace_updated_event(
    event_hub_client: &EventHubClient,
    app: &App,
    app_context: &Arc<AppContext>,
) {
    event_hub_client.subscribe(
        Origin::DirectAccess(DirectAccessEntity::Workspace(EntityEvent::Updated)),
        {
            let ctx = Arc::clone(app_context);
            let app_weak = app.as_weak();
            move |event| {
                log::info!(
                    "Workspace updated event received (features tab): {:?}",
                    event
                );
                let ctx = Arc::clone(&ctx);
                let app_weak = app_weak.clone();

                let _ = slint::invoke_from_event_loop(move || {
                    if let Some(app) = app_weak.upgrade()
                        && app.global::<AppState>().get_manifest_is_open()
                    {
                        fill_feature_list(&app, &ctx);
                        app.global::<AppState>().set_manifest_is_saved(false);
                    }
                });
            }
        },
    );
}

/// Subscribe to Feature update events to refresh feature_cr_list
pub fn subscribe_feature_updated_event(
    event_hub_client: &EventHubClient,
    app: &App,
    app_context: &Arc<AppContext>,
) {
    event_hub_client.subscribe(
        Origin::DirectAccess(DirectAccessEntity::Feature(EntityEvent::Updated)),
        {
            let ctx = Arc::clone(app_context);
            let app_weak = app.as_weak();
            move |event| {
                log::info!("Feature updated event received: {:?}", event);
                let ctx = Arc::clone(&ctx);
                let app_weak = app_weak.clone();

                let _ = slint::invoke_from_event_loop(move || {
                    if let Some(app) = app_weak.upgrade()
                        && app.global::<AppState>().get_manifest_is_open()
                    {
                        fill_feature_list(&app, &ctx);
                        fill_use_case_list(&app, &ctx);
                        app.global::<AppState>().set_manifest_is_saved(false);
                    }
                });
            }
        },
    )
}

/// Subscribe to Feature deletion events
pub fn subscribe_feature_deletion_event(
    event_hub_client: &EventHubClient,
    app: &App,
    app_context: &Arc<AppContext>,
) {
    event_hub_client.subscribe(
        Origin::DirectAccess(DirectAccessEntity::Feature(EntityEvent::Removed)),
        {
            let ctx = Arc::clone(app_context);
            let app_weak = app.as_weak();
            move |event| {
                log::info!("Feature updated event received: {:?}", event);
                let _ctx = Arc::clone(&ctx);
                let app_weak = app_weak.clone();

                let _ = slint::invoke_from_event_loop(move || {
                    if let Some(app) = app_weak.upgrade()
                        && app.global::<AppState>().get_manifest_is_open()
                    {
                        app.global::<AppState>().set_manifest_is_saved(false);
                    }
                });
            }
        },
    )
}

pub fn fill_feature_list(app: &App, app_context: &Arc<AppContext>) {
    log::info!("Filling feature list ...");

    let ctx = Arc::clone(app_context);
    let app_weak = app.as_weak();

    if let Some(app) = app_weak.upgrade() {
        let workspace_id = app.global::<AppState>().get_workspace_id() as common::types::EntityId;

        if workspace_id > 0 {
            let feature_ids_res = workspace_commands::get_workspace_relationship(
                &ctx,
                &workspace_id,
                &WorkspaceRelationshipField::Features,
            );

            match feature_ids_res {
                Ok(feature_ids) => {
                    // empty field list if no features
                    if feature_ids.is_empty() {
                        let model = std::rc::Rc::new(slint::VecModel::from(Vec::<ListItem>::new()));
                        app.global::<FeaturesTabState>()
                            .set_feature_cr_list(model.into());
                        log::info!("Feature list cleared (no features)");
                        return;
                    }

                    match feature_commands::get_feature_multi(&ctx, &feature_ids) {
                        Ok(features_opt) => {
                            let mut list: Vec<ListItem> = Vec::new();
                            for f in features_opt.into_iter().flatten() {
                                list.push(ListItem {
                                    id: f.id as i32,
                                    text: slint::SharedString::from(f.name),
                                    subtitle: slint::SharedString::from(""),
                                    checked: false,
                                    gradient_color: slint::Color::default(),
                                });
                            }

                            let model = std::rc::Rc::new(slint::VecModel::from(list));
                            app.global::<FeaturesTabState>()
                                .set_feature_cr_list(model.into());
                            log::info!("Feature list refreshed");
                        }
                        Err(e) => {
                            log::error!("Failed to fetch features: {}", e);
                        }
                    }
                }
                Err(e) => {
                    log::error!("Failed to get workspace features: {}", e);
                }
            }
        }
    }
}

pub fn clear_feature_list(app: &App, app_context: &Arc<AppContext>) {
    let _ctx = Arc::clone(app_context);
    let app_weak = app.as_weak();

    if let Some(app) = app_weak.upgrade() {
        // Clear feature list
        let model = std::rc::Rc::new(slint::VecModel::from(Vec::<ListItem>::new()));
        app.global::<FeaturesTabState>()
            .set_feature_cr_list(model.into());
        log::info!("Feature list cleared");
    }
}

/// Helper function to fill feature form from FeatureDto
pub fn fill_feature_form(app: &App, feature: &direct_access::FeatureDto) {
    let state = app.global::<FeaturesTabState>();
    state.set_selected_feature_id(feature.id as i32);
    state.set_selected_feature_name(feature.name.clone().into());
}

/// Helper function to clear feature form
pub fn clear_feature_form(app: &App) {
    let state = app.global::<FeaturesTabState>();
    state.set_selected_feature_id(-1);
    state.set_selected_feature_name("".into());
}

pub fn setup_features_reorder_callback(app: &App, app_context: &Arc<AppContext>) {
    app.global::<FeaturesTabState>()
        .on_request_features_reorder({
            let ctx = Arc::clone(app_context);
            let app_weak = app.as_weak();
            move |from_index, to_index| {
                let from = from_index as usize;
                let to = to_index as usize;

                if let Some(app) = app_weak.upgrade() {
                    let workspace_id =
                        app.global::<AppState>().get_workspace_id() as common::types::EntityId;
                    let feature_ids_res = workspace_commands::get_workspace_relationship(
                        &ctx,
                        &workspace_id,
                        &WorkspaceRelationshipField::Features,
                    );
                    let mut feature_ids = feature_ids_res.unwrap_or_default();

                    if from == to || from >= feature_ids.len() {
                        return;
                    }

                    let moving_feature_id = feature_ids.remove(from);
                    let mut insert_at = if to > from { to - 1 } else { to };
                    if insert_at > feature_ids.len() {
                        insert_at = feature_ids.len();
                    }
                    feature_ids.insert(insert_at, moving_feature_id);

                    let result = workspace_commands::set_workspace_relationship(
                        &ctx,
                        Some(
                            app.global::<FeaturesTabState>()
                                .get_features_undo_stack_id() as u64,
                        ),
                        &direct_access::WorkspaceRelationshipDto {
                            id: workspace_id,
                            field: WorkspaceRelationshipField::Features,
                            right_ids: feature_ids,
                        },
                    );

                    match result {
                        Ok(()) => {
                            log::info!("Features reordered successfully");
                        }
                        Err(e) => {
                            log::error!("Failed to reorder features: {}", e);
                        }
                    }
                }
            }
        });
}

pub fn setup_feature_deletion_callback(app: &App, app_context: &Arc<AppContext>) {
    app.global::<FeaturesTabState>()
        .on_request_feature_deletion({
            let ctx = Arc::clone(app_context);
            let app_weak = app.as_weak();
            move |feature_id| {
                if feature_id < 0 {
                    return;
                }
                if let Some(app) = app_weak.upgrade() {
                    let result = feature_commands::remove_feature(
                        &ctx,
                        Some(
                            app.global::<FeaturesTabState>()
                                .get_features_undo_stack_id() as u64,
                        ),
                        &(feature_id as common::types::EntityId),
                    );
                    match result {
                        Ok(()) => {
                            log::info!("Feature deleted successfully");
                            // Clear feature form
                            clear_feature_form(&app);
                            // Clear use case list and form
                            clear_use_case_list(&app, &ctx);
                            clear_use_case_form(&app);
                            // Refresh feature list
                            fill_feature_list(&app, &ctx);
                        }
                        Err(e) => {
                            log::error!("Failed to delete feature: {}", e);
                        }
                    }
                }
            }
        });
}

pub fn setup_select_feature_callbacks(app: &App, app_context: &Arc<AppContext>) {
    app.global::<FeaturesTabState>().on_feature_selected({
        let ctx = Arc::clone(app_context);
        let app_weak = app.as_weak();
        move |feature_id| {
            if feature_id < 0 {
                return;
            }
            if let Some(app) = app_weak.upgrade() {
                let feature_res =
                    feature_commands::get_feature(&ctx, &(feature_id as common::types::EntityId));
                match feature_res {
                    Ok(Some(feature)) => {
                        fill_feature_form(&app, &feature);
                        fill_use_case_list(&app, &ctx);
                        // Clear use case form when feature changes
                        clear_use_case_form(&app);
                        log::info!("Feature selected: {}", feature.name);
                    }
                    Ok(None) => {
                        log::warn!("Feature not found: {}", feature_id);
                    }
                    Err(e) => {
                        log::error!("Failed to get feature: {}", e);
                    }
                }
            }
        }
    });
}

pub fn setup_feature_name_callback(app: &App, app_context: &Arc<AppContext>) {
    app.global::<FeaturesTabState>().on_feature_name_changed({
        let ctx = Arc::clone(app_context);
        let app_weak = app.as_weak();
        move |name| {
            if let Some(app) = app_weak.upgrade() {
                let feature_id = app.global::<FeaturesTabState>().get_selected_feature_id();
                if feature_id < 0 {
                    return;
                }

                let feature_res =
                    feature_commands::get_feature(&ctx, &(feature_id as common::types::EntityId));

                if let Ok(Some(mut feature)) = feature_res.map(|f| f.map(UpdateFeatureDto::from)) {
                    feature.name = name.to_string();
                    match feature_commands::update_feature(
                        &ctx,
                        Some(
                            app.global::<FeaturesTabState>()
                                .get_features_undo_stack_id() as u64,
                        ),
                        &feature,
                    ) {
                        Ok(_) => {
                            log::info!("Feature name updated successfully");
                        }
                        Err(e) => {
                            log::error!("Failed to update feature name: {}", e);
                        }
                    }
                }
            }
        }
    });
}

pub fn setup_feature_addition_callback(app: &App, app_context: &Arc<AppContext>) {
    app.global::<FeaturesTabState>()
        .on_request_feature_addition({
            let ctx = Arc::clone(app_context);
            let app_weak = app.as_weak();
            move || {
                if let Some(app) = app_weak.upgrade() {
                    let workspace_id = app.global::<AppState>().get_workspace_id();
                    if workspace_id <= 0 {
                        log::warn!("Cannot add feature: no workspace loaded");
                        return;
                    }

                    let stack_id = app
                        .global::<FeaturesTabState>()
                        .get_features_undo_stack_id() as u64;

                    if let Err(e) = undo_redo_commands::begin_composite(&ctx, Some(stack_id)) {
                        log::error!("Failed to begin composite: {e}");
                        return;
                    }

                    // Create a new feature with default values
                    let create_dto = direct_access::CreateFeatureDto {
                        created_at: chrono::Utc::now(),
                        updated_at: chrono::Utc::now(),
                        name: "new_feature".to_string(),
                        use_cases: vec![],
                    };

                    match feature_commands::create_orphan_feature(&ctx, Some(stack_id), &create_dto)
                    {
                        Ok(new_feature) => {
                            log::info!("Feature created successfully with id: {}", new_feature.id);

                            // Get current feature ids from workspace
                            let feature_ids_res = workspace_commands::get_workspace_relationship(
                                &ctx,
                                &(workspace_id as common::types::EntityId),
                                &WorkspaceRelationshipField::Features,
                            );

                            match feature_ids_res {
                                Ok(mut feature_ids) => {
                                    // Add the new feature id to the list
                                    feature_ids.push(new_feature.id);

                                    // Update the workspace relationship
                                    let relationship_dto =
                                        direct_access::WorkspaceRelationshipDto {
                                            id: workspace_id as common::types::EntityId,
                                            field: WorkspaceRelationshipField::Features,
                                            right_ids: feature_ids,
                                        };

                                    if let Err(e) = workspace_commands::set_workspace_relationship(
                                        &ctx,
                                        Some(
                                            app.global::<FeaturesTabState>()
                                                .get_features_undo_stack_id()
                                                as u64,
                                        ),
                                        &relationship_dto,
                                    ) {
                                        log::error!(
                                            "Failed to add feature to workspace relationship: {}",
                                            e
                                        );
                                        undo_redo_commands::cancel_composite(&ctx);
                                    } else {
                                        log::info!(
                                            "Feature added to workspace relationship successfully"
                                        );
                                        undo_redo_commands::end_composite(&ctx);
                                    }
                                }
                                Err(e) => {
                                    log::error!(
                                        "Failed to get workspace features relationship: {}",
                                        e
                                    );
                                    undo_redo_commands::cancel_composite(&ctx);
                                }
                            }
                        }
                        Err(e) => {
                            log::error!("Failed to create feature: {}", e);
                            undo_redo_commands::cancel_composite(&ctx);
                        }
                    }
                }
            }
        });
}