zenity

package module
v23.4.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 24, 2023 License: MIT Imports: 13 Imported by: 0

README

Zenity dialogs for Golang, Windows and macOS

This repo is a fork of go-zenity which implements some features of zenity (only those portable on every platform). This fork implements the missing features even i fthey can not be fully supported by each platform.

Go Reference Go Report Go Coverage Mentioned in Awesome Go

This repo includes:

  • a cross-platform Go package providing Zenity-like dialogs (simple dialogs that interact graphically with the user)
  • a “port” of the zenity command to both Windows and macOS based on that library.

Implemented dialogs:

Behavior on Windows, macOS and other Unixes might differ slightly. Some of that is intended (reflecting platform differences), other bits are unfortunate limitations.

Installing

The Go package:

go get github.com/agambier/zenity/v23@latest

The zenity command on macOS/WSL using Homebrew 🍺:

brew install ncruces/tap/zenity

The zenity command on Windows using Scoop 🍨:

scoop install https://ncruces.github.io/scoop/zenity.json

The zenity command on macOS/Windows, if you have Go:

go install github.com/agambier/zenity/v23/cmd/zenity@latest

Or download the latest release.

Using

For the Go package, consult the documentation and examples.

The zenity command does its best to be compatible with the GNOME version.
Consult the documentation and man page of that command.

Why?

Benefits of the Go package:
  • no cgo (see benefits, mostly cross-compilation)
  • no main loop (or any other threading or initialization requirements)
  • cancelation through context
  • on Windows:
    • no additional dependencies
      • Explorer shell not required
      • works in Server Core
    • Unicode support
    • High DPI (no manifest required)
    • Visual Styles (no manifest required)
    • WSL/Cygwin/MSYS2 support
  • on macOS:
    • only dependency is osascript
  • on other Unixes:
    • wraps either one of zenity, matedialog, qarma

Credits

I'd like to thank all contributors, but @gen2brain in particular for dlgs, which was instrumental to the Windows port of zenity.

Documentation

Overview

Package zenity provides cross-platform access to simple dialogs that interact graphically with the user.

It is inspired by, and closely follows the API of, the zenity program, which it uses to provide the functionality on various Unixes. See:

https://help.gnome.org/users/zenity/stable/

This package does not require cgo, and it does not impose any threading or initialization requirements.

Index

Examples

Constants

View Source
const (
	FormFieldEntry formFieldKind = iota
	FormFieldPassword
	FormFieldCalendar
	FormFieldComboBox
	FormFieldList
)
View Source
const ErrCanceled = zenutil.ErrCanceled

ErrCanceled is returned when the cancel button is pressed, or window functions are used to close the dialog.

View Source
const ErrExtraButton = zenutil.ErrExtraButton

ErrExtraButton is returned when the extra button is pressed.

View Source
const ErrUnsupported = zenutil.ErrUnsupported

ErrUnsupported is returned when a combination of options is not supported.

Variables

This section is empty.

Functions

func Calendar

func Calendar(text string, options ...Option) (time.Time, error)

Calendar displays the calendar dialog.

Valid options: Title, Width, Height, OKLabel, CancelLabel, ExtraButton, WindowIcon, Attach, Modal, DefaultDate.

May return: ErrCanceled, ErrExtraButton.

Example
zenity.Calendar("Select a date from below:",
	zenity.DefaultDate(2006, time.January, 1))
Output:

func Entry

func Entry(text string, options ...Option) (string, error)

Entry displays the text entry dialog.

Valid options: Title, Width, Height, OKLabel, CancelLabel, ExtraButton, WindowIcon, Attach, Modal, EntryText, HideText.

May return: ErrCanceled, ErrExtraButton.

Example
zenity.Entry("Enter new text:",
	zenity.Title("Add a new entry"))
Output:

func Error

func Error(text string, options ...Option) error

Error displays the error dialog.

Valid options: Title, Width, Height, OKLabel, ExtraButton, Icon, WindowIcon, Attach, Modal, NoWrap, Ellipsize.

May return: ErrCanceled, ErrExtraButton.

Example
zenity.Error("An error has occurred.",
	zenity.Title("Error"),
	zenity.ErrorIcon)
Output:

func Forms

func Forms(text string, options ...Option) ([]string, error)

func Info

func Info(text string, options ...Option) error

Info displays the info dialog.

Valid options: Title, Width, Height, OKLabel, ExtraButton, Icon, WindowIcon, Attach, Modal, NoWrap, Ellipsize.

May return: ErrCanceled, ErrExtraButton.

Example
zenity.Info("All updates are complete.",
	zenity.Title("Information"),
	zenity.InfoIcon)
Output:

func IsAvailable

func IsAvailable() bool

IsAvailable reports whether dependencies of the package are installed. It always returns true on Windows and macOS.

func List

func List(text string, items []string, options ...Option) (string, error)

List displays the list dialog.

Valid options: Title, Width, Height, OKLabel, CancelLabel, ExtraButton, WindowIcon, Attach, Modal, RadioList, DefaultItems, DisallowEmpty.

May return: ErrCanceled, ErrExtraButton, ErrUnsupported.

Example
zenity.List(
	"Select items from the list below:",
	[]string{"apples", "oranges", "bananas", "strawberries"},
	zenity.Title("Select items from the list"),
	zenity.DisallowEmpty(),
)
Output:

func ListItems

func ListItems(text string, items ...string) (string, error)

ListItems displays the list dialog.

May return: ErrCanceled, ErrUnsupported.

Example
zenity.ListItems(
	"Select items from the list below:",
	"apples", "oranges", "bananas", "strawberries")
Output:

func ListMultiple

func ListMultiple(text string, items []string, options ...Option) ([]string, error)

ListMultiple displays the list dialog, allowing multiple items to be selected.

Valid options: Title, Width, Height, OKLabel, CancelLabel, ExtraButton, WindowIcon, Attach, Modal, CheckList, DefaultItems, DisallowEmpty.

May return: ErrCanceled, ErrExtraButton, ErrUnsupported.

Example
zenity.ListMultiple(
	"Select items from the list below:",
	[]string{"apples", "oranges", "bananas", "strawberries"},
	zenity.Title("Select items from the list"),
	zenity.DefaultItems("apples", "bananas"),
)
Output:

func ListMultipleItems

func ListMultipleItems(text string, items ...string) ([]string, error)

ListMultipleItems displays the list dialog, allowing multiple items to be selected.

May return: ErrCanceled, ErrUnsupported.

Example
zenity.ListMultipleItems(
	"Select items from the list below:",
	"apples", "oranges", "bananas", "strawberries")
Output:

func Notify

func Notify(text string, options ...Option) error

Notify displays a notification.

Valid options: Title, Icon.

Example
zenity.Notify("There are system updates necessary!",
	zenity.Title("Warning"),
	zenity.InfoIcon)
Output:

func Password

func Password(options ...Option) (usr string, pwd string, err error)

Password displays the password dialog.

Valid options: Title, OKLabel, CancelLabel, ExtraButton, WindowIcon, Attach, Modal, Username.

May return: ErrCanceled, ErrExtraButton.

Example
zenity.Password(zenity.Title("Type your password"))
Output:

Example (Username)
zenity.Password(
	zenity.Title("Type your username and password"),
	zenity.Username())
Output:

func Question

func Question(text string, options ...Option) error

Question displays the question dialog.

Valid options: Title, Width, Height, OKLabel, CancelLabel, ExtraButton, Icon, WindowIcon, Attach, Modal, NoWrap, Ellipsize, DefaultCancel.

May return: ErrCanceled, ErrExtraButton.

Example
zenity.Question("Are you sure you want to proceed?",
	zenity.Title("Question"),
	zenity.QuestionIcon)
Output:

func SelectColor

func SelectColor(options ...Option) (color.Color, error)

SelectColor displays the color selection dialog.

Valid options: Title, WindowIcon, Attach, Modal, Color, ShowPalette.

May return: ErrCanceled.

Example
zenity.SelectColor(
	zenity.Color(color.NRGBA{R: 0x66, G: 0x33, B: 0x99, A: 0x80}))
Output:

Example (Palette)
zenity.SelectColor(
	zenity.ShowPalette(),
	zenity.Color(color.NRGBA{R: 0x66, G: 0x33, B: 0x99, A: 0xff}))
Output:

func SelectFile

func SelectFile(options ...Option) (string, error)

SelectFile displays the file selection dialog.

Valid options: Title, WindowIcon, Attach, Modal, Directory, Filename, ShowHidden, FileFilter(s).

May return: ErrCanceled.

Example
package main

import (
	"github.com/agambier/zenity"
)

const defaultPath = ``

func main() {
	zenity.SelectFile(
		zenity.Filename(defaultPath),
		zenity.FileFilters{
			{"Go files", []string{"*.go"}, false},
			{"Web files", []string{"*.html", "*.js", "*.css"}, true},
			{"Image files", []string{"*.png", "*.gif", "*.ico", "*.jpg", "*.webp"}, true},
		})
}
Output:

Example (Directory)
package main

import (
	"github.com/agambier/zenity"
)

const defaultPath = ``

func main() {
	zenity.SelectFile(
		zenity.Filename(defaultPath),
		zenity.Directory())
}
Output:

func SelectFileMultiple

func SelectFileMultiple(options ...Option) ([]string, error)

SelectFileMultiple displays the multiple file selection dialog.

Valid options: Title, WindowIcon, Attach, Modal, Directory, Filename, ShowHidden, FileFilter(s).

May return: ErrCanceled, ErrUnsupported.

Example
package main

import (
	"github.com/agambier/zenity"
)

const defaultPath = ``

func main() {
	zenity.SelectFileMultiple(
		zenity.Filename(defaultPath),
		zenity.FileFilters{
			{"Go files", []string{"*.go"}, false},
			{"Web files", []string{"*.html", "*.js", "*.css"}, true},
			{"Image files", []string{"*.png", "*.gif", "*.ico", "*.jpg", "*.webp"}, true},
		})
}
Output:

Example (Directory)
package main

import (
	"github.com/agambier/zenity"
)

const defaultPath = ``

func main() {
	zenity.SelectFileMultiple(
		zenity.Filename(defaultPath),
		zenity.Directory())
}
Output:

func SelectFileSave

func SelectFileSave(options ...Option) (string, error)

SelectFileSave displays the save file selection dialog.

Valid options: Title, WindowIcon, Attach, Modal, Filename, ConfirmOverwrite, ConfirmCreate, ShowHidden, FileFilter(s).

May return: ErrCanceled.

Example
package main

import (
	"github.com/agambier/zenity"
)

const defaultName = ``

func main() {
	zenity.SelectFileSave(
		zenity.ConfirmOverwrite(),
		zenity.Filename(defaultName),
		zenity.FileFilters{
			{"Go files", []string{"*.go"}, false},
			{"Web files", []string{"*.html", "*.js", "*.css"}, true},
			{"Image files", []string{"*.png", "*.gif", "*.ico", "*.jpg", "*.webp"}, true},
		})
}
Output:

func Warning

func Warning(text string, options ...Option) error

Warning displays the warning dialog.

Valid options: Title, Width, Height, OKLabel, ExtraButton, Icon, WindowIcon, Attach, Modal, NoWrap, Ellipsize.

May return: ErrCanceled, ErrExtraButton.

Example
zenity.Warning("Are you sure you want to proceed?",
	zenity.Title("Warning"),
	zenity.WarningIcon)
Output:

Types

type DialogIcon

type DialogIcon int

DialogIcon is an Option that sets the dialog icon.

const (
	ErrorIcon DialogIcon = iota
	WarningIcon
	InfoIcon
	QuestionIcon
	PasswordIcon
	NoIcon
)

The stock dialog icons.

type FileFilter

type FileFilter struct {
	Name     string   // display string that describes the filter (optional)
	Patterns []string // filter patterns for the display string
	CaseFold bool     // if set patterns are matched case-insensitively
}

FileFilter is an Option that sets a filename filter.

On Windows and macOS filtering is always case-insensitive.

macOS hides filename filters from the user, and only supports filtering by extension (or "uniform type identifiers").

Patterns may use the fnmatch syntax on all platforms: https://docs.python.org/3/library/fnmatch.html

type FileFilters

type FileFilters []FileFilter

FileFilters is an Option that sets multiple filename filters.

type Option

type Option interface {
	// contains filtered or unexported methods
}

An Option is an argument passed to dialog functions to customize their behavior.

func Attach

func Attach(id any) Option

Attach returns an Option to set the parent window to attach to.

Attach accepts:

  • a window id (int) on Unix
  • a window handle (~uintptr) on Windows
  • an application name (string) or process id (int) on macOS

func CalendarField

func CalendarField(name string) Option

func CancelLabel

func CancelLabel(cancel string) Option

CancelLabel returns an Option to set the label of the Cancel button.

func CheckList

func CheckList() Option

CheckList returns an Option to show check boxes (Unix only).

func ClassHint

func ClassHint(name, class string) Option

ClassHint returns an Option to set the program name and class as used by the window manager (Unix only).

func Color

func Color(c color.Color) Option

Color returns an Option to set the color.

func ComboBoxField

func ComboBoxField(name string, values ...string) Option

func ConfirmCreate

func ConfirmCreate() Option

ConfirmCreate returns an Option to confirm file selection if the file does not yet exist (Windows only).

func ConfirmOverwrite

func ConfirmOverwrite() Option

ConfirmOverwrite returns an Option to confirm file selection if the file already exists.

func Context

func Context(ctx context.Context) Option

Context returns an Option to set a Context that can dismiss the dialog.

Dialogs dismissed by ctx return ctx.Err().

func DefaultCancel

func DefaultCancel() Option

DefaultCancel returns an Option to give the Cancel button focus by default.

func DefaultDate

func DefaultDate(year int, month time.Month, day int) Option

DefaultDate returns an Option to set the date.

func DefaultItems

func DefaultItems(items ...string) Option

DefaultItems returns an Option to set the items to initially select (Windows and macOS only).

func Directory

func Directory() Option

Directory returns an Option to activate directory-only selection.

func DisallowEmpty

func DisallowEmpty() Option

DisallowEmpty returns an Option to not allow zero items to be selected (Windows and macOS only).

func Display

func Display(display string) Option

Display returns an Option to set the X display to use (Unix only).

func Ellipsize

func Ellipsize() Option

Ellipsize returns an Option to enable ellipsizing in the dialog text (Unix only).

func EntryField

func EntryField(name string) Option

func EntryText

func EntryText(text string) Option

EntryText returns an Option to set the entry text.

func ExtraButton

func ExtraButton(extra string) Option

ExtraButton returns an Option to add one extra button.

func Filename

func Filename(filename string) Option

Filename returns an Option to set the filename.

You can specify a file name, a directory path, or both. Specifying a file name, makes it the default selected file. Specifying a directory path, makes it the default dialog location.

func Height

func Height(height uint) Option

Height returns an Option to set the dialog height (Unix only).

func HideText

func HideText() Option

HideText returns an Option to hide the entry text.

func Icon

func Icon(icon any) Option

Icon returns an Option to set the dialog icon.

Icon accepts a DialogIcon, or a string. The string can be a GTK icon name (Unix), or a file path (Windows and macOS). Supported file formats depend on the plaftorm, but PNG should be cross-platform.

func ListField

func ListField(name string, showHeader bool, cols []string, values ...string) Option

func MaxValue

func MaxValue(value int) Option

MaxValue returns an Option to set the maximum value. The default maximum value is 100.

func MidSearch

func MidSearch() Option

MidSearch returns an Option to change list search to find text in the middle, not on the beginning (Unix only).

func Modal() Option

Modal returns an Option to set the modal hint.

func NoCancel

func NoCancel() Option

NoCancel returns an Option to hide the Cancel button (Windows and Unix only).

func NoWrap

func NoWrap() Option

NoWrap returns an Option to disable text wrapping (Unix only).

func OKLabel

func OKLabel(ok string) Option

OKLabel returns an Option to set the label of the OK button.

func PasswordField

func PasswordField(name string) Option

func Pulsate

func Pulsate() Option

Pulsate returns an Option to pulsate the progress bar.

func RadioList

func RadioList() Option

RadioList returns an Option to show radio boxes (Unix only).

func ShowHidden

func ShowHidden() Option

ShowHidden returns an Option to show hidden files (Windows and macOS only).

func ShowPalette

func ShowPalette() Option

ShowPalette returns an Option to show the palette.

func TimeRemaining

func TimeRemaining() Option

TimeRemaining returns an Option to estimate when progress will reach 100% (Unix only).

func Title

func Title(title string) Option

Title returns an Option to set the dialog title.

func Username

func Username() Option

Username returns an Option to display the username.

func Width

func Width(width uint) Option

Width returns an Option to set the dialog width (Unix only).

func WindowIcon

func WindowIcon(icon any) Option

WindowIcon returns an Option to set the window icon.

WindowIcon accepts a DialogIcon, or a string file path. Supported file formats depend on the plaftorm, but PNG should be cross-platform.

type ProgressDialog

type ProgressDialog interface {
	// Text sets the dialog text.
	Text(string) error

	// Value sets how much of the task has been completed.
	Value(int) error

	// MaxValue gets how much work the task requires in total.
	MaxValue() int

	// Complete marks the task completed.
	Complete() error

	// Close closes the dialog.
	Close() error

	// Done returns a channel that is closed when the dialog is closed.
	Done() <-chan struct{}
}

ProgressDialog allows you to interact with the progress indication dialog.

func Progress

func Progress(options ...Option) (ProgressDialog, error)

Progress displays the progress indication dialog.

Valid options: Title, Width, Height, OKLabel, CancelLabel, ExtraButton, Icon, WindowIcon, Attach, Modal, MaxValue, Pulsate, NoCancel, TimeRemaining.

May return: ErrUnsupported.

Example
dlg, err := zenity.Progress(
	zenity.Title("Update System Logs"))
if err != nil {
	return
}
defer dlg.Close()

dlg.Text("Scanning mail logs...")
dlg.Value(0)
time.Sleep(time.Second)

dlg.Value(25)
time.Sleep(time.Second)

dlg.Text("Updating mail logs...")
dlg.Value(50)
time.Sleep(time.Second)

dlg.Text("Resetting cron jobs...")
dlg.Value(75)
time.Sleep(time.Second)

dlg.Text("Rebooting system...")
dlg.Value(100)
time.Sleep(time.Second)

dlg.Complete()
time.Sleep(time.Second)
Output:

Example (Pulsate)
dlg, err := zenity.Progress(
	zenity.Title("Update System Logs"),
	zenity.Pulsate())
if err != nil {
	return
}
defer dlg.Close()

dlg.Text("Scanning mail logs...")
time.Sleep(time.Second)

dlg.Text("Updating mail logs...")
time.Sleep(time.Second)

dlg.Text("Resetting cron jobs...")
time.Sleep(time.Second)

dlg.Text("Rebooting system...")
time.Sleep(time.Second)

dlg.Complete()
time.Sleep(time.Second)
Output:

Directories

Path Synopsis
cmd
internal
win
Package win is internal.
Package win is internal.
zencmd
Package zencmd is internal.
Package zencmd is internal.
zenutil
Package zenutil is internal.
Package zenutil is internal.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL