### Install Fabric Dependencies and Source Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/contributing/development-environment.mdx Installs project dependencies listed in 'requirements.txt' and then installs the current Fabric source code in editable mode. This prepares the environment for development and ensures all necessary packages are available. ```bash pip install -r requirements.txt pip install -e . ``` -------------------------------- ### Install Fabric Globally Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/getting-started/installation-guide.mdx An alternative, though not recommended, method to install Fabric system-wide using pip directly from its GitHub repository. This approach can lead to dependency issues and is generally less isolated than virtual environment installations. ```bash pip install git+https://github.com/Fabric-Development/fabric.git ``` -------------------------------- ### Install Fabric in a Python Virtual Environment Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/getting-started/installation-guide.mdx The recommended method for installing Fabric, involving creating a dedicated project folder, setting up a Python virtual environment, activating it, and then installing Fabric directly from its GitHub repository using pip. This approach helps manage dependencies and avoids conflicts with system-wide packages. ```bash mkdir ``` ```bash cd ``` ```bash python -m venv venv ``` ```bash source venv/bin/activate ``` ```bash pip install git+https://github.com/Fabric-Development/fabric.git ``` -------------------------------- ### Install Python 3.11+ on Linux Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/getting-started/installation-guide.mdx Commands to install Python version 3.11 or later, which is a prerequisite for Fabric, on common Linux distributions. Users should check their distribution's specific package manager for the most recent compatible version. ```bash sudo pacman -S python ``` ```bash sudo zypper install python311 ``` ```bash sudo dnf in python ``` -------------------------------- ### Python Comment Style Guidelines Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/contributing/code-style-guide.mdx Illustrates the recommended style for comments in Python code, adhering to PEP 8 guidelines. It shows examples of correct single-line comments and explicitly warns against incorrect or unconventional comment styles. ```python # Like this. ##not like this..## #nor like this.. #--/ nor whatever else. /--# ``` -------------------------------- ### Install Fabric Dependencies on Linux Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/getting-started/installation-guide.mdx Commands to install all necessary system and Python dependencies for Fabric, including GTK3, Cairo, GObject introspection libraries, and Python packages like python-pip, python-gobject, python-cairo, and python-loguru. Specific commands are provided for Arch Linux, OpenSUSE, and Fedora, as package names may vary. ```bash sudo pacman -S gtk3 cairo gtk-layer-shell libgirepository gobject-introspection gobject-introspection-runtime python python-pip python-gobject python-cairo python-loguru pkgconf ``` ```bash sudo zypper install gtk3-devel cairo-devel gtk-layer-shell-devel libgirepository-1_0-1 libgirepository-2_0-0 gobject-introspection-devel python311 python311-pip python311-gobject python311-gobject-cairo python311-pycairo python311-loguru pkgconf ``` ```bash sudo dnf install gtk3-devel cairo-devel gtk-layer-shell-devel glib2 gobject-introspection-devel python3-devel python-pip python3-gobject python3-cairo python3-loguru pkgconf ``` -------------------------------- ### Good CSS Naming Convention Examples Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/styling.mdx This snippet provides examples of CSS selectors that adhere to the recommended `kebab-case` naming convention. Following these rules ensures consistency, readability, and maintainability across your Fabric application's stylesheets. ```css #my-widget { /* ... */ } #my-widget .class-name { /* ... */ } ``` -------------------------------- ### CHANGELOG.md Entry Format Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/contributing/code-style-guide.mdx Specifies the required format for entries in the `CHANGELOG.md` file. Each entry must include a change number, pull request number, and a concise commit message, with examples illustrating different types of changes like features, fixes, and refactors. ```APIDOC -- Format -- . <#Pull-Request-Number> -- Examples -- 1. <#Pull-Request-Number> feat: something awesome! 2. <#Pull-Request-Number> feat: new method to do magic! 3. <#Pull-Request-Number> fix: fabricated, this fixes/closes ! 4. refactor: i dunno how to fabricate XD ``` -------------------------------- ### Define a Basic Fabric Service Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/services.mdx This snippet demonstrates the minimal definition of a Fabric Service by subclassing `fabric.core.service.Service`. It serves as a starting point for creating custom services. ```python from fabric.core.service import Service class MyService(Service):... ``` -------------------------------- ### Using Astro Components for Layout and Content Display Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/index.mdx These examples illustrate the declarative usage of Astro components to structure the page content. Components like `HeroBackground`, `CardGrid`, `FeatureCard`, `ShowcaseCard`, `Badge`, `Icon`, and `LinkButton` are used to create visually appealing sections, display features, showcase projects, and provide interactive links. This approach promotes modularity and reusability in web development. ```Astro

What's That?

Fabric is a Desktop Widgets System which can be customized in Python, Fabric offers a ton of features to make the boring process of writing widget way more easier and fun!

Features

Visual Tour

A Collection of Desktop rices that muscle-show what are you able to do using Fabric!
---

Show Support!

You can show your support and help in the development via Ko-fi donations. Github stars are also appreciated!
Our Ko-fi Star Fabric!
---
**[Fabric Development](https://github.com/Fabric-Development)** © Copyrights are hereby granted for usage under the AGPL agreements ---
Made using [Starlight](https://starlight.astro.build/)
``` -------------------------------- ### Define a Fabric Service with Signals and Properties Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/services.mdx This comprehensive example illustrates how to define a Fabric Service (`NameService`) that incorporates both Signals and Properties. It shows how to declare a `Signal` (`name_changed`) and a `Property` (`name`) with a setter that emits the signal upon value change. It also demonstrates connecting a listener to the signal and triggering the property setter. ```python from fabric.core.service import Service, Signal, Property class NameService(Service): @Signal def name_changed(self, new_name: str) -> None:... @Property(str, flags="read-write") def name(self) -> str: return self._name @name.setter def name(self, value: str): self._name = value self.name_changed(value) def __init__(self, name: str | None = None): super().__init__() self._name = name or "" name_service = NameService() name_service.connect( "name-changed", lambda new_name: print(f"the name has changed, new name is {new_name}") ) name_service.name = "Homan" ``` -------------------------------- ### Conventional Commits Message Format Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/contributing/code-style-guide.mdx Defines the standard structure for commit messages following the Conventional Commits specification. It includes the required type, optional scope, description, and optional body and footers, along with practical examples for feature additions and bug fixes. ```APIDOC [optional scope]: [optional body] [optional footer(s)] Examples: feat: Add `balloons` argument to `Universe.celebrating_koalas` fix: Check for fradulent koalas before allocating balloons ``` -------------------------------- ### Activate Python Virtual Environment Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/contributing/development-environment.mdx Activates the previously created Python virtual environment. Once activated, subsequent Python commands will use the packages installed within this isolated environment. ```bash source venv/bin/activate ``` -------------------------------- ### Demonstrate Nested Box Layouts with Labels in Fabric Python Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/first-widget.mdx This Python example illustrates the use of `Box` widgets in Fabric to create structured layouts. It defines two `Box` instances with different orientations (vertical and horizontal) and spacing, nesting one inside the other. Labels are added to demonstrate how elements are arranged within these containers, providing a clear understanding of Fabric's layout capabilities. ```python import fabric # importing the base pacakge from fabric import Application # prepare the application class which manages multi-config setups from fabric.widgets.box import Box # gets the Box class from fabric.widgets.label import Label # gets the Label class from fabric.widgets.window import Window # grabs the Window class from Fabric if __name__ == "__main__": box_1 = Box( orientation="v", # vertical children=Label(label="this is the first box") ) box_2 = Box( spacing=28, # adds some spacing between the children orientation="h", # horizontal children=[ Label(label="this is the first element in the second box"), Label(label="btw, this box elements will get added horizontally") ] ) box_1.add(box_2) # append box_2 inside box_1 along with the label already in there window = Window(child=box_1) # there's no need showing this window using `show_all()`; it'll show them itself because the children are already passed app = Application("default", window) # define a new config named "default" which holds `window` app.run() # run the event loop (run the config) ``` -------------------------------- ### Configure Fabricator Service using Builder Callback Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/services.mdx This example illustrates an alternative method for configuring a `Fabricator` service using a callback function. The callback receives the `Service` instance and the builder object, allowing for flexible configuration of signals and values within an encapsulated block. ```python fabricator = Fabricator( poll_from=lambda: "hello there!", interval=1000, ).build( lambda self, builder: builder\ .connect("changed", lambda *_: print("changed"))\ .connect("notify::value", lambda *_: print("value notified"))\ .set_value("initial value") ) ``` -------------------------------- ### Fabric Service Signal Emission and Connection Example Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/services.mdx This example demonstrates the full lifecycle of a Fabric Service signal. It shows how to define a signal (`name_changed`), emit it explicitly within a method (`set_name`), and connect a lambda function as a listener to react to the signal emission. It also illustrates alternative ways to emit and connect to signals. ```python class NameService(Service): @Signal def name_changed(self, new_name: str) -> None: ... def __init__(self, **kwargs): super().__init__(**kwargs) self.name = "" def get_name(self) -> str: return self.name def set_name(self, new_name: str) -> None: self.name = new_name # Emit the "name-changed" signal self.name_changed(new_name) # Alternative ways to emit a signal: # self.name_changed.emit(new_name) # self.emit("name-changed", new_name) name_service = NameService() # Connect a listener to the "name-changed" signal name_service.connect( "name-changed", lambda new_name: print(f"The name has changed, new name is {new_name}") ) # Alternative way to connect to the signal # name_service.name_changed.connect(...) ``` -------------------------------- ### Initialize Fabricator Service with Direct Builder Chaining Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/services.mdx This snippet demonstrates how to initialize a `Fabricator` object using the builder pattern's direct chaining method. It shows connecting signals ('changed', 'notify::value') and setting an initial value, then unwrapping the builder to get the actual `Fabricator` instance. ```python fabricator = Fabricator( poll_from=lambda: "hello there!", interval=1000, ).build()\ .connect("changed", lambda *_: print("changed"))\ .connect("notify::value", lambda *_: print("value notified"))\ .set_value("initial value")\ .unwrap() # Return the actual Fabricator, not the Builder object ``` -------------------------------- ### Python Fabricator Usage Examples Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/fabricators.mdx This snippet demonstrates various ways to initialize and use `Fabricator` instances in Python. It covers polling from Python lambda functions for internal logic (like a counter), and from external shell commands for data like weather, current date, media player status, and directory size. It showcases the `interval`, `default_value`, `poll_from`, `stream`, and `on_changed` parameters for different data acquisition and handling scenarios. ```python from fabric import Application, Fabricator # lambda symbols # f: is the fabricator itself, v: is the new value counter_fabricator = Fabricator( interval=50, # ms default_value=0, poll_from=lambda f: f.get_value() + 1, on_changed=lambda f, v: (( f.stop(), print("Counter Stopped") ) if v == 43 else print(f"Counter Value: {v}") ), ) # example output: # Counter Value: 1 # Counter Value: 2 # Counter Value: 3 # ... # Counter Value: 42 # Counter Stopped weather_fabricator = Fabricator( interval=1000 * 60, # 1min poll_from="curl https://wttr.in/?format=Weather+in+%l:+%t+(Feels+Like+%f),+%C+%c", on_changed=lambda f, v: print(v.strip()), ) # example output: # Weather in Homenland:, +15°C (Feels Like +15°C), Clear ☀️ # ... date_fabricator = Fabricator( interval=500, poll_from="date", on_changed=lambda f, v: print(f"Current Date: {v.strip()}"), ) # example output: # current date and time: Fri Nov 29 03:45:32 AM EET 2024 # current date and time: Fri Nov 29 03:45:32 AM EET 2024 # ... # NOTE: this is just an example, the use of the Playerctl Python module would be a better idea player_fabricator = Fabricator( stream=True, poll_from="playerctl --follow metadata --format '[{{status}}] {{title}} - {{artist}}'", on_changed=lambda f, v: print(v.strip()), ) # example output: # [Playing] Something - HomenArtsHouse # [Paused] Something - HomenArtsHouse # [Playing] The Stars - HomenArtsHouse # ... # NOTE: this is just an example, the use of something like os would be better documents_fabricator = Fabricator( interval=1000, # 1 second poll_from="du -sh /home/homan/Documents/", # NOTE: edit this on_changed=lambda f, v: print(f"Size of Documents: {v.split()[0]}"), ) # example output: # Size of Documents: 1G # Size of Documents: 1.1G # ... app = Application() app.run() ``` -------------------------------- ### Create Python Virtual Environment Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/contributing/development-environment.mdx Creates a new isolated Python virtual environment named 'venv' in the current directory. This helps manage project dependencies without interfering with the system's global Python installation. ```bash python -m venv venv ``` -------------------------------- ### Bad CSS Naming Convention Examples Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/styling.mdx This snippet illustrates examples of CSS selectors that violate the recommended `kebab-case` naming convention. It demonstrates common mistakes such as using underscores, mixed cases, or double hyphens, which should be avoided for consistent and maintainable stylesheets. ```css #My_Widget { /* ... */ } #My-Widget { /* ... */ } #myWidget { /* ... */ } #my-widget .Class--name { /* ... */ } ``` -------------------------------- ### Connecting Signals to Callbacks in Fabric Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/services.mdx This example illustrates multiple ways to connect signals to callback functions within Fabric services. It shows connecting signals directly in the `Fabricator` constructor, using the generic `connect` method, and a service-specific `changed.connect` method. ```python def callback(): print("I've been called") # using a Fabricator as the service fabricator = Fabricator( poll_from=lambda: "hello there!", interval=1000, # signal connections on_changed=callback, # Connect the "changed" signal to the callback notify_value=lambda *_: print("value notified") # Connect to "notify::value" for property changes ) # alternative ways to connect signals fabricator.connect("changed", callback) fabricator.changed.connect(callback) # works specifically for Fabric services # fabricator.connect("notify::value", lambda *_: print("value notified")) ``` -------------------------------- ### Fabricating a Custom GTK Widget in Python Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/contributing/hacking-guide.mdx This Python snippet demonstrates how to create a custom GTK widget that integrates with the Fabric framework. It shows the necessary imports for `gi`, `Gtk`, and Fabric's base `Widget` class. The example defines a new class that inherits from both a desired GTK widget (e.g., `Gtk.MyWidget`) and Fabric's `Widget`, illustrating the `__init__` method for proper initialization and custom argument handling. ```python import gi # import the gi repository to get GTK from it later gi.require_version("Gtk", "3.0") # graps the version 3 of GTK since this is what fabric uses from gi.repository import Gtk # now we have GTK (version 3) imported from fabric.widgets.widget import Widget # imports fabric's base widget class MyFabricatedWidget(Gtk.MyWidget, Widget): # creates a new class named "MyFabricatedWidget", this class inherits the desired GTK widget and fabric's base widget def __init__(self, **kwargs): # the initializer function, **kwargs (a dict) means whatever you pass as extra argument will be in that dict # you can set more arguments to this newly created class, this is useful if you want to make this widget able to do more during the initialization phase # you may add more logic here to handle the new arguments (if any) super().__init__(**kwargs) # initializes the new mixed class ``` -------------------------------- ### Connecting to Property Change Notifications (Explicit) Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/services.mdx This example shows how to explicitly connect a callback function to a property's change notification signal. The `connect` method is used with the 'notify::property_name' syntax to listen for updates to the 'status' property. ```python example_service = MyService("Initializing") # Connect to the notify::status signal for the status property example_service.connect("notify::status", lambda *_: print("Status has changed")) example_service.status = "Running" ``` -------------------------------- ### Python Inline If-Statement for Single Object Assignment Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/contributing/code-style-guide.mdx Demonstrates the use of an inline if-statement in Python. This pattern is preferred when the conditional logic only affects the assignment of a single object's value, promoting conciseness. ```python x = "the x object" if unexpected_feature is not True else "the x man" ``` -------------------------------- ### Python Regular If-Statement for Code Blocks Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/contributing/code-style-guide.mdx Explains when to use a regular if-statement in Python: specifically when a block of code needs to be executed based on a condition, rather than just assigning a single value. It also contrasts this with an anti-pattern of using multiple inline if-statements for a block. ```python if unexpected_feature is True: x = "the unknown guy" y = "idk" z = 4002 ... # This is much more concise and clear than x = "the unknown guy" if unexcpected_feature is True else None y = "idk" if unexcpected_feature is True else None z = 4002 if unexcpected_feature is True else None ``` -------------------------------- ### Define a Signal with the Fabric Signal Decorator Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/services.mdx This example demonstrates how to define a signal within a Fabric Service using the `@Signal` decorator. It specifies the signal's name and the type hints for its arguments and return value, adhering to the requirement for fully typed signal handlers. ```python @Signal def signal_name(self, arg1: str, arg2: int, arg3: float) -> None: ... ``` -------------------------------- ### Unset Default GTK Stylesheet Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/styling.mdx To start styling your Fabric widgets from a clean slate, this CSS snippet can be added to your `style.css` file. It uses `all: unset;` to remove all default GTK styles, ensuring that no pre-existing stylesheets interfere with your custom designs. ```css * { all: unset; } ``` -------------------------------- ### Create a Basic 'Hello, World' Window with Fabric Python Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/first-widget.mdx This Python snippet demonstrates how to create a fundamental GUI application using the Fabric library. It initializes a `Window` widget and adds a `Label` widget displaying 'Hello, World' as its child. The code then configures and runs the Fabric application, making the window and its contents visible. ```python import fabric # importing the base package from fabric import Application from fabric.widgets.label import Label # gets the Label class from fabric.widgets.window import Window # grabs the Window class from Fabric window = Window( # creates a new instance of the Window class and assign it to the `window` variable child = Label("Hello, World"), # creates a new Label instance with the content being "Hello, World" and assigns it as a child of the window all_visible=True # to make the window and all of its children appear once the config runs ) app = Application("default", window) # define a new config named "default" which holds `window` app.run() # run the event loop (run the config) ``` -------------------------------- ### Fabric CLI Command Reference Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/getting-started/client-and-cli.mdx Comprehensive documentation for the Fabric command-line interface, detailing its main options and subcommands for interacting with running Fabric instances via DBus. It includes options like --help and subcommands such as 'evaluate', 'execute', and 'list-all', each with a brief description of its purpose. ```APIDOC Usage: python -m fabric [OPTIONS] COMMAND [ARGS] ... Options: --help Show this message and exit. Commands: evaluate evaluate a python code within a running fabric instance and return the result execute executes a python code within the running fabric instance list-all list all currently running fabric instances ``` -------------------------------- ### Run Fabric Application with StatusBar Instance Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/first-widget.mdx This code block illustrates how to instantiate the `StatusBar` class and run the Fabric application. It sets up the main application loop, making the status bar active, though it might not be visible initially if unstyled or empty. ```python if __name__ == "__main__": bar = StatusBar() app = Application("bar", bar) app.run() ``` -------------------------------- ### List All Running Fabric Instances Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/getting-started/client-and-cli.mdx Demonstrates how to use the `fabric list-all` command to display currently running Fabric instances. The output shows the instance name and the path to its configuration file. ```python $ python -m fabric list-all my-bar: /home/homan/.config/fabric/config.py ``` -------------------------------- ### Change Directory to Fabric Repository Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/contributing/development-environment.mdx Navigates into the newly cloned 'fabric' directory. This is a necessary step before performing further operations within the repository. ```bash cd fabric ``` -------------------------------- ### Create Fabric Status Bar for Wayland and X11 Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/first-widget.mdx This Python code demonstrates how to create a basic status bar using the Fabric library, providing separate implementations for Wayland and X11 environments. Both versions initialize a `StatusBar` window with a `DateTime` widget centered within it, adapting to the specific windowing system. ```python import fabric from fabric import Application from fabric.widgets.datetime import DateTime from fabric.widgets.centerbox import CenterBox from fabric.widgets.wayland import WaylandWindow as Window class StatusBar(Window): def __init__(self, **kwargs): super().__init__( layer="top", anchor="left top right", exclusivity="auto", **kwargs ) self.date_time = DateTime() self.children = CenterBox(center_children=self.date_time) if __name__ == "__main__": bar = StatusBar() app = Application("bar-example", bar) app.run() ``` ```python import fabric from fabric import Application from fabric.widgets.datetime import DateTime from fabric.widgets.centerbox import CenterBox from fabric.widgets.x11 import X11Window as Window class StatusBar(Window): def __init__(self, **kwargs): super().__init__( layer="top", geometry="top", type_hint="dock", **kwargs ) self.date_time = DateTime() self.children = CenterBox(center_children=self.date_time) if __name__ == "__main__": bar = StatusBar() app = Application("bar-example", bar) app.run() ``` -------------------------------- ### Import Fabric UI Widgets for Basic Bar (Wayland/X11) Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/first-widget.mdx This snippet illustrates how to import additional Fabric UI widgets necessary for constructing a basic status bar, differentiating between Wayland and X11 display protocols. It includes imports for DateTime and CenterBox widgets, and specifically replaces the generic Window import with either WaylandWindow or X11Window to create 'layer windows' suitable for desktop widgets. ```python ... from fabric.widgets.datetime import DateTime from fabric.widgets.centerbox import CenterBox from fabric.widgets.wayland import WaylandWindow as Window # Replace the previous Window import with this ``` ```python ... from fabric.widgets.datetime import DateTime from fabric.widgets.centerbox import CenterBox from fabric.widgets.x11 import X11Window as Window # Replace the previous Window import with this ``` -------------------------------- ### Initialize Fabric StatusBar Class for Wayland and X11 Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/first-widget.mdx This snippet demonstrates the initialization of the `StatusBar` class, inheriting from `Window`. It shows how to configure the status bar's behavior and appearance differently for Wayland and X11 display servers using parameters like `layer`, `anchor`, `exclusivity`, `geometry`, and `type_hint`. ```python class StatusBar(Window): def __init__(self, **kwargs): super().__init__( layer="top", # Ensure it stays above other apps anchor="left top right", # Anchors the bar at the top, stretching from left to right exclusivity="auto", # Reserves space for the bar so it behaves like a normal window **kwargs ) ``` ```python class StatusBar(Window): def __init__(self, **kwargs): super().__init__( layer="top", # Ensure it stays above other apps geometry="top", # Position it at the top of the screen type_hint="dock", # Inform the window manager that this is a dock-like window **kwargs ) ``` -------------------------------- ### List All Running Fabric Instances (JSON Output) Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/getting-started/client-and-cli.mdx Shows how to retrieve a JSON-serialized list of running Fabric instances using the `-j` flag with the `fabric list-all` command. This provides a structured output suitable for programmatic parsing. ```python $ python -m fabric list-all -j # json serialization {'instances-dbus-names': ['org.Fabric.fabric.my-bar']} ``` -------------------------------- ### Set GDK_BACKEND Environment Variable for Wayland Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/getting-started/faq.mdx To ensure Fabric windows are rendered correctly as layers on Wayland compositors, the `GDK_BACKEND` environment variable must be explicitly set to `wayland`. This command demonstrates how to launch a Fabric configuration with the correct backend, preventing windows from appearing as normal desktop windows. ```bash env GDK_BACKEND=wayland python path/to/fabric/config ``` -------------------------------- ### Importing Astro Components for UI Development Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/index.mdx This snippet demonstrates how to import various UI components from Astro's Starlight library and local project files. These imports are essential for building the page's layout and interactive elements, allowing developers to reuse pre-defined components like buttons, card grids, and custom feature/showcase cards. ```JavaScript import { LinkButton, CardGrid, Badge, Card, Icon } from "@astrojs/starlight/components"; import { Image } from "astro:assets"; import FeatureCard from "../../components/FeatureCard.astro"; import ShowcaseCard from "../../components/ShowcaseCard.astro"; import HeroBackground from "../../components/HeroBackground.astro"; ``` -------------------------------- ### Open Current Directory in VS Code Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/contributing/development-environment.mdx Opens the current working directory in Visual Studio Code. This command is useful for continuing development within an integrated terminal or IDE environment. ```bash code . ``` -------------------------------- ### FASS Macro/Mixin Definition and Application Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/styling.mdx Shows how to define reusable macros (functions or mixins) in FASS with parameters, and then apply them to CSS selectors using the `@apply` directive to inject a block of styles. ```css @define my-macro(--color, --margin, --padding) { color: --color; margin: --margin; padding: --padding; } #my-widget { @apply my-macro(red, 0.5rem, 1rem); } ``` ```css #my-widget { color: red; margin: 0.5rem; padding: 1rem; } ``` -------------------------------- ### Launch GTK Inspector from Command Line Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/styling.mdx The GTK Inspector is a powerful debugging tool for styling issues. This shell command demonstrates how to launch your Python Fabric application with the GTK Inspector enabled, allowing you to inspect and debug widget styles interactively. ```sh GTK_DEBUG=interactive python config.py ``` -------------------------------- ### FASS Web CSS Variable Compilation Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/styling.mdx Demonstrates how FASS compiles standard web CSS variables defined within a `:vars` selector into GTK's native `@define-*` format for global scope, and how they are then referenced. ```css :vars { --my-color: red; } #my-widget { background-color: var(--my-color); } ``` ```css @define-color my-color red; #my-widget { background-color: @my-color; } ``` -------------------------------- ### Configure Hyprland for Fabric Window Blurring Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/getting-started/faq.mdx To enable background blurring for Fabric widgets on Hyprland, specific `layerrule` configurations need to be added to the Hyprland configuration file. These rules instruct the compositor to apply blur effects and ignore zero-sized areas for windows identified as 'fabric'. ```conf layerrule = blur, fabric layerrule = ignorezero, fabric ``` -------------------------------- ### Import Custom Astro Component for 404 Page Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/404.mdx Imports the `NotFoundView` component from a relative path. This component is designed to provide the specific UI and logic for the 404 error page, centralizing its implementation. ```Astro import NotFoundView from "../../components/NotFoundView.astro"; ``` -------------------------------- ### GTK CSS Selector Types and Usage Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/styling.mdx This section details the different types of CSS selectors available in GTK for styling widgets, comparing them to web CSS. It explains the syntax and recommended usage for type selectors, name selectors (IDs), and class selectors, emphasizing their roles in applying styles. ```APIDOC GTK CSS Selector Types: Type (widget's type): Syntax: `widget-type` (no prefix/suffix) Description: Selects all widgets of a specific type (e.g., `button`, `label`). Note: Generally not recommended for broad, hard-to-maintain styles. Names (widget's name): Syntax: `#widget-name` (hashtag prefixed name) Description: Selects a specific widget with the given name. Usage: Use for uniquely named widgets (e.g., `#main-button`, `#sidebar`). Avoid: Using names for state or variant styling (e.g., `#focused`, `#inactive`, `#blue-button`). Classes (widget's class): Syntax: `.widget-class` (dot prefixed name) Description: Selects widgets with a specific class or set of classes. Usage: Best for applying reusable styles for specific states or variants (e.g., `.primary`, `.disabled`, `.highlight`). ``` -------------------------------- ### Create Fabric UI Buttons with a Factory Function Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/first-widget.mdx This Python snippet demonstrates how to create and manage multiple Fabric UI buttons within an application window. It utilizes a factory function to generate new button instances, ensuring each widget is unique, and connects their click events to update their labels. The application sets up a basic window with a vertical box containing a label and a horizontal box of dynamically created buttons. ```python import fabric from fabric import Application from fabric.widgets.box import Box from fabric.widgets.label import Label from fabric.widgets.button import Button from fabric.widgets.window import Window def create_button(): # define a "factory function" return Button(label="Click Me", on_clicked=lambda b, *_: b.set_label("you clicked me")) if __name__ == "__main__": box = Box( orientation="v", children=[ Label(label="Fabric Buttons Demo"), Box( orientation="h", children=[ create_button(), create_button(), create_button(), create_button(), ], ), ], ) window = Window(child=box) app = Application("default", window) app.run() ``` -------------------------------- ### Add Widgets to Fabric StatusBar using CenterBox (Wayland/X11) Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/first-widget.mdx This snippet demonstrates how to add child widgets, specifically a `DateTime` widget, to the `StatusBar`. It utilizes a `CenterBox` to manage the positioning of the `DateTime` widget, ensuring it is neatly centered within the status bar for both Wayland and X11 configurations. ```python class StatusBar(Window): def __init__(self, **kwargs): super().__init__( layer="top", anchor="left top right", exclusivity="auto", **kwargs ) self.date_time = DateTime() self.children = CenterBox(center_children=self.date_time) ``` ```python class StatusBar(Window): def __init__(self, **kwargs): super().__init__( layer="top", geometry="top", type_hint="dock", **kwargs ) self.date_time = DateTime() self.children = CenterBox(center_children=self.date_time) ``` -------------------------------- ### Evaluate Python Code and Handle Errors Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/getting-started/client-and-cli.mdx Demonstrates using `fabric evaluate` to run Python code on a Fabric instance and shows how errors, such as an `AttributeError` when a method does not exist, are returned. This highlights the utility's ability to provide feedback on code execution. ```python $ python -m fabric evaluate my-bar "bar.this_method_does_not_exist()" # should return an error exception: AttributeError("'StatusBar' object has no attribute 'this_method_does_not_exist'") ``` -------------------------------- ### Import Fabric Service and Signal Decorator Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/services.mdx This snippet shows the necessary import statement to use the `Service` class and the `Signal` decorator from the `fabric.core.service` module when defining custom services. ```python from fabric.core.service import Service, Signal ``` -------------------------------- ### Render Custom Astro Component Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/404.mdx Renders the previously imported `NotFoundView` component within the Astro page's template. This action displays the custom 404 error interface to the end-user, leveraging the component's encapsulated design. ```Astro ``` -------------------------------- ### Creating a Custom Fabric Service with Signals in Python Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/contributing/hacking-guide.mdx Demonstrates how to define a custom service in Fabric by inheriting from `fabric.service.Service` and how to declare and emit custom signals using `SignalContainer` and `Signal` objects. This allows for event-driven communication within the Fabric application. ```python from fabric.service import * class MyUsefulService(Service): __gsignals__ = SignalContainer( Signal("my-really-useful-signal", "run-first", None, (object,)) # signal name, run flags, what does the call back return, the argument type of the callback ) def __init__(self): self.emit("my-really-useful-signal", "this is my super useful argument passed to you, what a useful string") ``` -------------------------------- ### Execute Python Code on Running Fabric Instance Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/getting-started/client-and-cli.mdx Illustrates how to execute a Python code snippet (`bar.hide()`) within a specified running Fabric instance using the `fabric execute` command. The `-j` flag is used here, though its effect on `execute` is not explicitly shown in the output. ```python $ python -m fabric execute my-bar "bar.hide()" -j # executing python code ``` -------------------------------- ### FASS Constant Definition and Compilation Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/styling.mdx Illustrates how to define immutable constants in FASS using `@define` and apply them to CSS properties using the `apply()` function. The compiled output shows the constants replaced by their actual values. ```css @define size-xl 12rem; @define wide-edges 2rem 4rem; #my-widget { padding: apply(size-xl); } #my-container { padding: apply(wide-edges); } ``` ```css #my-widget { padding: 12rem; } #my-container { padding: 2rem 4rem; } ``` -------------------------------- ### Fabric Core Components and Service API Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/contributing/hacking-guide.mdx Documentation for core Fabric components including the base `Widget` and `Service` classes, and how to define notifiable properties and custom signals within services. This covers the fundamental building blocks for extending Fabric's functionality. ```APIDOC fabric.widgets.widget.Widget - Description: The base widget class from which nearly all other Fabric widgets inherit properties and methods. - Purpose: Provides a common foundation for all Fabric widgets, simplifying global modifications. fabric.service.Service - Description: The base class for creating new Fabric services. - Usage: New services should inherit from this class. fabric.service.Property - Description: A decorator used in Fabric services to define notifiable properties. - Usage: Replaces the standard Python `@property` decorator for properties that should emit change notifications. fabric.service.SignalContainer - Description: A container object used to define custom signals for a Fabric service. - Usage: Assigned to the `__gsignals__` variable within a `Service` class. - Parameters: - `*signals`: One or more `Signal` objects. fabric.service.Signal - Description: Represents a custom signal that can be emitted by a Fabric service. - Usage: Used within a `SignalContainer` to define service signals. - Parameters: - `signal_name` (str): The name of the signal. - `run_flags` (str): GObject run flags (e.g., "run-first"). - `return_type` (type or None): The expected return type of the callback, or `None` if no return value. - `argument_types` (tuple): A tuple of argument types for the callback function. ``` -------------------------------- ### Calling Python Functions from FASS CSS Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/styling.mdx Demonstrates how to expose Python functions to FASS and call them directly from CSS using `@apply`. The Python function processes arguments from CSS and returns a style string, which FASS then injects into the compiled CSS. ```python # ... app = Application(...) app.set_stylesheet_from_file( "./style.css", exposed_functions={ "my-function": lambda prop, value: f"{prop}: {value};" }, ) ``` ```css #my-widget { @apply my-function(margin, 0.5rem); @apply my-function(padding, 1rem); } ``` ```css #my-widget { margin: 0.5rem; padding: 1rem; } ``` -------------------------------- ### Connecting to Property Change Notifications (Constructor) Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/services.mdx This snippet demonstrates an alternative, more concise way to connect to property change notifications directly within the service constructor. By passing a `notify_` argument, a callback is automatically registered for property updates. ```python # Initialize MyService with a callback for the status property notification example_service = MyService( initial_status="Initializing", notify_status=lambda *_: print("Status has changed") ) example_service.status = "Running" ``` -------------------------------- ### Apply Inline Styles to Fabric Widgets Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/styling.mdx Fabric allows applying CSS-like inline styles directly within a widget's definition using the `style` parameter. These styles are automatically compiled by default, offering a convenient way to apply specific styling to individual widget instances. ```python Label( style="color: red; font-size: 1rem;" ) # for the sake of this example we're using the Label widget # any other fabric widget should work the same way ``` -------------------------------- ### Dynamically Reload Fabric Stylesheet on File Change Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/styling.mdx This Python snippet demonstrates how to set up a file monitor to automatically reload your application's stylesheet whenever the CSS files change. This feature is highly beneficial for development, enabling live updates to styles without restarting the application. ```python app = Application(...) def apply_stylesheet(*_): return app.set_stylesheet_from_file( get_relative_path("./styles/style.css") ) style_monitor = monitor_file(get_relative_path("./styles")) style_monitor.connect("changed", apply_stylesheet) apply_stylesheet() # initial styling # ... ``` -------------------------------- ### Defining Properties in Fabric Services Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/services.mdx This snippet demonstrates how to define a property within a Fabric service using the `@Property` decorator. It shows specifying the data type, flags (e.g., 'read-write'), and implementing both a getter and a setter for the property. ```python from fabric.core.service import Service, Property class MyService(Service): @Property(str, flags="read-write") def status(self) -> str: return self._status @status.setter def status(self, value: str): self._status = value def __init__(self, status="", **kwargs): super().__init__(**kwargs) self._status = status ``` -------------------------------- ### Triggering a Signal in Fabric Source: https://github.com/fabric-development/fabric-wiki/blob/main/src/content/docs/guide/services.mdx This snippet demonstrates how changing a service's state (e.g., setting a name) can automatically trigger a predefined signal, notifying other parts of the application about the change. The `name_changed` signal is emitted when `set_name` is called. ```python name_service.set_name("Homan") ```