wxdragon-sys 0.9.16

Raw FFI bindings to libwxdragon (which statically links wxWidgets).
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
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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
#include <wx/wxprec.h>
#include <wx/wx.h>
#include <wx/cmdline.h>
#include "../include/wxdragon.h"
#include <wx/app.h>
#include <wx/image.h>
#include <cstdlib>
#include <wx/private/safecall.h>
#include <wx/scopeguard.h>
#include <vector>
#include <utility>

// --- Globals ---
// Store the C callback and user data provided to wxd_Main
static wxd_OnInitCallback g_OnInitCallback = nullptr;
static void* g_OnInitUserData = nullptr;

// Function to process Rust callbacks, implemented in Rust
extern "C" int
process_rust_callbacks();

// --- Internal C++ App Class ---

class WxdApp : public wxApp {
public:
    // Called by wxWidgets framework on application startup.
    virtual bool
    OnInit() override;

    // Accept any command line parameters without errors
    virtual void
    OnInitCmdLine(wxCmdLineParser& parser) override;

    virtual bool
    OnCmdLineParsed(wxCmdLineParser& parser) override;

    // Idle event handler to process callbacks
    void
    OnIdle(wxIdleEvent& event);

    // Override OnExit to clean up IPC/DDE objects before module cleanup
    virtual int OnExit() override;

#ifdef __WXOSX__
    // macOS-specific overrides
    virtual void
    MacOpenFiles(const wxArrayString& fileNames) override;
    virtual void
    MacOpenURL(const wxString& url) override;
    virtual void
    MacNewFile() override;
    virtual void
    MacReopenApp() override;
    virtual void
    MacPrintFiles(const wxArrayString& fileNames) override;

    // Store multiple callbacks for each event type
    struct MacCallbackList {
        std::vector<std::pair<wxd_MacOpenFilesCallback, void*>> openFiles;
        std::vector<std::pair<wxd_MacOpenURLCallback, void*>> openURL;
        std::vector<std::pair<wxd_MacNewFileCallback, void*>> newFile;
        std::vector<std::pair<wxd_MacReopenAppCallback, void*>> reopenApp;
        std::vector<std::pair<wxd_MacPrintFilesCallback, void*>> printFiles;
    } m_macCallbacks;
#endif
};

// Implementation of OnInit - this is where we call the C callback
bool
WxdApp::OnInit()
{
    // Call base class OnInit (important)
    if (!wxApp::OnInit()) {
        return false;
    }

#ifdef __WXMSW__
    // Use best available visual (important for proper rendering, especially with transparency)
    SetUseBestVisual(true);
#endif

    // Initialize all stock items (standard icons, etc.)
    wxInitializeStockLists();

    // Bind idle event to process callbacks
    Bind(wxEVT_IDLE, &WxdApp::OnIdle, this);

    // Call the stored C callback function
    if (g_OnInitCallback) {
        // The callback is responsible for creating the main window
        // and calling wxd_App_SetTopWindow.
        bool success = g_OnInitCallback(g_OnInitUserData);
        return success;
    }
    else {
        // Should not happen if wxd_Main is used correctly
        WXD_LOG_ERROR("wxDragon: No OnInit callback provided to wxd_Main.");
        return false;
    }
}

// Process callbacks on idle
void
WxdApp::OnIdle(wxIdleEvent& event)
{
    // Process any pending Rust callbacks
    int callbacks_processed = process_rust_callbacks();

    // Only request more idle events if there were callbacks to process
    // This prevents unnecessary CPU usage when the app is idle
    if (callbacks_processed > 0) {
        event.RequestMore();
    }
}

// Clean up IPC/DDE objects before wxWidgets module cleanup.
// On Windows, wxDDECleanUp() asserts all DDE objects are gone.
// Rust-side Drop impls may not run until after that point, so
// we proactively destroy any remaining IPC objects here.
int
WxdApp::OnExit()
{
    wxd_IPC_CleanupAll();
    return wxApp::OnExit();
}

// Configure command line parser to accept any parameters (no options).
void
WxdApp::OnInitCmdLine(wxCmdLineParser& parser)
{
    // Call base to keep standard behaviour, then override as needed
    wxApp::OnInitCmdLine(parser);

    // Disable option parsing so tokens starting with '-' are not treated as options
    parser.EnableLongOptions(false);
    parser.SetSwitchChars("");

    // Accept any number of free string parameters
    static const wxCmdLineEntryDesc cmdLineDesc[] = {
        { wxCMD_LINE_PARAM, nullptr, nullptr, "arg", wxCMD_LINE_VAL_STRING,
          wxCMD_LINE_PARAM_MULTIPLE | wxCMD_LINE_PARAM_OPTIONAL },
        { wxCMD_LINE_NONE, nullptr, nullptr, nullptr, wxCMD_LINE_VAL_NONE, 0 }
    };
    parser.SetDesc(cmdLineDesc);
}

// Always accept the parsed command line
bool
WxdApp::OnCmdLineParsed(wxCmdLineParser& parser)
{
    // Don't enforce any checks here; accept everything
    return true;
}

// --- C API Implementation ---

// This macro creates the necessary wxWidgets entry points (like main or WinMain)
// and instantiates our WxdApp class when wxEntry is called.
// It effectively hides the platform-specific entry point boilerplate.
// However, it means our C API user doesn't write main(), they write a function
// that calls wxd_Main(), and we need a way to trigger wxEntry.

// Let's use DECLARE/IMPLEMENT_APP_NO_MAIN. This requires us to provide
// the actual main() function or equivalent, allowing our wxd_Main to control
// the startup sequence.
wxDECLARE_APP(WxdApp);
wxIMPLEMENT_APP_NO_MAIN(WxdApp);

// Main entry point implementation
int
wxd_Main(int argc, char** argv, wxd_OnInitCallback on_init_cb, void* userData)
{
    if (!on_init_cb) {
        fprintf(stderr, "wxDragon Error: No OnInit callback provided to wxd_Main.\n");
        return 1;
    }

    g_OnInitCallback = on_init_cb;
    g_OnInitUserData = userData;

    if (!wxEntryStart(argc, argv)) {
        fprintf(stderr, "wxDragon Error: Failed to initialize wxWidgets (wxEntryStart failed).\n");
        return 1;
    }

    // Initialize all available image handlers (PNG, JPEG, etc.)
    // This must be done after wxEntryStart and before any image loading (e.g., in app OnInit).
    wxInitAllImageHandlers();

    int result = wxSafeCall<int>(
        []() {
            // wxTheApp should now be a WxdApp instance.
            if (wxTheApp == nullptr) {
                fprintf(stderr, "wxDragon Error: wxTheApp is null after wxEntryStart.\n");
                return wxApp::GetFatalErrorExitCode();
            }
            // CallOnInit will execute WxdApp::OnInit, which calls the Rust g_OnInitCallback.
            if (!wxTheApp->CallOnInit()) {
                // don't call OnExit() if OnInit() failed
                return wxTheApp->GetErrorExitCode();
            }

            // ensure that OnExit() is called if OnInit() had succeeded
            wxON_BLOCK_EXIT_OBJ0(*wxTheApp, wxApp::OnExit);

            // Rust initialization was successful (returned true),
            // then app execution, start the main event loop
            return wxTheApp->OnRun();
        },
        []() {
            wxApp::CallOnUnhandledException();
            return wxApp::GetFatalErrorExitCode();
        });

    wxEntryCleanup();
    g_OnInitCallback = nullptr;
    g_OnInitUserData = nullptr;
    return result;
}

// Gets the handle to the global application instance.
wxd_App_t*
wxd_GetApp()
{
    // wxTheApp is the global pointer to the wxApp instance
    return reinterpret_cast<wxd_App_t*>(wxTheApp);
}

// Sets the top window (main frame) for the application.
void
wxd_App_SetTopWindow(wxd_App_t* app, wxd_Window_t* window)
{
    if (!app || !window)
        return;
    WxdApp* wx_app = reinterpret_cast<WxdApp*>(app);
    wxWindow* wx_window = reinterpret_cast<wxWindow*>(window);
    wx_app->SetTopWindow(wx_window);
}

wxd_Window_t*
wxd_App_GetTopWindow(wxd_App_t* app)
{
    if (!app)
        return nullptr;
    wxApp* wx_app = reinterpret_cast<wxApp*>(app);
    return reinterpret_cast<wxd_Window_t*>(wx_app->GetTopWindow());
}

bool
wxd_App_IsMainLoopRunning(wxd_App_t* app)
{
    if (!app)
        return false;
    return wxApp::IsMainLoopRunning();
}

void
wxd_App_ExitMainLoop(wxd_App_t* app)
{
    if (!app)
        return;
    wxApp* wx_app = reinterpret_cast<wxApp*>(app);
    wx_app->ExitMainLoop();
}

bool
wxd_App_GetExitOnFrameDelete(wxd_App_t* app)
{
    if (!app)
        return true;
    wxApp* wx_app = reinterpret_cast<wxApp*>(app);
    return wx_app->GetExitOnFrameDelete();
}

void
wxd_App_SetExitOnFrameDelete(wxd_App_t* app, bool exitOnFrameDelete)
{
    if (!app)
        return;
    wxApp* wx_app = reinterpret_cast<wxApp*>(app);
    wx_app->SetExitOnFrameDelete(exitOnFrameDelete);
}

void
wxd_App_SetAppName(wxd_App_t* app, const char* name)
{
    if (!app || !name)
        return;
    wxApp* wx_app = reinterpret_cast<wxApp*>(app);
    wx_app->SetAppName(wxString::FromUTF8(name));
}

int
wxd_App_GetAppName(const wxd_App_t* app, char* out, size_t out_len)
{
    if (!app)
        return -1;
    const wxApp* wx_app = reinterpret_cast<const wxApp*>(app);
    return static_cast<int>(wxd_cpp_utils::copy_wxstring_to_buffer(wx_app->GetAppName(), out, out_len));
}

void
wxd_App_SetAppDisplayName(wxd_App_t* app, const char* name)
{
    if (!app || !name)
        return;
    wxApp* wx_app = reinterpret_cast<wxApp*>(app);
    wx_app->SetAppDisplayName(wxString::FromUTF8(name));
}

int
wxd_App_GetAppDisplayName(const wxd_App_t* app, char* out, size_t out_len)
{
    if (!app)
        return -1;
    const wxApp* wx_app = reinterpret_cast<const wxApp*>(app);
    return static_cast<int>(wxd_cpp_utils::copy_wxstring_to_buffer(wx_app->GetAppDisplayName(), out, out_len));
}

void
wxd_App_SetVendorName(wxd_App_t* app, const char* name)
{
    if (!app || !name)
        return;
    wxApp* wx_app = reinterpret_cast<wxApp*>(app);
    wx_app->SetVendorName(wxString::FromUTF8(name));
}

int
wxd_App_GetVendorName(const wxd_App_t* app, char* out, size_t out_len)
{
    if (!app)
        return -1;
    const wxApp* wx_app = reinterpret_cast<const wxApp*>(app);
    return static_cast<int>(wxd_cpp_utils::copy_wxstring_to_buffer(wx_app->GetVendorName(), out, out_len));
}

void
wxd_App_SetVendorDisplayName(wxd_App_t* app, const char* name)
{
    if (!app || !name)
        return;
    wxApp* wx_app = reinterpret_cast<wxApp*>(app);
    wx_app->SetVendorDisplayName(wxString::FromUTF8(name));
}

int
wxd_App_GetVendorDisplayName(const wxd_App_t* app, char* out, size_t out_len)
{
    if (!app)
        return -1;
    const wxApp* wx_app = reinterpret_cast<const wxApp*>(app);
    return static_cast<int>(wxd_cpp_utils::copy_wxstring_to_buffer(wx_app->GetVendorDisplayName(), out, out_len));
}

// Manual callback processing for cases where we need to trigger it
void
wxd_App_ProcessCallbacks()
{
    process_rust_callbacks();
}

// Implementation for wxd_free_int_array
void
wxd_free_int_array(int* ptr)
{
    if (ptr) {
        free(ptr);
    }
}

// --- Appearance Support Implementation (wxWidgets 3.3.0+) ---

#if wxCHECK_VERSION(3, 3, 0)
#include <wx/settings.h>
#include <wx/systhemectrl.h>
#endif

// Set the application appearance mode
wxd_AppearanceResult
wxd_App_SetAppearance(wxd_App_t* app, wxd_Appearance appearance)
{
    if (!app)
        return WXD_APPEARANCE_RESULT_FAILURE;

#if wxCHECK_VERSION(3, 3, 0)
    wxApp* wx_app = reinterpret_cast<wxApp*>(app);

    wxApp::Appearance wx_appearance;
    switch (appearance) {
    case WXD_APPEARANCE_LIGHT:
        wx_appearance = wxApp::Appearance::Light;
        break;
    case WXD_APPEARANCE_DARK:
        wx_appearance = wxApp::Appearance::Dark;
        break;
    case WXD_APPEARANCE_SYSTEM:
    default:
        wx_appearance = wxApp::Appearance::System;
        break;
    }

    wxApp::AppearanceResult result = wx_app->SetAppearance(wx_appearance);

    switch (result) {
    case wxApp::AppearanceResult::Ok:
        return WXD_APPEARANCE_RESULT_OK;
    case wxApp::AppearanceResult::Failure:
        return WXD_APPEARANCE_RESULT_FAILURE;
    case wxApp::AppearanceResult::CannotChange:
        return WXD_APPEARANCE_RESULT_CANNOT_CHANGE;
    }

    return WXD_APPEARANCE_RESULT_FAILURE;
#else
    // For older wxWidgets versions, appearance is not supported
    return WXD_APPEARANCE_RESULT_FAILURE;
#endif
}

// Get system appearance information
wxd_SystemAppearance_t*
wxd_SystemSettings_GetAppearance()
{
#if wxCHECK_VERSION(3, 3, 0)
    wxSystemAppearance appearance = wxSystemSettings::GetAppearance();
    // Create a copy on the heap to return to Rust
    wxSystemAppearance* heap_appearance = new wxSystemAppearance(appearance);
    return reinterpret_cast<wxd_SystemAppearance_t*>(heap_appearance);
#else
    // For older wxWidgets versions, return null
    return nullptr;
#endif
}

// Check if the system is using dark mode
bool
wxd_SystemAppearance_IsDark(wxd_SystemAppearance_t* appearance)
{
    if (!appearance)
        return false;

#if wxCHECK_VERSION(3, 3, 0)
    wxSystemAppearance* wx_appearance = reinterpret_cast<wxSystemAppearance*>(appearance);
    return wx_appearance->IsDark();
#else
    return false;
#endif
}

// Check if the system background is dark
bool
wxd_SystemAppearance_IsUsingDarkBackground(wxd_SystemAppearance_t* appearance)
{
    if (!appearance)
        return false;

#if wxCHECK_VERSION(3, 3, 0)
    wxSystemAppearance* wx_appearance = reinterpret_cast<wxSystemAppearance*>(appearance);
    return wx_appearance->IsUsingDarkBackground();
#else
    return false;
#endif
}

// Get the system appearance name (mainly for macOS)
WXD_EXPORTED int
wxd_SystemAppearance_GetName(const wxd_SystemAppearance_t* appearance, char* out, size_t out_len)
{
    if (!appearance)
        return -1;

#if wxCHECK_VERSION(3, 3, 0)
    const wxSystemAppearance* a = reinterpret_cast<const wxSystemAppearance*>(appearance);
    wxString name = a->GetName();
    return (int)wxd_cpp_utils::copy_wxstring_to_buffer(name, out, out_len);
#endif
    return -1;
}

// Free system appearance object
void
wxd_SystemAppearance_Destroy(wxd_SystemAppearance_t* appearance)
{
    if (!appearance)
        return;

#if wxCHECK_VERSION(3, 3, 0)
    wxSystemAppearance* wx_appearance = reinterpret_cast<wxSystemAppearance*>(appearance);
    delete wx_appearance;
#endif
}

// --- End of Appearance Support Implementation ---

// --- macOS-specific App Event Handlers Implementation ---

#ifdef __WXOSX__

// MacOpenFiles override - calls all registered handlers
void
WxdApp::MacOpenFiles(const wxArrayString& fileNames)
{
    if (m_macCallbacks.openFiles.empty()) {
        // No callbacks registered, use default behavior
        wxApp::MacOpenFiles(fileNames);
        return;
    }

    // Convert wxArrayString to C string array
    size_t count = fileNames.GetCount();
    std::vector<std::string> strings;
    std::vector<const char*> cStrings;
    strings.reserve(count);
    cStrings.reserve(count);

    for (size_t i = 0; i < count; i++) {
        strings.push_back(fileNames[i].ToStdString());
        cStrings.push_back(strings.back().c_str());
    }

    // Call ALL registered Rust callbacks
    for (const auto& pair : m_macCallbacks.openFiles) {
        if (pair.first) {
            pair.first(pair.second, cStrings.data(), static_cast<int>(count));
        }
    }
}

// MacOpenURL override - calls all registered handlers
void
WxdApp::MacOpenURL(const wxString& url)
{
    if (m_macCallbacks.openURL.empty()) {
        wxApp::MacOpenURL(url);
        return;
    }

    std::string urlStr = url.ToStdString();

    // Call ALL registered Rust callbacks
    for (const auto& pair : m_macCallbacks.openURL) {
        if (pair.first) {
            pair.first(pair.second, urlStr.c_str());
        }
    }
}

// MacNewFile override - calls all registered handlers
void
WxdApp::MacNewFile()
{
    if (m_macCallbacks.newFile.empty()) {
        wxApp::MacNewFile();
        return;
    }

    // Call ALL registered Rust callbacks
    for (const auto& pair : m_macCallbacks.newFile) {
        if (pair.first) {
            pair.first(pair.second);
        }
    }
}

// MacReopenApp override - calls all registered handlers
void
WxdApp::MacReopenApp()
{
    if (m_macCallbacks.reopenApp.empty()) {
        wxApp::MacReopenApp();
        return;
    }

    // Call ALL registered Rust callbacks
    for (const auto& pair : m_macCallbacks.reopenApp) {
        if (pair.first) {
            pair.first(pair.second);
        }
    }
}

// MacPrintFiles override - calls all registered handlers
void
WxdApp::MacPrintFiles(const wxArrayString& fileNames)
{
    if (m_macCallbacks.printFiles.empty()) {
        wxApp::MacPrintFiles(fileNames);
        return;
    }

    // Convert wxArrayString to C string array
    size_t count = fileNames.GetCount();
    std::vector<std::string> strings;
    std::vector<const char*> cStrings;
    strings.reserve(count);
    cStrings.reserve(count);

    for (size_t i = 0; i < count; i++) {
        strings.push_back(fileNames[i].ToStdString());
        cStrings.push_back(strings.back().c_str());
    }

    // Call ALL registered Rust callbacks
    for (const auto& pair : m_macCallbacks.printFiles) {
        if (pair.first) {
            pair.first(pair.second, cStrings.data(), static_cast<int>(count));
        }
    }
}

#endif // __WXOSX__

// Registration functions - add handlers to the callback lists
void
wxd_App_AddMacOpenFilesHandler(wxd_App_t* app, wxd_MacOpenFilesCallback callback, void* userData)
{
#ifdef __WXOSX__
    if (!app || !callback)
        return;
    WxdApp* wx_app = reinterpret_cast<WxdApp*>(app);
    wx_app->m_macCallbacks.openFiles.push_back(std::make_pair(callback, userData));
#endif
}

void
wxd_App_AddMacOpenURLHandler(wxd_App_t* app, wxd_MacOpenURLCallback callback, void* userData)
{
#ifdef __WXOSX__
    if (!app || !callback)
        return;
    WxdApp* wx_app = reinterpret_cast<WxdApp*>(app);
    wx_app->m_macCallbacks.openURL.push_back(std::make_pair(callback, userData));
#endif
}

void
wxd_App_AddMacNewFileHandler(wxd_App_t* app, wxd_MacNewFileCallback callback, void* userData)
{
#ifdef __WXOSX__
    if (!app || !callback)
        return;
    WxdApp* wx_app = reinterpret_cast<WxdApp*>(app);
    wx_app->m_macCallbacks.newFile.push_back(std::make_pair(callback, userData));
#endif
}

void
wxd_App_AddMacReopenAppHandler(wxd_App_t* app, wxd_MacReopenAppCallback callback, void* userData)
{
#ifdef __WXOSX__
    if (!app || !callback)
        return;
    WxdApp* wx_app = reinterpret_cast<WxdApp*>(app);
    wx_app->m_macCallbacks.reopenApp.push_back(std::make_pair(callback, userData));
#endif
}

void
wxd_App_AddMacPrintFilesHandler(wxd_App_t* app, wxd_MacPrintFilesCallback callback, void* userData)
{
#ifdef __WXOSX__
    if (!app || !callback)
        return;
    WxdApp* wx_app = reinterpret_cast<WxdApp*>(app);
    wx_app->m_macCallbacks.printFiles.push_back(std::make_pair(callback, userData));
#endif
}

// --- End of macOS-specific App Event Handlers Implementation ---