### Building and Running the Basic GTK4 Example Source: https://github.com/jwijenbergh/puregotk/blob/main/README.md Instructions for building and running the 'Hello, World!' GTK4 application using puregotk. It also mentions the option to build without Cgo. ```bash go run main.go ``` ```bash CGO_ENABLED=0 go build ``` -------------------------------- ### Build and install application with Meson Source: https://github.com/jwijenbergh/puregotk/blob/main/examples/myapp-gnome-meson/README.md Use these commands to configure, compile, and install the application using the Meson build system. ```shell meson setup _build --prefix=/usr --wipe && meson compile -C _build && sudo meson install -C _build myapp-gnome-meson ``` -------------------------------- ### Build and Install Library with Meson Source: https://github.com/jwijenbergh/puregotk/blob/main/examples/mylib-gtk-meson/README.md Commands to clean existing installations and perform a fresh build and install using Meson. ```shell sudo ninja -C _build uninstall || true meson setup _build --prefix=/usr --wipe && meson compile -C _build && sudo meson install -C _build ``` -------------------------------- ### Execute GJS Example Application Source: https://github.com/jwijenbergh/puregotk/blob/main/examples/mylib-gtk-meson/README.md Command to launch the JavaScript example that utilizes the custom Go-based widget. ```shell ./example.js ``` -------------------------------- ### Basic GTK4 Hello World Application in Go Source: https://github.com/jwijenbergh/puregotk/blob/main/README.md This example demonstrates how to create a simple GTK4 application window with a label using puregotk. It shows application initialization, signal connection, and basic widget management. Ensure to use `defer app.Unref()` for cleanup as the library does not use finalizers. ```go package main import ( "os" "github.com/jwijenbergh/puregotk/v4/gio" "github.com/jwijenbergh/puregotk/v4/gtk" ) func main() { app := gtk.NewApplication("com.github.jwijenbergh.puregotk.gtk4.hello", gio.GApplicationFlagsNoneValue) // cleanup, no finalizers are used in this library defer app.Unref() // functions with callback arguments take function pointers // this is for internal re-use of callbacks actcb := func(_ gio.Application) { activa te(app) } app.ConnectActivate(&actcb) if code := app.Run(len(os.Args), os.Args); code > 0 { os.Exit(code) } } func activate(app *gtk.Application) { window := gtk.NewApplicationWindow(app) window.SetTitle("purego") label := gtk.NewLabel("Hello, World!") window.SetChild(&label.Widget) // cleanup, no finalizers are used in this library label.Unref() window.SetDefaultSize(500, 500) window.Present() } ``` -------------------------------- ### Build and Run with Flatpak Source: https://github.com/jwijenbergh/puregotk/blob/main/examples/mylib-gtk-meson/README.md Commands to build the library and example application using Flatpak and execute the resulting package. ```shell flatpak-builder --force-clean --force-clean --user --repo=repo --install builddir io.github.puregotk.MyLibGtkMesonExample.json flatpak run io.github.puregotk.MyLibGtkMesonExample ``` -------------------------------- ### Create GTK Application Windows Source: https://context7.com/jwijenbergh/puregotk/llms.txt Shows how to initialize an ApplicationWindow, manage its lifecycle, and add custom UI elements like HeaderBars. ```go package main import ( "github.com/jwijenbergh/puregotk/v4/gtk" ) func createWindows(app *gtk.Application) { // Application window with proper lifecycle management mainWindow := gtk.NewApplicationWindow(app) mainWindow.SetTitle("Main Window") mainWindow.SetDefaultSize(800, 600) // Set window as resizable or fixed size mainWindow.SetResizable(true) // Connect to close request for cleanup closeHandler := func(_ gtk.Window) bool { fmt.Println("Window closing...") return false // Return false to allow closing, true to prevent } mainWindow.ConnectCloseRequest(&closeHandler) // Add custom titlebar headerBar := gtk.NewHeaderBar() mainWindow.SetTitlebar(&headerBar.Widget) // Add content content := gtk.NewLabel("Window Content") mainWindow.SetChild(&content.Widget) // Show the window mainWindow.Present() // Maximize or fullscreen // mainWindow.Maximize() // mainWindow.Fullscreen() } ``` -------------------------------- ### Working with GTK Labels Source: https://context7.com/jwijenbergh/puregotk/llms.txt Demonstrates creating and configuring labels with features like Pango markup, selection, ellipsization, wrapping, and mnemonics. ```go package main import ( "github.com/jwijenbergh/puregotk/v4/gtk" ) func createLabels(window *gtk.ApplicationWindow) { box := gtk.NewBox(gtk.OrientationVerticalValue, 10) // Simple label simpleLabel := gtk.NewLabel("Hello, World!") box.Append(&simpleLabel.Widget) // Label with Pango markup for styled text styledLabel := gtk.NewLabel("") styledLabel.SetMarkup("Bold and italic text") box.Append(&styledLabel.Widget) // Selectable label that users can copy from selectableLabel := gtk.NewLabel("You can select this text") selectableLabel.SetSelectable(true) box.Append(&selectableLabel.Widget) // Label with ellipsization for long text longLabel := gtk.NewLabel("This is a very long text that will be ellipsized") longLabel.SetEllipsize(1) // PANGO_ELLIPSIZE_END longLabel.SetMaxWidthChars(20) box.Append(&longLabel.Widget) // Label with text wrapping wrappedLabel := gtk.NewLabel("This label will wrap to multiple lines when the text is too long") wrappedLabel.SetWrap(true) box.Append(&wrappedLabel.Widget) // Label with mnemonic (Alt+H activates associated widget) mnemonicLabel := gtk.NewLabelWithMnemonic("_Hello") box.Append(&mnemonicLabel.Widget) window.SetChild(&box.Widget) } ``` -------------------------------- ### Create a GTK4 Application Source: https://context7.com/jwijenbergh/puregotk/llms.txt Initializes a GTK application instance and connects to the Activate signal to build the UI. ```go package main import ( "os" "github.com/jwijenbergh/puregotk/v4/gio" "github.com/jwijenbergh/puregotk/v4/gtk" ) func main() { app := gtk.NewApplication("com.example.myapp", gio.GApplicationFlagsNoneValue) // Always clean up - no finalizers are used in this library defer app.Unref() // Connect the activate signal using a function pointer activateCb := func(_ gio.Application) { window := gtk.NewApplicationWindow(app) window.SetTitle("My GTK4 App") window.SetDefaultSize(400, 300) window.Present() } app.ConnectActivate(&activateCb) // Run the application and exit with its return code if code := app.Run(len(os.Args), os.Args); code > 0 { os.Exit(code) } } ``` -------------------------------- ### Create GTK Buttons Source: https://context7.com/jwijenbergh/puregotk/llms.txt Demonstrates creating buttons with labels, icons, mnemonics, custom children, and flat styling. ```go package main import ( "fmt" "github.com/jwijenbergh/puregotk/v4/gtk" ) func createButtons(window *gtk.ApplicationWindow) { box := gtk.NewBox(gtk.OrientationVerticalValue, 10) // Button with label textButton := gtk.NewButtonWithLabel("Click Me") clickHandler := func(_ gtk.Button) { fmt.Println("Button was clicked!") } textButton.ConnectClicked(&clickHandler) box.Append(&textButton.Widget) // Button with icon iconButton := gtk.NewButtonFromIconName("document-open-symbolic") iconClickHandler := func(_ gtk.Button) { fmt.Println("Open button clicked!") } iconButton.ConnectClicked(&iconClickHandler) box.Append(&iconButton.Widget) // Button with mnemonic (Alt+S activates) mnemonicButton := gtk.NewButtonWithMnemonic("_Save") box.Append(&mnemonicButton.Widget) // Flat button (no visible border) flatButton := gtk.NewButtonWithLabel("Flat Button") flatButton.SetHasFrame(false) box.Append(&flatButton.Widget) // Button with custom child widget customButton := gtk.NewButton() buttonBox := gtk.NewBox(gtk.OrientationHorizontalValue, 5) icon := gtk.NewImageFromIconName("starred-symbolic") label := gtk.NewLabel("Favorite") buttonBox.Append(&icon.Widget) buttonBox.Append(&label.Widget) customButton.SetChild(&buttonBox.Widget) box.Append(&customButton.Widget) window.SetChild(&box.Widget) } ``` -------------------------------- ### Run application with Go build system Source: https://github.com/jwijenbergh/puregotk/blob/main/examples/myapp-gnome-gomod/README.md Use go generate to prepare resources and go run with ldflags to point gettext to local translation files. ```shell go generate ./... go run -ldflags="-X 'main.LocaleDir=${PWD}/po'" ./src/ ``` -------------------------------- ### Create an Adwaita Application Source: https://context7.com/jwijenbergh/puregotk/llms.txt Initializes an Adwaita-enhanced application with modern GNOME styling and adaptive widgets. ```go package main import ( "os" "github.com/jwijenbergh/puregotk/v4/adw" "github.com/jwijenbergh/puregotk/v4/gio" "github.com/jwijenbergh/puregotk/v4/gtk" ) func main() { app := adw.NewApplication("com.example.adwapp", gio.GApplicationDefaultFlagsValue) defer app.Unref() activateCb := func(_ gio.Application) { // Use AdwApplicationWindow for modern GNOME styling window := adw.NewApplicationWindow(&app.Application) window.SetTitle("Adwaita App") window.SetDefaultSize(600, 400) // AdwHeaderBar provides GNOME-style title bar headerBar := adw.NewHeaderBar() // Use ToolbarView for proper layout toolbarView := adw.NewToolbarView() toolbarView.AddTopBar(&headerBar.Widget) content := gtk.NewLabel("Hello Adwaita!") toolbarView.SetContent(&content.Widget) window.SetContent(&toolbarView.Widget) window.Present() } app.ConnectActivate(&activateCb) os.Exit(int(app.Run(int32(len(os.Args)), os.Args))) } ``` -------------------------------- ### Create GTK Layout Containers Source: https://context7.com/jwijenbergh/puregotk/llms.txt Demonstrates creating and arranging widgets using vertical and horizontal boxes, a grid, and a stack with a stack switcher. Requires GTK widgets and layout containers. ```go package main import ( "github.com/jwijenbergh/puregotk/v4/gtk" ) func createLayouts(window *gtk.ApplicationWindow) { // Vertical box layout vbox := gtk.NewBox(gtk.OrientationVerticalValue, 10) // Horizontal box inside vertical box hbox := gtk.NewBox(gtk.OrientationHorizontalValue, 5) hbox.Append(>k.NewLabel("Left").Widget) hbox.Append(>k.NewLabel("Center").Widget) hbox.Append(>k.NewLabel("Right").Widget) vbox.Append(&hbox.Widget) // Grid layout for form-like arrangements grid := gtk.NewGrid() grid.SetRowSpacing(5) grid.SetColumnSpacing(10) // Attach widgets at specific positions (col, row, width, height) nameLabel := gtk.NewLabel("Name:") grid.Attach(&nameLabel.Widget, 0, 0, 1, 1) nameEntry := gtk.NewEntry() grid.Attach(&nameEntry.Widget, 1, 0, 1, 1) emailLabel := gtk.NewLabel("Email:") grid.Attach(&emailLabel.Widget, 0, 1, 1, 1) emailEntry := gtk.NewEntry() grid.Attach(&emailEntry.Widget, 1, 1, 1, 1) vbox.Append(&grid.Widget) // Stack for switching between views stack := gtk.NewStack() stack.AddTitled(>k.NewLabel("Page 1 Content").Widget, "page1", "Page 1") stack.AddTitled(>k.NewLabel("Page 2 Content").Widget, "page2", "Page 2") // Stack switcher for navigation stackSwitcher := gtk.NewStackSwitcher() stackSwitcher.SetStack(stack) vbox.Append(&stackSwitcher.Widget) vbox.Append(&stack.Widget) window.SetChild(&vbox.Widget) } ``` -------------------------------- ### Run the application Source: https://context7.com/jwijenbergh/puregotk/llms.txt Execute the compiled binary directly from the terminal. ```bash ./myapp ``` -------------------------------- ### Configure Library Paths and Build Source: https://context7.com/jwijenbergh/puregotk/llms.txt Set environment variables to specify library locations or perform static builds without Cgo. ```bash # Set path to a specific library file export PUREGOTK_GTK_PATH=/custom/path/libgtk-4.so.1 # Set root folder for all libraries export PUREGOTK_LIB_FOLDER=/custom/lib/ # Build without Cgo (fully static Go compilation) CGO_ENABLED=0 go build -o myapp main.go ``` -------------------------------- ### Build and run with Flatpak Source: https://github.com/jwijenbergh/puregotk/blob/main/examples/myapp-gnome-gomod/README.md Use flatpak-builder to compile the application and its dependencies, then execute the resulting package. ```shell flatpak-builder --force-clean --force-clean --user --repo=repo --install builddir io.github.puregotk.MyAppGnomeGomod.json flatpak run io.github.puregotk.MyAppGnomeMeson ``` -------------------------------- ### Configure library loading paths Source: https://context7.com/jwijenbergh/puregotk/llms.txt Library paths are automatically registered in init functions and searched based on environment variables and system defaults. ```go // The library loading happens automatically in init() functions // Each package (gtk, adw, gio, etc.) registers its library paths: // // core.SetPackageName("GTK", "gtk4") // core.SetSharedLibraries("GTK", []string{"libgtk-4.so.1"}) // // Paths are searched in order: // 1. PUREGOTK_GTK_PATH environment variable (full path) // 2. PUREGOTK_LIB_FOLDER environment variable (directory) // 3. Common system paths: /app/lib/, /usr/lib/x86_64-linux-gnu/, /usr/lib64/, /usr/lib/ // 4. pkg-config fallback (slower startup) ``` -------------------------------- ### Build and run with Flatpak Source: https://github.com/jwijenbergh/puregotk/blob/main/examples/myapp-gnome-meson/README.md Use Flatpak to build the application and its dependencies in an isolated environment. ```shell flatpak-builder --force-clean --force-clean --user --repo=repo --install builddir io.github.puregotk.MyAppGnomeMeson.json flatpak run io.github.puregotk.MyAppGnomeMeson ``` -------------------------------- ### Connect GTK Signals and Callbacks Source: https://context7.com/jwijenbergh/puregotk/llms.txt Illustrates connecting widget signals to Go function pointers for handling user input events. ```go package main import ( "fmt" "github.com/jwijenbergh/puregotk/v4/gio" "github.com/jwijenbergh/puregotk/v4/gtk" ) func demonstrateSignals(app *gtk.Application) { window := gtk.NewApplicationWindow(app) button := gtk.NewButtonWithLabel("Click Counter") clickCount := 0 // Connect clicked signal - note the function pointer syntax clickHandler := func(_ gtk.Button) { clickCount++ button.SetLabel(fmt.Sprintf("Clicked %d times", clickCount)) } button.ConnectClicked(&clickHandler) entry := gtk.NewEntry() // Connect text changed signal changedHandler := func(_ gtk.Editable) { text := entry.GetText() fmt.Printf("Entry text: %s\n", text) } entry.ConnectChanged(&changedHandler) // Connect activate signal (Enter key pressed) activateHandler := func(_ gtk.Entry) { fmt.Println("Entry activated!") } entry.ConnectActivate(&activateHandler) box := gtk.NewBox(gtk.OrientationVerticalValue, 10) box.Append(&button.Widget) box.Append(&entry.Widget) window.SetChild(&box.Widget) window.Present() } ``` -------------------------------- ### Generate Go bindings Source: https://github.com/jwijenbergh/puregotk/blob/main/examples/mylib-gtk-meson-go/README.md Execute the generation script to create Go bindings from the specified GIR file. ```shell ./gen.sh ``` -------------------------------- ### Create Adwaita Toast Notifications Source: https://context7.com/jwijenbergh/puregotk/llms.txt Shows how to create and display different types of Adwaita toast notifications using `adw.NewToast`. Includes simple toasts, timed toasts, and toasts with action buttons. Requires `adw.ToastOverlay` to display. ```go package main import ( "github.com/jwijenbergh/puregotk/v4/adw" "github.com/jwijenbergh/puregotk/v4/gtk" ) func createToastDemo(window *adw.ApplicationWindow) { // ToastOverlay wraps content and displays toasts toastOverlay := adw.NewToastOverlay() box := gtk.NewBox(gtk.OrientationVerticalValue, 10) // Simple toast simpleButton := gtk.NewButtonWithLabel("Show Simple Toast") simpleHandler := func(_ gtk.Button) { toast := adw.NewToast("This is a simple toast message") toastOverlay.AddToast(toast) } simpleButton.ConnectClicked(&simpleHandler) box.Append(&simpleButton.Widget) // Toast with custom timeout timedButton := gtk.NewButtonWithLabel("Show Timed Toast") timedHandler := func(_ gtk.Button) { toast := adw.NewToast("This toast lasts 5 seconds") toast.SetTimeout(5) toastOverlay.AddToast(toast) } timedButton.ConnectClicked(&timedHandler) box.Append(&timedButton.Widget) // Toast with action button actionButton := gtk.NewButtonWithLabel("Show Toast with Action") actionHandler := func(_ gtk.Button) { toast := adw.NewToast("Item deleted") toast.SetButtonLabel("Undo") toast.SetActionName("app.undo") toast.SetPriority(adw.ToastPriorityHighValue) toastOverlay.AddToast(toast) } actionButton.ConnectClicked(&actionHandler) box.Append(&actionButton.Widget) toastOverlay.SetChild(&box.Widget) window.SetContent(&toastOverlay.Widget) } ``` -------------------------------- ### Load GIO Resources Source: https://context7.com/jwijenbergh/puregotk/llms.txt Register compiled resource data globally to allow UI files to reference embedded assets. ```go package main import ( "github.com/jwijenbergh/puregotk/v4/gio" "github.com/jwijenbergh/puregotk/v4/glib" ) // ResourceContents would be populated by embedding a .gresource file // using go:embed or generated at compile time var ResourceContents []byte func initResources() error { // Create resource from embedded data resource, err := gio.NewResourceFromData( glib.NewBytes(ResourceContents, uint(len(ResourceContents))), ) if err != nil { return err } // Register globally so UI files can reference resources gio.ResourcesRegister(resource) // List available resources children, err := gio.ResourcesEnumerateChildren("/com/example/app/", 0) if err == nil { for _, child := range children { fmt.Printf("Resource: %s\n", child) } } return nil } ``` -------------------------------- ### Update gettext i18n resources Source: https://github.com/jwijenbergh/puregotk/blob/main/examples/myapp-gnome-meson/README.md Commands to regenerate POT files and update PO files for internationalization. ```shell meson compile -C _build myapp-gnome-meson-pot meson compile -C _build myapp-gnome-meson-update-po ``` -------------------------------- ### Update gettext i18n Resources Source: https://github.com/jwijenbergh/puregotk/blob/main/examples/mylib-gtk-meson/README.md Commands to regenerate POT files and update PO files for internationalization. ```shell meson compile -C _build mylib-gtk-meson-pot meson compile -C _build mylib-gtk-meson-update-po ``` -------------------------------- ### Manage memory and cleanup in puregotk Source: https://context7.com/jwijenbergh/puregotk/llms.txt Explicitly call Unref on objects to prevent memory leaks, as finalizers are not used. Use SetDataFull to attach cleanup callbacks to GObjects. ```go package main import ( "github.com/jwijenbergh/puregotk/v4/gtk" "github.com/jwijenbergh/puregotk/v4/glib" ) func memoryManagement() { app := gtk.NewApplication("com.example.app", 0) // Always defer Unref for top-level objects defer app.Unref() activateCb := func(_ gio.Application) { window := gtk.NewApplicationWindow(app) // Widgets added to containers are managed by the container label := gtk.NewLabel("Hello") window.SetChild(&label.Widget) // Call Unref after adding to container since container takes ownership label.Unref() // For objects with associated Go data, use SetDataFull cleanup := func(data uintptr) { // Called when the GObject is finalized fmt.Println("Cleanup callback executed") } window.SetDataFull("my-data", 0, &cleanup) window.Present() } app.ConnectActivate(&activateCb) app.Run(len(os.Args), os.Args) } ``` -------------------------------- ### Subclass GObject in Go Source: https://context7.com/jwijenbergh/puregotk/llms.txt Register a custom GObject type by overriding virtual methods and managing Go-side instance data. Requires careful memory management using runtime.Pinner to prevent garbage collection of the Go instance. ```go package main import ( "runtime" "unsafe" "github.com/jwijenbergh/puregotk/v4/adw" "github.com/jwijenbergh/puregotk/v4/glib" "github.com/jwijenbergh/puregotk/v4/gobject" "github.com/jwijenbergh/puregotk/v4/gtk" ) var gTypeCustomWindow gobject.Type const dataKeyGoInstance = "go-instance" type CustomWindow struct { adw.ApplicationWindow counter int label *gtk.Label } func NewCustomWindow(app *gtk.Application) CustomWindow { obj := gobject.NewObject(gTypeCustomWindow, "application", app) var v CustomWindow obj.Cast(&v) return v } func init() { // Class initialization - called once when type is first used classInit := func(tc *gobject.TypeClass, u uintptr) { objClass := (*gobject.ObjectClass)(unsafe.Pointer(tc)) // Override the constructed virtual method objClass.OverrideConstructed(func(o *gobject.Object) { // Chain up to parent parentObjClass := (*gobject.ObjectClass)(unsafe.Pointer(tc.PeekParent())) parentObjClass.GetConstructed()(o) var parent adw.ApplicationWindow o.Cast(&parent) // Create Go-side instance w := &CustomWindow{ ApplicationWindow: parent, counter: 0, } // Pin to prevent GC var pinner runtime.Pinner pinner.Pin(w) // Clean up when GObject is finalized cleanup := func(data uintptr) { pinner.Unpin() } o.SetDataFull(dataKeyGoInstance, uintptr(unsafe.Pointer(w)), &cleanup) // Build UI w.label = gtk.NewLabel("Counter: 0") button := gtk.NewButtonWithLabel("Increment") clickHandler := func(_ gtk.Button) { w.counter++ w.label.SetLabel(fmt.Sprintf("Counter: %d", w.counter)) } button.ConnectClicked(&clickHandler) box := gtk.NewBox(gtk.OrientationVerticalValue, 10) box.Append(&w.label.Widget) box.Append(&button.Widget) parent.SetContent(&box.Widget) }) } instanceInit := func(ti *gobject.TypeInstance, tc *gobject.TypeClass) {} // Query parent type info var parentQuery gobject.TypeQuery gobject.NewTypeQuery(adw.ApplicationWindowGLibType(), &parentQuery) // Register the new type gTypeCustomWindow = gobject.TypeRegisterStaticSimple( parentQuery.Type, "CustomWindow", parentQuery.ClassSize, &classInit, parentQuery.InstanceSize, &instanceInit, 0, ) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.