Search code examples
luaawesome-wm

Add a widget from awful.spawn.easy_async?


I'd like to add a power-status widget but only if the system supports it (I run the same config on my desktop as my laptop). Obviously I could check the hostname, but I'd rather just check if acpi is available. Currently I've got this:

mybattery = nil    
awful.spawn.easy_async("acpi",
                           function(stdout, stderr, reason, exit_code)
                               if string.find(stdout, "^Battery") then
                                   mybattery = batteryarc_widget{
                                       show_current_level = true,
                                       arc_thickness = 1
                                   }
                               end
                           end
    )

Then mybattery is added as a widget. This fails, presumably because updating mybattery later doesn't update the wibar. How do I add a widget after the fact? Or is there a better way to do this? I'd rather not call acpi synchronously.

Followup: Since this widget periodically polls acpi and pops up warnings when it fails to find a battery I didn't want to create the widget at all unless it would work. So taking Emmanuel's other suggestion, this is what I ended up with. vert_sep is just a separator widget and mybattery is added to the wibar later in the config.

mybattery = wibox.container.background()
awful.spawn.easy_async("acpi",
                       function(stdout, stderr, reason, exit_code)
                           if string.find(stdout, "^Battery") then
                               local batteryarc_widget =
                                   require("awesome-wm-widgets.batteryarc-widget.batteryarc")
                               local w = wibox.layout.fixed.horizontal()
                               w:add(batteryarc_widget{
                                         show_current_level = true,
                                         arc_thickness = 1})
                               w:add(vert_sep)
                               mybattery.widget = w
                           end
                       end
)

Solution

  • There is multiple ways. You can use the layout :add() or :insert() methods [1]. It is also possible to create the widget even if it wont be used. The use visible = false or forced_width = 0 to make sure it isn't shown. This has a microscopic performance penalty, but is simpler than using the imperative layout methods. A third way would be to add a placeholder container and set its .widget later. However at that point, the visible trick seems simpler.

    [1] https://awesomewm.org/apidoc/widget_layouts/wibox.layout.fixed.html#insert