### Select Installation Method Source: https://github.com/fschutt/azul/blob/master/doc/templates/index.template.html Updates the selected installation method for a given base language and saves it to local storage. This is used to configure how the framework is installed. ```javascript function selectInstallMethod(method) { var baseLang = currentLang.startsWith('cpp') ? 'cpp' : currentLang; currentInstallMethod[baseLang] = method; localStorage.setItem('azul-install-methods', JSON.stringify(currentInstallMethod)); updateAllUI(); } ``` -------------------------------- ### Get Installation Methods for Language Source: https://github.com/fschutt/azul/blob/master/doc/templates/index.template.html Retrieves the available installation methods for a given language. It checks the language configuration for a 'methods' property. ```javascript function getMethods(lang) { // For dialects, check the actual language key (e.g., cpp23) for methods var langConfig = installationConfig.languages[lang]; if (!langConfig || !langConfig.methods) return []; return langConfig.methods; } ``` -------------------------------- ### Get Current Installation Method Source: https://github.com/fschutt/azul/blob/master/doc/templates/index.template.html Determines the current installation method for a given language. It prioritizes the specific language's methods, falling back to the first available method if none is explicitly set. ```javascript function getInstallMethod(lang) { var baseLang = getBaseLang(lang); var methods = getMethods(lang); if (methods.length === 0) return 'default'; return currentInstallMethod[baseLang] || methods[0]; } ``` -------------------------------- ### Azul Installation and Build Commands Source: https://context7.com/fschutt/azul/llms.txt Provides build and installation commands for Azul across different environments. Includes Rust static/dynamic linking, Python PyPI installation, C/C++ linking for Linux, macOS, and Windows, and building the library from source. ```bash # Rust (static linking, default) # Cargo.toml: # [dependencies] # azul = "1.0.0-alpha5" cargo new my-app && cargo build --release ``` ```bash # Rust (dynamic linking for fast iteration) cargo build --release --manifest-path dll/Cargo.toml \ --no-default-features --features "build-dll,std,all_img_formats" # Then in app's Cargo.toml: # [dependencies.azul] # version = "1.0.0-alpha5" # default-features = false # features = ["link-dynamic"] AZUL_LINK_PATH=$(pwd)/target/release cargo run --release ``` ```bash # Python (PyPI) pip install azul # or place azul.so / azul.pyd next to main.py and: from azul import * ``` ```bash # C / C++ (Linux) gcc -O3 -lazul -L/path/to/lib ./main.c -Wl,-rpath,'$ORIGIN' g++ -std=c++17 -O3 -lazul -L/path/to/lib ./main.cpp -Wl,-rpath,'$ORIGIN' ``` ```bash # C / C++ (macOS) clang -O3 -lazul -L/path/to/lib ./main.c -Wl,-rpath,@loader_path clang++ -std=c++17 -O3 -lazul -L/path/to/lib ./main.cpp -Wl,-rpath,@loader_path ``` ```bash # C / C++ (Windows MSVC) cl main.c azul.lib cl /std:c++17 main.cpp azul.lib ``` ```bash # Build library from source git clone https://github.com/fschutt/azul && cd azul cargo build --release --manifest-path doc/Cargo.toml ``` -------------------------------- ### Build and Run Azul Example Source: https://github.com/fschutt/azul/blob/master/scripts/SCROLLBAR_BUGS_S10.md Steps to build the Azul project with specific features and then compile and run a C example that reproduces a scrollbar-related crash. ```bash cd /Users/fschutt/Development/azul cargo build --features build-dll --release cd examples/c cc -o scrolling.bin scrolling.c -lazul -L../../target/release -I../../dll AZUL_DEBUG=8765 DYLD_LIBRARY_PATH=../../target/release ./scrolling.bin # → Resize the window → crash ``` -------------------------------- ### Install Git on Debian/Ubuntu Source: https://github.com/fschutt/azul/blob/master/scripts/linux-install.txt Installs the Git version control system using apt. This is a prerequisite for cloning the repository. ```bash sudo apt install git ``` -------------------------------- ### Build and Run Azul DLL and Example Source: https://github.com/fschutt/azul/blob/master/scripts/SVG_CLIP_MASKS_AGENT_PROMPT.md Commands to build the Azul DLL, copy C API headers, compile a C example, and run it. Includes instructions for setting library paths and enabling debug server. ```bash # Build DLL cargo build -p azul-dll --features build-dll --release ``` ```bash # Build example cp target/codegen/v2/azul.h examples/c/azul.h cd examples/c cc -o chart chart.c -I. -L../../target/release -lazul -Wl,-rpath,../../target/release ``` ```bash # Run DYLD_LIBRARY_PATH=../../target/release ./chart ``` ```bash # Run with debug server for inspection AZUL_DEBUG=8766 DYLD_LIBRARY_PATH=../../target/release ./chart ``` ```bash # Take screenshots via debug server curl -s -X POST http://localhost:8766/ -d '{"op": "take_native_screenshot"}' > native.json curl -s -X POST http://localhost:8766/ -d '{"op": "take_screenshot"}' > cpu.json ``` -------------------------------- ### Initialize and Use GnomeMenuManager in Rust Source: https://github.com/fschutt/azul/blob/master/dll/src/desktop/shell2/linux/gnome_menu/README.md Example of initializing GnomeMenuManager, setting window properties, and updating menus. Handles potential errors during setup and updates. ```rust use azul_dll::desktop::shell2::linux::gnome_menu::GnomeMenuManager; // In X11Window::new_with_resources() if options.state.flags.use_native_menus { if let Some(title) = options.state.title.as_ref() { match GnomeMenuManager::new(title.as_str()) { Some(menu_manager) => { match menu_manager.set_window_properties(window.window, display as *mut _) { Ok(_) => { println!("GNOME menus enabled"); window.gnome_menu = Some(menu_manager); } Err(e) => { eprintln!("GNOME menu setup failed: {} - using CSD", e); // Continue with CSD menus } } } None => { println!("GNOME menus not available - using CSD"); } } } } // Later, when menu changes if let Some(ref menu_manager) = window.gnome_menu { if let Err(e) = menu_manager.update_menu(&new_menu) { eprintln!("Failed to update GNOME menu: {}", e); // CSD menu is still functional } } ``` -------------------------------- ### App::create() - New Asynchronous Font Loading Setup Source: https://github.com/fschutt/azul/blob/master/scripts/STARTUP_LATENCY.md Demonstrates the refactored `App::create()` method using `FcFontRegistry` for asynchronous font loading. This setup significantly reduces startup time by performing font operations in the background. ```rust let registry = Arc::new(FcFontRegistry::new()); registry.register_memory_fonts(bundled_fonts); registry.load_from_disk_cache(); registry.spawn_scout(); registry.spawn_builder_pool(num_cpus); ``` -------------------------------- ### Complete Todo List App Example Source: https://github.com/fschutt/azul/blob/master/doc/guide/getting-started-python.md A full example of an Azul application demonstrating state management, UI rendering, and user interaction for a todo list. ```python from azul import * class TodoApp: def __init__(self): self.items = ["Buy groceries", "Walk the dog", "Learn Azul"] self.new_item = "" def on_add_item(data, info): if data.new_item.strip(): data.items.append(data.new_item) data.new_item = "" return Update.RefreshDom return Update.DoNothing def layout(data, info): items = [ Dom.div() .with_inline_style("padding: 8px; border-bottom: 1px solid #ccc;") .with_child(Dom.text(item)) for item in data.items ] return Dom.body() \ .with_inline_style("padding: 20px; font-family: sans-serif;") \ .with_child(Dom.div() .with_inline_style("font-size: 24px; margin-bottom: 20px;") .with_child(Dom.text("Todo List"))) .with_children(items) .style(Css.empty()) app = App(TodoApp(), AppConfig(layout)) app.run(WindowCreateOptions.default()) ``` -------------------------------- ### Rust Usage Example Source: https://github.com/fschutt/azul/blob/master/dll/src/desktop/shell2/linux/gnome_menu/README.md Example demonstrating how to initialize and use the GnomeMenuManager in a Rust application, including setting window properties and updating menus. ```rust use azul_dll::desktop::shell2::linux::gnome_menu::GnomeMenuManager; // In X11Window::new_with_resources() if options.state.flags.use_native_menus { if let Some(title) = options.state.title.as_ref() { match GnomeMenuManager::new(title.as_str()) { Some(menu_manager) => { match menu_manager.set_window_properties(window.window, display as *mut _) { Ok(_) => { println!("GNOME menus enabled"); window.gnome_menu = Some(menu_manager); } Err(e) => { eprintln!("GNOME menu setup failed: {} - using CSD", e); // Continue with CSD menus } } } None => { println!("GNOME menus not available - using CSD"); } } } } // Later, when menu changes if let Some(ref menu_manager) = window.gnome_menu { if let Err(e) = menu_manager.update_menu(&new_menu) { eprintln!("Failed to update GNOME menu: {}", e); // CSD menu is still functional } } ``` -------------------------------- ### Install Azul Source: https://github.com/fschutt/azul/blob/master/doc/guide/getting-started-python.md Install the Azul library using pip. This is the first step to using Azul in your Python project. ```bash pip install azul ``` -------------------------------- ### Win32Window Implementation Example Source: https://github.com/fschutt/azul/blob/master/scripts/PLATFORM_WINDOW_REFACTORING.md Example of how a specific platform, Win32Window, implements the PlatformWindow trait, utilizing the macro for common getters and providing platform-specific logic for other methods. ```APIDOC ## Implementation: Win32Window for PlatformWindow ### Description Provides a concrete implementation of the `PlatformWindow` trait for the Win32 platform. ### Methods #### Macro-Generated Getters - `impl_platform_window_getters!(common);`: This macro call generates all 28 required getter and setter methods. #### Overridden Methods - `poll_event(&mut self) -> ...`: Win32-specific event polling. - `request_redraw(&mut self)`: Win32-specific redraw request. - `is_open(&self) -> bool`: Returns the `is_open` status of the Win32 window. - `get_raw_window_handle(&self) -> RawWindowHandle`: Returns the HWND for the Win32 window. - `start_timer(&mut self, ...)`: Uses Win32's `SetTimer` function. - `stop_timer(&mut self, ...)`: Uses Win32's `KillTimer` function. - `start_thread_poll_timer(&mut self)`: Uses Win32's `SetTimer(0xFFFF)`. - `stop_thread_poll_timer(&mut self)`: Uses Win32's `KillTimer(0xFFFF)`. - `sync_window_state(&mut self)`: Uses Win32 functions like `SetWindowPos`. - `show_tooltip_from_callback(&mut self, ...)`: Implements Win32 tooltip functionality. - `hide_tooltip_from_callback(&mut self)`: Hides the Win32 tooltip. - `prepare_callback_invocation(&mut self) -> ...`: Handles Win32-specific callback invocation preparation. ``` -------------------------------- ### Install Toolchain and Bash Source: https://github.com/fschutt/azul/blob/master/scripts/INSTALLATION_WINDOWS.txt Installs the MinGW-w64 UCRT toolchain and bash shell, essential for development. ```bash pacman -S mingw-w64-ucrt-x86_64-toolchain bash ``` -------------------------------- ### GNOME Actions Interface - Describe Method Example Source: https://github.com/fschutt/azul/blob/master/dll/src/desktop/shell2/linux/gnome_menu/README.md Example output for the Describe() method of the org.gtk.Actions interface, showing action details including enabled status, parameter type, and state. ```text (true, "", []) ``` -------------------------------- ### Linux Configuration File Example Source: https://github.com/fschutt/azul/blob/master/scripts/SYSTEMSTYLE.md Example of a standard INI file format used for GTK settings on Linux. Parsing this file is a fallback for discovering settings when DBus is unavailable. ```ini [Settings] gtk-double-click-time=400 gtk-enable-animations=1 gtk-menu-images=0 ``` -------------------------------- ### GNOME Actions Interface - List Method Example Source: https://github.com/fschutt/azul/blob/master/dll/src/desktop/shell2/linux/gnome_menu/README.md Example output for the List() method of the org.gtk.Actions interface, which returns an array of all available action names. ```text ["app.file.new", "app.file.open", "app.quit"] ``` -------------------------------- ### Copy Example Code to Clipboard Source: https://github.com/fschutt/azul/blob/master/doc/templates/index.template.html Copies the currently displayed example code for a given ID to the clipboard, considering language variants. ```javascript function copyExampleCode(id) { var ex = examples[id]; if (!ex) return; var code = ex['code_' + currentLang]; if (!code && isDialect(currentLang)) { code = ex['code_' + currentCppVersion] || ex['code_cpp23'] || ''; } if (code) navigator.clipboard.writeText(code); } ``` -------------------------------- ### Update Install Commands Source: https://github.com/fschutt/azul/blob/master/doc/templates/index.template.html Renders installation steps for a given container. It supports command, code, and text step types, fetching configuration based on the current language and operating system. ```javascript function updateInstallCommands(container) { // For installation, use the actual language key (e.g., cpp23 for specific install steps) var langConfig = installationConfig.languages[currentLang]; if (!langConfig) { container.innerHTML = '
Select a language
'; return; } var steps = null; // Check for method-based installation (e.g., pip vs uv for Python) if (langConfig.methods && langConfig.methods.length > 0 && langConfig.methodSteps) { var method = getInstallMethod(currentLang); steps = langConfig.methodSteps[method]; } // Fall back to platform-specific steps if (!steps) { steps = langConfig[currentOS]; } if (!steps || steps.length === 0) { container.innerHTML = ''; return; } var html = ''; steps.forEach(function(step) { if (step.type === 'command') { html += '
' + '' + escHtml(step.content) + '' + '' + '
'; } else if (step.type === 'code') { html += '
' + '
' + escHtml(step.content) + '
' + '' + '
'; } else if (step.type === 'text') { html += '
' + escHtml(step.content) + '
'; } }); container.innerHTML = html; } ``` -------------------------------- ### GNOME Menu Debug Output Examples Source: https://github.com/fschutt/azul/blob/master/dll/src/desktop/shell2/linux/gnome_menu/README.md Examples of debug logging output from the GNOME menu module, which can be enabled using the `AZUL_GNOME_MENU_DEBUG` environment variable. ```text [AZUL GNOME MENU] Creating GNOME menu manager for app: MyApp [AZUL GNOME MENU] DBus connection established [AZUL GNOME MENU] Registering org.gtk.Menus interface with DBus [AZUL GNOME MENU] Setting X11 window properties for GNOME menu [AZUL GNOME MENU] Menu update complete ``` -------------------------------- ### C Example: Chart Widget with Clip Masks Source: https://github.com/fschutt/azul/blob/master/scripts/SVG_CLIP_MASKS_AGENT_PROMPT.md Demonstrates a C example using Azul to create a bar chart with clip masks and an animated pie chart. It shows how to attach clip masks to gradient divs and handle CPU/GPU rendering toggles. ```bash cp target/codegen/v2/azul.h examples/c/azul.h cd examples/c cc -o chart chart.c -I. -L../../target/release -lazul -Wl,-rpath,../../target/release DYLD_LIBRARY_PATH=../../target/release ./chart ``` -------------------------------- ### Initialize App and Create Window in Rust Source: https://context7.com/fschutt/azul/llms.txt Demonstrates the basic setup for an Azul application, including defining application state, a layout callback function, and running the event loop. ```rust use azul::prelude::*; struct DataModel { counter: usize, } // Layout callback: pure fn(state) -> UI, called on every RefreshDom extern "C" fn my_layout(mut data: RefAny, _: LayoutCallbackInfo) -> Dom { let counter = match data.downcast_ref::() { Some(d) => format!("{}", d.counter), None => return Dom::create_body(), }; let mut label = Dom::create_text(counter.as_str()); label.set_inline_style("font-size: 50px"); Dom::create_body() .with_inline_style("background-color: #f5f5f5; padding: 20px;") .with_child(label) } fn main() { let data = DataModel { counter: 0 }; let config = AppConfig::create(); let app = App::create(RefAny::new(data), config); let window = WindowCreateOptions::create(my_layout_func); app.run(window); // blocks until window is closed } ``` -------------------------------- ### Start Azul Application with Debug Mode Source: https://github.com/fschutt/azul/blob/master/scripts/DEBUG_API.md Start your Azul application with the AZUL_DEBUG environment variable set to enable the debug API. Then, check if the server is running by sending a GET request to the root endpoint. ```bash # Start your Azul application with the `AZUL_DEBUG` env var AZUL_DEBUG=8765 ./your_app # Check that the server is running curl http://localhost:8765/ ``` -------------------------------- ### Get App State Response (Serialization Error) Source: https://github.com/fschutt/azul/blob/master/scripts/DEBUG_API.md Example JSON response for a get_app_state request when serialization is not supported, indicating an error. ```json { "data": { "type": "app_state", "value": { "metadata": { ... }, "state": null, "error": { "error_type": "not_serializable" } } } } ``` -------------------------------- ### Get Cursor Property Source: https://github.com/fschutt/azul/blob/master/scripts/COMPACT_CACHE_STATUS.md Example of a getter function that could be used for hit testing, potentially replacing direct cache access. ```rust get_cursor_property() ``` -------------------------------- ### Hello World Application Source: https://github.com/fschutt/azul/blob/master/doc/guide/getting-started-cpp.md A basic Azul application demonstrating state management, UI layout, and window creation. ```cpp #include "azul.hpp" #include // Your application state class MyApp { public: int counter = 0; MyApp() = default; }; // Layout function - converts state to UI StyledDom layout(RefAny& data, LayoutCallbackInfo& info) { auto app = data.downcastRef(); if (!app) { return StyledDom::default_(); } auto text = "Counter: " + std::to_string(app->ptr.counter); return Dom::body() .withChild(Dom::text(String::fromStdString(text))) .style(Css::empty()); } int main() { auto data = RefAny::new_(std::move(MyApp())); auto app = App::new_(std::move(data), AppConfig::new_((LayoutCallbackType)layout)); app.run(WindowCreateOptions::default_()); return 0; } ``` -------------------------------- ### Get App State Response (Success) Source: https://github.com/fschutt/azul/blob/master/scripts/DEBUG_API.md Example JSON response for a successful get_app_state request, showing full metadata for a RefAny type. ```json { "status": "ok", "request_id": 1, "data": { "type": "app_state", "value": { "metadata": { "type_id": 4375150160, "type_name": "MyDataModel", "can_serialize": true, "can_deserialize": true }, "state": { "counter": 42.0 } } } } ``` -------------------------------- ### Hello World Application in C Source: https://github.com/fschutt/azul/blob/master/doc/guide/getting-started-c.md Creates a basic Azul application with a counter that increments on button click. Requires including 'azul.h'. ```c #include "azul.h" // Your application state typedef struct { int counter; } MyApp; // Destructor (required by AZ_REFLECT) void MyApp_destructor(MyApp* instance) { } AZ_REFLECT(MyApp, MyApp_destructor); // Layout function - converts state to UI AzStyledDom layout(AzRefAny* data, AzLayoutCallbackInfo info) { MyAppRef app_ref = MyAppRef_create(data); MyApp* app; if (!MyApp_downcastRef(data, &app_ref)) { return AzStyledDom_default(); } char text[64]; snprintf(text, sizeof(text), "Counter: %d", app_ref.ptr->counter); AzDom body = AzDom_body(); AzDom_addChild(&body, AzDom_text(AzString_fromConstStr(text))); MyAppRef_delete(&app_ref); return AzDom_style(body, AzCss_empty()); } int main() { MyApp initial_state = { .counter = 0 }; AzRefAny data = MyApp_upcast(initial_state); AzApp app = AzApp_new(data, AzAppConfig_new((AzLayoutCallbackType)layout)); AzApp_run(app, AzWindowCreateOptions_default()); return 0; } ``` -------------------------------- ### Get Dialect Variants Source: https://github.com/fschutt/azul/blob/master/doc/templates/index.template.html Retrieves the available dialect variants for a given dialect group from the installation configuration. This is used to populate dropdowns for selecting language versions. ```javascript function getDialectVariants(dialectGroup) { var dialect = installationConfig.dialects[dialectGroup]; if (!dialect) return {}; return dialect.variants; } ``` -------------------------------- ### Initialize Azul GUI Framework Source: https://github.com/fschutt/azul/blob/master/doc/templates/index.template.html Initializes the framework by loading saved language, OS, and installation method preferences from local storage. If no saved preferences are found, it defaults to 'rust' for language and 'linux' for OS. ```javascript var examples = $$JAVASCRIPT_EXAMPLES$$; var installationConfig = $$JAVASCRIPT_INSTALLATION$$; var currentLang = 'rust'; var currentOS = detectOS(); var currentCppVersion = 'cpp23'; var currentInstallMethod = {}; // Init from localStorage (function() { var savedLang = localStorage.getItem('azul-lang'); var savedOS = localStorage.getItem('azul-os'); var savedCpp = localStorage.getItem('azul-cpp-version'); var savedMethods = localStorage.getItem('azul-install-methods'); if (savedLang) currentLang = savedLang; if (savedOS) currentOS = savedOS; if (savedCpp) currentCppVersion = savedCpp; if (savedMethods) { try { currentInstallMethod = JSON.parse(savedMethods); } catch(e) {} } // Check if savedLang is a dialect variant (will be validated after functions load) })(); ``` -------------------------------- ### Get Base Language Source: https://github.com/fschutt/azul/blob/master/doc/templates/index.template.html Returns the base language group for a given language. For example, if the input is 'cpp23', it returns 'cpp'. This is useful for grouping language variants. ```javascript function getBaseLang(lang) { var langConfig = installationConfig.languages[lang]; if (langConfig && langConfig.dialectOf) { return langConfig.dialectOf; } return lang; } ``` -------------------------------- ### Instantiate and Run App Source: https://github.com/fschutt/azul/blob/master/scripts/TODO_LIST.md This Python code instantiates an `App` with a `TodoApp` and `AppConfig`, then runs the application with default window creation options. ```python app = App(TodoApp(), AppConfig(layout)) app.run(WindowCreateOptions.default()) ``` -------------------------------- ### Rust OpenGL Reference Example Source: https://github.com/fschutt/azul/blob/master/scripts/OPENGL_DEBUG_TASK.md The Rust reference example for OpenGL debugging, demonstrating similar functionality to the C example. ```rust use std::ffi::c_void; use glow::HasContext; const VERTEX_SHADER_SOURCE: &str = "#version 430 core\n" "layout (location = 0) in vec2 aPos;\n" "void main()\n" "{\n" " gl_Position = vec4(aPos.x, aPos.y, 0.0, 1.0);\n" "}"; const FRAGMENT_SHADER_SOURCE: &str = "#version 430 core\n" "out vec4 FragColor;\n" "void main()\n" "{\n" " FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n" "}"; fn main() { // Initialize OpenGL context (implementation-specific) // ... (e.g., using glutin, winit, or other windowing libraries) let glow_context = unsafe { glow::Context::from_loader_function(|s| get_proc_address(s) as *const _) }; // Create shaders let vertex_shader = glow_context .create_shader(glow::VERTEX_SHADER) .expect("Failed to create vertex shader"); glow_context .shader_source(vertex_shader, VERTEX_SHADER_SOURCE); glow_context.compile_shader(vertex_shader); check_shader_compilation(&glow_context, vertex_shader, "Vertex Shader"); let fragment_shader = glow_context .create_shader(glow::FRAGMENT_SHADER) .expect("Failed to create fragment shader"); glow_context .shader_source(fragment_shader, FRAGMENT_SHADER_SOURCE); glow_context.compile_shader(fragment_shader); check_shader_compilation(&glow_context, fragment_shader, "Fragment Shader"); // Create shader program let shader_program = glow_context .create_program() .expect("Failed to create shader program"); glow_context.attach_shader(shader_program, vertex_shader); glow_context.attach_shader(shader_program, fragment_shader); glow_context.link_program(shader_program); check_program_linking(&glow_context, shader_program, "Shader Program"); // Enable debug output if available unsafe { if let Some(debug_message_callback) = glow_context.debug_message_callback { glow_context.enable(glow::DEBUG_OUTPUT); glow_context.enable(glow::DEBUG_OUTPUT_SYNCHRONOUS); debug_message_callback(Some(error_callback), None); } } // Define vertices for a triangle let vertices: [f32; 6] = [ -0.5, -0.5, // bottom-left 0.5, -0.5, // bottom-right 0.0, 0.5, // top ]; // Create Vertex Buffer Object (VBO) and Vertex Array Object (VAO) let vao = glow_context .create_vertex_array() .expect("Failed to create VAO"); let vbo = glow_context .create_buffer() .expect("Failed to create VBO"); // Bind VAO and VBO unsafe { glow_context.bind_vertex_array(Some(vao)); glow_context.bind_buffer(glow::ARRAY_BUFFER, Some(vbo)); glow_context.buffer_data(glow::ARRAY_BUFFER, &vertices, glow::STATIC_DRAW); // Configure vertex attributes glow_context.vertex_attrib_pointer(0, 2, glow::FLOAT, false, 4 * 2, 0); // 2 floats * 4 bytes/float glow_context.enable_vertex_attrib_array(0); // Unbind VBO and VAO glow_context.bind_buffer(glow::ARRAY_BUFFER, None); glow_context.bind_vertex_array(None); } // Main render loop (implementation-specific) // ... (e.g., clear screen, use shader program, bind VAO, draw arrays, swap buffers) // Example render call: unsafe { glow_context.clear_color(0.2, 0.3, 0.3, 1.0); glow_context.clear(glow::COLOR_BUFFER_BIT); glow_context.use_program(Some(shader_program)); glow_context.bind_vertex_array(Some(vao)); glow_context.draw_arrays(glow::TRIANGLES, 0, 3); glow_context.bind_vertex_array(None); } // Swap buffers (implementation-specific) // ... // Clean up unsafe { glow_context.delete_program(shader_program); glow_context.delete_shader(vertex_shader); glow_context.delete_shader(fragment_shader); glow_context.delete_buffer(vbo); glow_context.delete_vertex_array(vao); } } unsafe fn get_proc_address(symbol: &str) -> *const c_void { // Implementation-specific function to get OpenGL function pointers // For example, using `std::mem::transmute` with platform-specific functions // or a library like `libloading`. std::ptr::null() // Placeholder } unsafe fn check_shader_compilation(gl: &glow::Context, shader: glow::Shader, name: &str) { if !gl.get_shader_compile_status(shader) { let log = gl.get_shader_info_log(shader); panic!("Shader compilation error in {}: {}", name, log); } } unsafe fn check_program_linking(gl: &glow::Context, program: glow::Program, name: &str) { if !gl.get_program_link_status(program) { let log = gl.get_program_info_log(program); panic!("Program linking error in {}: {}", name, log); } } unsafe extern "C" fn error_callback(source: u32, type_: u32, id: u32, severity: u32, length: i32, message: *const i8, user_param: *mut c_void) { let message = std::slice::from_raw_parts(message as *const u8, length as usize); let message = std::str::from_utf8_unchecked(message); eprintln!("GL Error: {}", message); } ``` -------------------------------- ### Build and Run OpenGL Application Source: https://github.com/fschutt/azul/blob/master/scripts/OPENGL_DEBUG_TASK.md Commands to build the Azul library, compile the C example application, and run it with the debug server enabled. Includes instructions for taking a native screenshot using curl and Python. ```bash # 1. Build the library cargo build --release -p azul-dll # 2. Copy the generated header and compile cp target/codegen/v2/azul.h examples/c/azul.h cd examples/c cc -o opengl opengl.c -I. -L../../target/release -lazul \ -Wl,-rpath,../../target/release # 3. Run with debug server cd ../.. AZUL_DEBUG=8765 examples/c/opengl # 4. In another terminal – take a native screenshot PORT=8765; API="http://localhost:$PORT" curl -s -X POST $API/ -d '{"op":"take_native_screenshot"}' \ | python3 -c "import sys,json,base64; d=json.load(sys.stdin); \ open('screenshot.png','wb').write(base64.b64decode(d['data']['screenshot']))" ``` -------------------------------- ### Component Structure Example Source: https://github.com/fschutt/azul/blob/master/scripts/COMPONENT_TYPE_SYSTEM_DESIGN.md Illustrates a project structure separating UI, logic, and application assembly into distinct crates. ```text my_app/ ├── my_ui_crate/ ← component definitions (templates, CSS, data models) │ ├── avatar.json ← dynamic component (design-time) │ └── avatar.rs ← compiled component (after codegen) │ ├── my_logic_crate/ ← callback implementations (pure business logic) │ └── handlers.rs ← fn navigate_to_href(...), fn load_avatar(...) │ └── my_app_crate/ ← application assembly └── main.rs ← creates ComponentMap, registers libraries, runs app ``` -------------------------------- ### Application Initialization Source: https://github.com/fschutt/azul/blob/master/doc/guide/architecture.md Initializes and runs the main application with AgeInput and default configuration. ```python app = App(AgeInput(18), AppConfig(LayoutSolver.Default)) app.run(WindowCreateOptions(layout_func)) ``` -------------------------------- ### Azul App::create() Startup Sequence Source: https://github.com/fschutt/azul/blob/master/scripts/STARTUP_LATENCY.md Outlines the steps involved in creating an Azul application, from initializing the font registry to spawning worker threads. ```rust App::create(initial_data, config): │ ├── 1. Create empty FcFontRegistry │ ├── 2. Register bundled fonts (Material Icons, etc.) ← <1ms │ ├── 3. Try to load on-disk font cache │ ├── If found: deserialize ALL font metadata ← ~10-20ms │ │ into Registry immediately. Mark all entries │ │ as "from_cache" (needs background verification) │ └── If not found: Registry starts empty │ ├── 4. Spawn Scout thread ← returns immediately │ Scout enumerates dirs, feeds Builder queue │ Also detects stale/new/removed fonts vs cache │ ├── 5. Spawn Builder pool (N threads) ← returns immediately │ Starts processing queue (High-priority first) │ └── return App (total: <25ms with cache, <5ms without) ``` -------------------------------- ### Timer ID Example Source: https://github.com/fschutt/azul/blob/master/scripts/scroll3.md This shows an example of a reserved timer ID, indicating that the timer system is already in use for specific functionalities. ```rust const AUTO_SCROLL_TIMER_ID: u32 = 0xABCD_1234; ``` -------------------------------- ### Build Initial Menu State Source: https://github.com/fschutt/azul/blob/master/scripts/TODO_LIST.md This comment suggests a TODO to build the initial menu state from the `layout_window` data. ```rust menu_state: menu::MenuState::new(), // TODO: build initial menu state from layout_window ``` -------------------------------- ### Get Component Preview Source: https://github.com/fschutt/azul/blob/master/scripts/COMPONENT_SYSTEM_STATUS.md This endpoint allows you to get a preview of a component rendered via the CPU renderer. It returns a base64-encoded PNG image. ```APIDOC ## POST /get_component_preview ### Description Generates a PNG preview of a component using the CPU renderer. ### Method POST ### Endpoint /get_component_preview ### Request Body - **op** (string) - Required - Operation name, should be "get_component_preview". - **component** (string) - Required - The component identifier (e.g., "builtin:div"). - **config** (object) - Required - Configuration for the preview. - **width** (integer) - Optional - The desired width of the preview. Null for auto-fit. - **height** (integer) - Optional - The desired height of the preview. Null for auto-fit. - **theme** (string) - Optional - The theme to use for rendering ('light' or 'dark'). - **os** (string) - Optional - The target operating system for rendering ('macos', 'windows', 'linux'). - **data** (object) - Optional - JSON object to populate the component's data model, overriding defaults. ### Request Example ```json { "op": "get_component_preview", "component": "builtin:div", "config": { "width": 300, "height": 200, "theme": "dark", "os": "macos", "data": { } } } ``` ### Response #### Success Response (200) - **image** (string) - Base64-encoded PNG image of the component preview. ``` -------------------------------- ### Field Editor Widget Rendering Example Source: https://github.com/fschutt/azul/blob/master/scripts/PLAN_JS_REUSABLE_COMPONENTS.md Demonstrates how to render the FieldEditor widget. This example appends the rendered element to the document body for testing purposes. ```javascript var el = app.widgets.FieldEditor.render( { name: 'test', fieldType: { type: 'String' }, readOnly: false }, { value: 'hello' }, { onChange: function(n, v) { console.log(n, v); } } ); document.body.appendChild(el); ``` -------------------------------- ### Constructor Usage Source: https://github.com/fschutt/azul/blob/master/doc/guide/getting-started-cpp.md Demonstrates creating objects using default and explicit constructors. ```cpp // API: struct ColorU { r: u8, g: u8, b: u8, a: u8 } auto color = ColorU(/*r*/ 255, /*g*/ 255, /*b*/ 255, /*a*/ 255); ``` ```cpp auto window = WindowCreateOptions::default_(LayoutSolver::Default); ``` -------------------------------- ### JavaScript Field Type Parsing Examples Source: https://github.com/fschutt/azul/blob/master/scripts/PLAN_COMPONENT_HIERARCHY.md Provides examples of how various string representations of field types are converted into structured objects by the `_parseFieldType` function. ```javascript - "String" → { type: "String" } - "Option" → { type: "Option", inner: { type: "String" } } - "Vec" → { type: "Vec", inner: { type: "i32" } } - "StyledDom" → { type: "StyledDom" } - "Callback(ButtonOnClick)" → { type: "Callback", signature: "ButtonOnClick" } ``` -------------------------------- ### Bottleneck Analysis Table Source: https://github.com/fschutt/azul/blob/master/scripts/STARTUP_LATENCY.md Summarizes the key performance bottlenecks during application startup, including time, location, and the specific problem. ```text | Phase | Time | Location | Problem | |---|---|---|---| | `FcFontCache::build()` | ~700ms | `dll/src/desktop/app.rs:150` | Scans + deep-parses ALL 1000 fonts | | `verify_unicode_ranges_with_cmap()` | ~400ms of the 700ms | `rust-fontconfig/src/lib.rs:3636` | Per-font CMAP glyph verification | | `Shaders::new()` | ~100-200ms | `dll/src/desktop/shell2/macos/mod.rs:2593` | Compiles ~60 WebRender shaders | | First layout only uses ~2-5 fonts | 0ms (wasted) | `layout/src/solver3/paged_layout.rs:143` | 995+ fonts parsed for nothing | ``` -------------------------------- ### Implement PlatformWindowV2 for X11Window Source: https://github.com/fschutt/azul/blob/master/scripts/PLATFORM_WINDOW_REFACTORING.md This example demonstrates the implementation of the `PlatformWindowV2` trait for `X11Window`, utilizing the `impl_platform_window_getters!` macro to include the common getter methods. This approach minimizes code duplication across different platform implementations. ```rust impl PlatformWindowV2 for X11Window { impl_platform_window_getters!(common); // ... } ``` -------------------------------- ### User Stylesheet Example CSS Source: https://github.com/fschutt/azul/blob/master/doc/guide/styling-system.md Example CSS content for a user-customizable stylesheet. This demonstrates overriding default styles for buttons, custom classes, and the body element. ```css /* Override button styling */ button { background: linear-gradient(to bottom, #667eea, #764ba2); border-radius: 20px; color: white; } /* Custom accent color */ .accent { background: system:accent; } /* Dark theme override */ body { background: #1a1a2e; color: #eaeaea; } ``` -------------------------------- ### Build DLL and Recompile hello-world Source: https://github.com/fschutt/azul/blob/master/scripts/HELLO_WORLD_LAYOUT_INVESTIGATION.md Commands to rebuild the Azul DLL and recompile the hello-world C example after applying fixes. ```bash cargo build --release -p azul-dll --features build-dll ``` ```bash scripts/collect_hello_world_debug.sh 8765 ``` -------------------------------- ### Get Colorization Color (Windows) Source: https://github.com/fschutt/azul/blob/master/scripts/SYSTEMSTYLE.md Gets the user's accent color and transparency blend for desktop window management on Windows. Requires loading Dwmapi.dll. ```c DwmGetColorizationColor: Gets the user's accent color and transparency blend. ``` -------------------------------- ### Implement PlatformWindowV2 for Win32Window Source: https://github.com/fschutt/azul/blob/master/scripts/PLATFORM_WINDOW_REFACTORING.md This example shows how to implement the `PlatformWindowV2` trait for `Win32Window` by invoking the `impl_platform_window_getters!` macro. This consolidates the common getter methods, leaving only platform-specific logic. ```rust impl PlatformWindowV2 for Win32Window { impl_platform_window_getters!(common); // ← generates all 28 methods // ... only ~10 platform-specific methods remain } ``` -------------------------------- ### Rendering Pipeline Steps Source: https://github.com/fschutt/azul/blob/master/scripts/OPENGL_DOM_DIFF_OPTIMIZATION.md Illustrates the full rendering pipeline triggered by Update::RefreshDom, highlighting the expensive steps that can be skipped. ```text layout() → CSS cascade → flexbox → display list → image callbacks → composite ``` -------------------------------- ### Update Example Code Snippet Source: https://github.com/fschutt/azul/blob/master/doc/templates/index.template.html Updates the displayed code example for a given ID based on the current language. It handles language variants and applies syntax highlighting using Prism. ```javascript function updateExampleCode(id) { var ex = examples[id]; if (!ex) return; var code = ex['code_' + currentLang]; // For dialect variants, try the specific variant first, then fallback if (!code && isDialect(currentLang)) { code = ex['code_' + currentCppVersion] || ex['code_cpp23'] || ''; } if (!code) code = ''; // Map language to Prism language class var prismLang = currentLang; if (currentLang.startsWith('cpp')) prismLang = 'cpp'; if (currentLang === 'c') prismLang = 'c'; if (currentLang === 'python') prismLang = 'python'; if (currentLang === 'rust') prismLang = 'rust'; var el = document.getElementById('example-code-' + id); if (el) { var codeEl = document.createElement('code'); codeEl.className = 'language-' + prismLang; codeEl.textContent = code; var preEl = document.createElement('pre'); preEl.appendChild(codeEl); el.innerHTML = ''; el.appendChild(preEl); el.insertAdjacentHTML('beforeend', ''); // Apply Prism highlighting if (typeof Prism !== 'undefined') { Prism.highlightElement(codeEl); } } } ``` -------------------------------- ### Initializing and Teardown Player with Lifecycle Callbacks Source: https://github.com/fschutt/azul/blob/master/doc/guide/lifecycle.md Illustrates using `On::AfterMount` and `On::BeforeUnmount` callbacks to manage external resources like a video player's library handle. `initialize_player` loads the library and starts playback on mount, while `teardown_player` cleans up resources before unmount. ```rust struct MyAppData { // Only store the video path, not the actual player state current_video: PathBuf, playing: bool, } struct MyVideoPlayer { video: PathBuf, playing: bool, lib_handle: Option<*mut c_void> } extern "C" fn my_layout(data: RefAny, info: LayoutCallbackInfo) -> StyledDom { let data = data.downcast_ref::().unwrap(); let uidata = MyVideoPlayer { video: data.video.clone(), position. data.playing, lib_handle: None, // see initialize_player }; let dataset = RefAny::new(uidata); Dom::div() .with_callback(On::AfterMount, dataset.clone(), initialize_player) .with_callback(On::BeforeUnmount, dataset.clone(), teardown_player) } extern "C" fn initialize_player(data: RefAny, info: CallbackInfo) -> Update { let mut player = info.downcast_mut::().unwrap(); if player.lib_handle.is_none() { // video player hasn't been initialized - load library here player.lib_handle = dlopen("libffmpeg.so"); player.start_playing(); // video just starts } Update::DoNothing } extern "C" fn teardown_player(data: RefAny, info: CallbackInfo) -> Update { let mut player = info.downcast_mut::().unwrap(); if player.lib_handle.is_some() { player.stop_playing(); dlclose("libffmpeg.so", player.lib_handle); player.lib_handle = None; } Update::DoNothing } ``` -------------------------------- ### Stateful Component Example Data Structure Source: https://github.com/fschutt/azul/blob/master/doc/guide/lifecycle.md Example of how to structure application state to hold persistent data for components, like a video URL, avoiding direct storage of component-specific handles. ```rust struct AppState { video_url: String, decoder: Option, } ``` -------------------------------- ### Azul Widget Library Example Source: https://context7.com/fschutt/azul/llms.txt Demonstrates the usage of various built-in Azul widgets including CheckBox, ProgressBar, Button, TextInput, NumberInput, and ColorInput. Callbacks are set using `set_on_*` methods with `RefAny` for state management. Requires `azul::prelude::*` and `azul::widgets::*` imports. ```Rust use azul::prelude::*; use azul::widgets::*; #[derive(Default, Clone)] struct FormState { enabled: bool, progress: f32, text: String, number: f64, } extern "C" fn on_toggle(mut data: RefAny, _: CallbackInfo) -> Update { if let Some(mut s) = data.downcast_mut::() { s.enabled = !s.enabled; return Update::RefreshDom; } Update::DoNothing } extern "C" fn on_progress_up(mut data: RefAny, _: CallbackInfo) -> Update { if let Some(mut s) = data.downcast_mut::() { s.progress = (s.progress + 10.0).min(100.0); return Update::RefreshDom; } Update::DoNothing } extern "C" fn layout(mut data: RefAny, _: LayoutCallbackInfo) -> Dom { let state = match data.downcast_ref::() { Some(s) => s.clone(), None => return Dom::create_body(), }; // CheckBox widget let mut checkbox = CheckBox::create(state.enabled); checkbox.set_on_toggle(data.clone(), on_toggle); // ProgressBar widget let progress_bar = ProgressBar::create(state.progress); // Button to advance progress let mut btn = Button::create("Advance +10%"); btn.set_on_click(data.clone(), on_progress_up); // TextInput with placeholder let text_input = TextInput::create() .with_placeholder("Enter text..."); // NumberInput let number_input = NumberInput::create(state.number); // ColorInput let color_input = ColorInput::create(ColorU::from_str("#4a90e2")); Dom::create_body() .with_inline_style("display: flex; flex-direction: column; gap: 12px; padding: 20px;") .with_child( Dom::create_div() .with_inline_style("display: flex; align-items: center; gap: 8px;") .with_child(checkbox.dom()) .with_child(Dom::create_text("Enable feature")) ) .with_child(progress_bar.dom().with_inline_style("width: 200px;")) .with_child(btn.dom()) .with_child(text_input.dom()) .with_child(number_input.dom()) .with_child(color_input.dom()) } fn main() { let state = FormState { progress: 30.0, ..Default::default() }; let app = App::create(RefAny::new(state), AppConfig::create()); app.run(WindowCreateOptions::create(layout)); } ``` -------------------------------- ### Scrollbar CSS Configuration Examples Source: https://github.com/fschutt/azul/blob/master/scripts/SCROLLBAR_BUGS_S10.md Provides example CSS properties for configuring scrollbar behavior, specifically controlling the visibility of scroll buttons and the corner rectangle, and setting the button size. These allow per-node overrides. ```css .__azul_scrollbar { -azul-scrollbar-show-buttons: false; -azul-scrollbar-button-size: 0px; -azul-scrollbar-show-corner: false; } ``` -------------------------------- ### Starting Debug HTTP Server Source: https://github.com/fschutt/azul/blob/master/scripts/E2E_DEBUGGER_PLAN.md Set the AZUL_DEBUG environment variable to a port number to start the HTTP debug server. The server serves the debugger.html file and exposes API endpoints for interacting with the application's state. ```bash AZUL_DEBUG=8765 ```