diff --git a/.flake8 b/.flake8
index 993f8dd..095595a 100644
--- a/.flake8
+++ b/.flake8
@@ -1,3 +1,3 @@
[flake8]
ignore=E501,E123,E124,E402,E731,E722,W504
-exclude=subprojects,build
+exclude=subprojects,build,.venv
diff --git a/.gitignore b/.gitignore
index 6b6f944..bb3630d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -29,3 +29,5 @@
*.pyd
*.dll.a
.coverage
+pdm.lock
+.pdm-python
\ No newline at end of file
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index 2eed8e7..4e4175e 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -45,16 +45,17 @@ pages:
dependencies:
- coverage
before_script:
- - python -m pip install -r docs/requirements.txt
+ - python -m pip install "pdm!=2.17.3"
+ - python -m pdm install -v
script:
- - python -m sphinx -T -E -W --keep-going -b html -d _build/doctrees -D language=en docs/ public
+ - python -m pdm run sphinx-build -T -E -W --keep-going -b html -d _build/doctrees -D language=en docs/ public
- mv coverage/ public/
artifacts:
paths:
- public
expire_in: 30 days
only:
- - master
+ - main
sdist:
stage: build_and_test
@@ -75,12 +76,6 @@ mingw64:
MSYSTEM: "MINGW64"
<<: *mingw-defaults
-python3.8:
- variables:
- PYTHON_VERSION: "3.8"
- TEST_GTK_VERSION: "3.0"
- <<: *defaults
-
python3.9:
variables:
PYTHON_VERSION: "3.9"
@@ -112,7 +107,6 @@ python3.12:
<<: *defaults
pypy3:
- allow_failure: true
variables:
PYTHON_VERSION: "pypy3"
TEST_GTK_VERSION: "3.0"
@@ -126,9 +120,14 @@ old-i386-py3:
- coverage/
script:
- bash -x ./.gitlab-ci/test-docker-old.sh
+ # This build sometimes fails with message:
+ # ninja: error: loading 'build.ninja': Value too large for defined data type
+ retry:
+ max: 2
+ when: runner_system_failure
+ exit_codes: 1
gnome-master:
- allow_failure: true
stage: build_and_test
image: quay.io/gnome_infrastructure/gnome-runtime-images:gnome-master
tags:
@@ -155,6 +154,17 @@ gnome-master-gtk4:
script:
- bash -x ./.gitlab-ci/test-flatpak.sh
+python3.12-pdm:
+ stage: build_and_test
+ variables:
+ PYTHON_VERSION: "3.12"
+ TEST_GTK_VERSION: "3.0"
+ before_script:
+ - python -m pip install "pdm!=2.17.3"
+ - python -m pdm install -v
+ script:
+ - xvfb-run -a python -m pdm run pytest
+
minimal-meson:
allow_failure: true
stage: build_and_test
@@ -164,4 +174,4 @@ minimal-meson:
script:
- meson setup _build
- meson compile -C _build
- - PYTEST_ADDOPTS="-k 'not test_cairo'" meson test -C _build --verbose
+ - PYTEST_ADDOPTS="-sv -k 'not test_cairo'" meson test -C _build --suite pygobject --verbose
diff --git a/.gitlab-ci/build-sdists.sh b/.gitlab-ci/build-sdists.sh
index a8f3291..3e0393b 100755
--- a/.gitlab-ci/build-sdists.sh
+++ b/.gitlab-ci/build-sdists.sh
@@ -13,23 +13,16 @@ rm -Rf _sdist_build
meson setup _sdist_build
meson dist --no-tests --allow-dirty -C _sdist_build
mv _sdist_build/meson-dist/*.tar.xz dist/
+
+VERSION=$(meson introspect --projectinfo --indent _sdist_build | awk -F'"' '/version/ { print $4 }')
+
rm -Rf _sdist_build
# Now the sdist for pypi
# Mark odd versions as PEP440 development versions (e.g. 0.1.0 -> 0.1.0.dev0)
-cp pyproject.toml pyproject.toml.bak
-awk '{
- if (/^version = "/) {
- split($0, a, "[ .\"]+");
- if (a[4] % 2 != 0)
- printf "version = \"%s.%s.%s.dev0\"\n", a[3], a[4], a[5];
- else
- print $0;
- } else {
- print $0;
- }
- }' pyproject.toml > _temp && mv _temp pyproject.toml
+[[ "$VERSION" =~ ^[0-9]\.[0-9]*[13579]\. ]] && meson rewrite kwargs set project / version ${VERSION}.dev0
python -m pip install --upgrade build
python -m build --sdist
-mv pyproject.toml.bak pyproject.toml
+
+meson rewrite kwargs set project / version ${VERSION}
diff --git a/.gitlab-ci/test-docker.sh b/.gitlab-ci/test-docker.sh
index 485484f..c91d017 100755
--- a/.gitlab-ci/test-docker.sh
+++ b/.gitlab-ci/test-docker.sh
@@ -32,7 +32,7 @@ source /tmp/venv/bin/activate
mkdir -p /tmp/venv/include/pypy3.9
python -m pip install --upgrade pip
-python -m pip install flake8 meson meson-python pycairo
+python -m pip install flake8 meson meson-python pycairo pytest pytest-cov
# CODE QUALITY
python -m flake8
@@ -40,6 +40,7 @@ python -m flake8
# BUILD & TEST
python -m pip install --config-settings=setup-args="-Dtests=true" --no-build-isolation --editable '.[dev]'
+# TEST
lcov --config-file .gitlab-ci/lcovrc --directory . --capture --initial --output-file \
"${COV_DIR}/${CI_JOB_NAME}-baseline.lcov"
diff --git a/.gitlab-ci/test-flatpak.sh b/.gitlab-ci/test-flatpak.sh
index c882f3d..7bc76e7 100755
--- a/.gitlab-ci/test-flatpak.sh
+++ b/.gitlab-ci/test-flatpak.sh
@@ -10,11 +10,11 @@ if [[ "$1" == "inflatpak" ]]; then
export COVERAGE_FILE="${COV_DIR}/.coverage.${COV_KEY}"
mkdir -p "${COV_DIR}"
- python3 -m venv _venv
- . _venv/bin/activate
- pip install pycairo meson meson-python
- pip install --config-settings=setup-args="-Dtests=true" --no-build-isolation --editable '.[dev]'
- pytest -v --cov
+ python3 --version
+
+ pip install pycairo meson meson-python pytest pytest-cov
+ pip install --config-settings=setup-args="-Dtests=true" --no-build-isolation --editable .
+ python -m pytest -v --cov
python3 -m coverage lcov -o "${COV_DIR}/${COV_KEY}.py.lcov"
chmod -R 777 "${COV_DIR}"
else
diff --git a/.readthedocs.yaml b/.readthedocs.yaml
deleted file mode 100644
index 719ca91..0000000
--- a/.readthedocs.yaml
+++ /dev/null
@@ -1,13 +0,0 @@
-version: 2
-
-build:
- os: ubuntu-22.04
- tools:
- python: "3.8"
-
-sphinx:
- configuration: docs/conf.py
-
-python:
- install:
- - requirements: docs/requirements.txt
\ No newline at end of file
diff --git a/PKG-INFO.in b/METADATA.in
similarity index 90%
rename from PKG-INFO.in
rename to METADATA.in
index 496c5ce..7169b8c 100644
--- a/PKG-INFO.in
+++ b/METADATA.in
@@ -2,7 +2,7 @@ Metadata-Version: 1.2
Name: PyGObject
Version: @VERSION@
Summary: Python bindings for GObject Introspection
-Home-page: https://gnome.pages.gitlab.gnome.org/pygobject
+Home-page: https://pygobject.gnome.org
Author: James Henstridge
Author-email: james@daa.com.au
Maintainer: Simon Feltman
@@ -18,4 +18,4 @@ Classifier: Operating System :: Microsoft :: Windows
Classifier: Programming Language :: C
Classifier: Programming Language :: Python
Classifier: Topic :: Software Development :: Libraries :: Python Modules
-Requires-Python: >=3.8, <4
+Requires-Python: >=3.9, <4
diff --git a/NEWS b/NEWS
index 1603c0f..56c1983 100644
--- a/NEWS
+++ b/NEWS
@@ -1,15 +1,42 @@
+3.50.0 - 2024-09-12
+-------------------
+
+* tests: Fix event test errors when GTK is not installed :mr:`347`
+
+
+3.49.0 - 2024-09-06 (pre-release)
+---------------------------------
+
+* Rename master branch to main
+* Drop support for Python 3.8 :mr:`300`
+* Add Override for Gio.DataInputStream :mr:`293`
+* Treat GParamSpec as any other fundamental type :mr:`268`
+* override connection.register_object to prevent an invocation object from
+ leaking :mr:`219`
+* Various PyPy related fixes :mr:`299`
+* bind_property: Accept keyword arguments :mr:`309`
+* Various documentation improvements :mr:`342` :mr:`343` :mr:`338`
+ :mr:`336` :mr:`335` :mr:`328` :mr:`329` :mr:`330` :mr:`325` :mr:`322` :mr:`312`
+* Python2 / GTK2 cleanups :mr:`338` :mr:`331`
+* asyncio integration with support to await Gio async functions :mr:`189`
+* meson: move from .egg-info to .dist-info/METADATA :mr:`306`
+* build: fixes for building with gobject-introspection 1.81 :mr:`344`
+
+
3.48.2 - 2024-04-06
-------------------
* Fix support for fundamental (primitive) types, such as Gst.Bitmask
:issue:`624` :mr:`304`
+
3.48.1 - 2024-03-10
-------------------
* Fix installation with pip failing in some environments with
ModuleNotFoundError in g-ir-scanner :issue:`622` :mr:`302`
+
3.48.0 - 2024-03-09
-------------------
diff --git a/README.rst b/README.rst
index 8727396..a6cf160 100644
--- a/README.rst
+++ b/README.rst
@@ -6,17 +6,48 @@
|
**PyGObject** is a Python package which provides bindings for `GObject
-`__ based libraries such as `GTK
+`__ based libraries such as `GTK
`__, `GStreamer `__,
`WebKitGTK `__, `GLib
-`__, `GIO
-`__ and many more.
+`__, `GIO
+`__ and many more.
-It supports Linux, Windows and macOS and works with **Python 3.8+** and
+It supports Linux, Windows, and macOS and works with **Python 3.9+** and
**PyPy3**. PyGObject, including this documentation, is licensed under the
**LGPLv2.1+**.
+Homepage
+--------
-----
+https://pygobject.gnome.org
-For more information visit https://gnome.pages.gitlab.gnome.org/pygobject
+Installation
+------------
+
+The latest version from PyGObject can be installed from `PyPI `__:
+
+ pip install PyGObject
+
+PyGObject is only distributed as source distribution, so you need a C compiler installed on your host.
+
+Please have a look at our `Getting Started `__ documentation
+for OS specific installation instructions.
+
+Development
+~~~~~~~~~~~
+
+Our website contains instructions on how to `set up a development environment
+`__.
+
+Default branch renamed to ``main``
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The default development branch of PyGObject has been renamed
+to ``main``. To update your local checkout, use::
+
+ git checkout master
+ git branch -m master main
+ git fetch
+ git branch --unset-upstream
+ git branch -u origin/main
+ git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/main
diff --git a/debian/changelog b/debian/changelog
index 20eddd2..c3c7a44 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,3 +1,43 @@
+pygobject (3.50.0-4) unstable; urgency=medium
+
+ [ Simon McVittie ]
+ * d/p/async-Use-correct-T_BOOL-type-for-_asyncio_future_blockin.patch:
+ Mark patch as applied upstream
+ * d/salsa-ci.yml: Use recommended recipe URL
+ * d/salsa-ci.yml: Disable Architecture: all build
+ * d/salsa-ci.yml: Don't attempt cross-building
+ * d/control: Explicitly build-depend on required GIR XML
+ * d/control: Build-depend on gobject-introspection and libgirepository-1.0-dev
+
+ -- Jeremy Bícha Fri, 17 Jan 2025 18:50:54 -0500
+
+pygobject (3.50.0-3) unstable; urgency=medium
+
+ * Team upload
+ * Release to unstable (Closes: #1082723)
+
+ -- Simon McVittie Sat, 26 Oct 2024 13:44:07 +0100
+
+pygobject (3.50.0-2) experimental; urgency=medium
+
+ * Team upload
+ * d/p/async-Use-correct-T_BOOL-type-for-_asyncio_future_blockin.patch:
+ Add proposed patch to fix asyncio calls on big-endian machines
+ (Closes: #1085891)
+ * Standards-Version: 4.7.0 (no changes required)
+ * d/source/lintian-overrides: Mark missing B-D on mesonpy as a false
+ positive.
+ We currently build with Meson directly, not via mesonpy.
+
+ -- Simon McVittie Wed, 23 Oct 2024 13:53:17 +0100
+
+pygobject (3.50.0-1) experimental; urgency=medium
+
+ * New upstream release
+ * .egg-info has been replaced by .dist-info/METADATA
+
+ -- Jeremy Bícha Mon, 16 Sep 2024 15:37:16 -0400
+
pygobject (3.48.2-1) unstable; urgency=medium
* New upstream release
diff --git a/debian/control b/debian/control
index 1e97947..2647c7f 100644
--- a/debian/control
+++ b/debian/control
@@ -7,11 +7,14 @@ Build-Depends: at-spi2-core ,
dbus-daemon ,
debhelper-compat (= 13),
dh-sequence-python3,
- gir1.2-gtk-3.0 ,
+ gir1.2-cairo-1.0-dev,
+ gir1.2-gio-2.0-dev,
gir1.2-girepository-2.0 ,
+ gir1.2-gtk-3.0 ,
+ gobject-introspection,
libcairo2-dev,
libffi-dev (>= 3.3),
- libgirepository1.0-dev (>= 1.64.0~),
+ libgirepository-1.0-dev,
libglib2.0-dev (>= 2.64.0),
locales ,
meson,
@@ -23,7 +26,7 @@ Build-Depends: at-spi2-core ,
xauth ,
xvfb
Rules-Requires-Root: no
-Standards-Version: 4.6.2
+Standards-Version: 4.7.0
Vcs-Browser: https://salsa.debian.org/gnome-team/pygobject
Vcs-Git: https://salsa.debian.org/gnome-team/pygobject.git
Homepage: https://pygobject.readthedocs.io/
diff --git a/debian/patches/async-Use-correct-T_BOOL-type-for-_asyncio_future_blockin.patch b/debian/patches/async-Use-correct-T_BOOL-type-for-_asyncio_future_blockin.patch
new file mode 100644
index 0000000..738aaad
--- /dev/null
+++ b/debian/patches/async-Use-correct-T_BOOL-type-for-_asyncio_future_blockin.patch
@@ -0,0 +1,40 @@
+From: Simon McVittie
+Date: Wed, 23 Oct 2024 12:01:24 +0100
+Subject: async: Use correct T_BOOL type for _asyncio_future_blocking
+
+Declaring a PyMemberDef with type T_BOOL requires the corresponding C
+type to be char, with value 0 or 1: when the member is read, CPython
+will effectively be dereferencing
+`* (char *) &pygiasync._asyncio_future_blocking`.
+
+On little-endian architectures, in practice this worked, because the
+low-order bits of an int are in the first byte, which would take value
+0 or 1 as desired, with all other bits zero. However, on big-endian
+architectures, the low-order bits of an int are in the last byte, so
+reading the _asyncio_future_blocking attribute from Python code would
+in practice always produce 0, even when the int field had been set to 1
+from C code.
+
+Reference: https://docs.python.org/3/c-api/structures.html#member-types
+Bug: https://gitlab.gnome.org/GNOME/pygobject/-/issues/650
+Bug-Debian: https://bugs.debian.org/1085891
+Signed-off-by: Simon McVittie
+Forwarded: https://gitlab.gnome.org/GNOME/pygobject/-/merge_requests/367
+Applied-upstream: 3.51.0, commit:a2445df58a712980ccd0c21d75a631c6bda89b2b
+---
+ gi/pygi-async.h | 2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/gi/pygi-async.h b/gi/pygi-async.h
+index d5e7a92..341d623 100644
+--- a/gi/pygi-async.h
++++ b/gi/pygi-async.h
+@@ -37,7 +37,7 @@ typedef struct {
+ PyGICallableInfo *finish_func;
+ PyObject *loop;
+ PyObject *cancellable;
+- int _asyncio_future_blocking;
++ char _asyncio_future_blocking;
+ PyObject *result;
+ PyObject *exception;
+
diff --git a/debian/patches/series b/debian/patches/series
index e69de29..c8c37d4 100644
--- a/debian/patches/series
+++ b/debian/patches/series
@@ -0,0 +1 @@
+async-Use-correct-T_BOOL-type-for-_asyncio_future_blockin.patch
diff --git a/debian/python3-gi.install b/debian/python3-gi.install
index e02d380..ef95c95 100644
--- a/debian/python3-gi.install
+++ b/debian/python3-gi.install
@@ -1,5 +1,5 @@
usr/lib/python3*/*-packages/gi/_gi.cpython-3*[0-9m]-${DEB_HOST_MULTIARCH}.so
usr/lib/python3*/*-packages/gi/*.py
usr/lib/python3*/*-packages/gi/*/*.py
-usr/lib/python3*/*-packages/*.egg-info
usr/lib/python3*/*-packages/pygtkcompat/*.py
+usr/lib/python3*/*/PyGObject-*.dist-info/METADATA
diff --git a/debian/salsa-ci.yml b/debian/salsa-ci.yml
index 33c3a64..de4f8ce 100644
--- a/debian/salsa-ci.yml
+++ b/debian/salsa-ci.yml
@@ -1,4 +1,7 @@
---
include:
- - https://salsa.debian.org/salsa-ci-team/pipeline/raw/master/salsa-ci.yml
- - https://salsa.debian.org/salsa-ci-team/pipeline/raw/master/pipeline-jobs.yml
+ - https://salsa.debian.org/salsa-ci-team/pipeline/raw/master/recipes/debian.yml
+
+variables:
+ SALSA_CI_DISABLE_BUILD_PACKAGE_ALL: '1'
+ SALSA_CI_DISABLE_CROSSBUILD_ARM64: 1
diff --git a/debian/source/lintian-overrides b/debian/source/lintian-overrides
new file mode 100644
index 0000000..0f33d7c
--- /dev/null
+++ b/debian/source/lintian-overrides
@@ -0,0 +1,2 @@
+# We build with Meson directly, not via mesonpy
+missing-prerequisite-for-pyproject-backend mesonpy (*) [pyproject.toml:*]
diff --git a/debian/upstream/metadata b/debian/upstream/metadata
index 1871057..45446a4 100644
--- a/debian/upstream/metadata
+++ b/debian/upstream/metadata
@@ -1,3 +1,4 @@
+---
Bug-Database: https://gitlab.gnome.org/GNOME/pygobject/-/issues
Bug-Submit: https://gitlab.gnome.org/GNOME/pygobject/-/issues/new
Repository: https://gitlab.gnome.org/GNOME/pygobject.git
diff --git a/docs/bugs_repo.rst b/docs/bugs_repo.rst
index 830c23f..c1e8fb8 100644
--- a/docs/bugs_repo.rst
+++ b/docs/bugs_repo.rst
@@ -9,8 +9,8 @@ Bug Tracker / Git / Source
We use the GNOME GitLab issue tracker:
-* List of existing issues: https://gitlab.gnome.org/GNOME/pygobject/issues
-* Create a new issue: https://gitlab.gnome.org/GNOME/pygobject/issues/new
+* List of existing issues: https://gitlab.gnome.org/GNOME/pygobject/-/issues
+* Create a new issue: https://gitlab.gnome.org/GNOME/pygobject/-/issues/new
|git-logo| Git Repo
diff --git a/docs/changelog.rst b/docs/changelog.rst
index 0e78f5e..07c06de 100644
--- a/docs/changelog.rst
+++ b/docs/changelog.rst
@@ -5,7 +5,7 @@ Versions with an odd minor version are unstable releases (e.g. 3.27.x) while
versions with even minor version are stable releases (e.g. 3.28.x). This list
is sorted by release date.
-For more details see the GIT log:
-https://gitlab.gnome.org/GNOME/pygobject/commits/master
+For more details see the Git log:
+https://gitlab.gnome.org/GNOME/pygobject/-/commits/main
.. include:: ../NEWS
diff --git a/docs/conf.py b/docs/conf.py
index 469fe8d..245a578 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -2,16 +2,16 @@
'sphinx.ext.todo',
'sphinx.ext.intersphinx',
'sphinx.ext.extlinks',
+ 'sphinx_copybutton',
]
intersphinx_mapping = {
- 'gtk': ('https://lazka.github.io/pgi-docs/Gtk-3.0', None),
- 'gobject': ('https://lazka.github.io/pgi-docs/GObject-2.0', None),
- 'glib': ('https://lazka.github.io/pgi-docs/GLib-2.0', None),
- 'gdk': ('https://lazka.github.io/pgi-docs/Gdk-3.0', None),
- 'gio': ('https://lazka.github.io/pgi-docs/Gio-2.0', None),
'python': ('https://docs.python.org/3', None),
'cairo': ('https://pycairo.readthedocs.io/en/latest', None),
+ 'apidocs': (
+ 'https://amolenaar.pages.gitlab.gnome.org/pygobject-docs',
+ None,
+ ),
}
source_suffix = '.rst'
@@ -24,6 +24,9 @@
html_favicon = "images/favicon.ico"
project = "PyGObject"
html_title = project
+html_theme_options = {
+ 'source_edit_link': 'https://gitlab.gnome.org/GNOME/pygobject/-/blob/main/docs/{filename}',
+}
html_context = {
'extra_css_files': [
@@ -33,7 +36,7 @@
"display_gitlab": True,
"gitlab_user": "GNOME",
"gitlab_repo": "pygobject",
- "gitlab_version": "master",
+ "gitlab_version": "main",
"conf_py_path": "/docs/",
"gitlab_host": "gitlab.gnome.org",
}
@@ -45,11 +48,12 @@
extlinks = {
'bzbug': ('https://bugzilla.gnome.org/show_bug.cgi?id=%s', 'bz#%s'),
- 'issue': ('https://gitlab.gnome.org/GNOME/pygobject/issues/%s', '#%s'),
+ 'issue': ('https://gitlab.gnome.org/GNOME/pygobject/-/issues/%s', '#%s'),
'commit': ('https://gitlab.gnome.org/GNOME/pygobject/commit/%s', '%s'),
'mr': (
- 'https://gitlab.gnome.org/GNOME/pygobject/merge_requests/%s', '!%s'),
+ 'https://gitlab.gnome.org/GNOME/pygobject/-/merge_requests/%s', '!%s'),
'user': ('https://gitlab.gnome.org/%s', '%s'),
+ 'devdocs': ('https://developer.gnome.org/documentation/%s.html', None)
}
suppress_warnings = ["image.nonlocal_uri"]
diff --git a/docs/devguide/dev_environ.rst b/docs/devguide/dev_environ.rst
index 3fb5f4c..5318c54 100644
--- a/docs/devguide/dev_environ.rst
+++ b/docs/devguide/dev_environ.rst
@@ -160,6 +160,33 @@ First, check out the source code:
git clone https://gitlab.gnome.org/GNOME/pygobject.git
cd pygobject
+With a local copy of PyGObject, there's three ways to start developing:
+
+1. PDM, a modern Python package and dependency manager
+2. Pip, the default Python package installer
+3. Meson, use the Meson build system directly
+
+
+PDM
+---
+
+Make sure you have `PDM `_ 2.13 or newer installed.
+
+Then set up the project by running:
+
+.. code:: console
+
+ pdm install
+
+You can run teh unit tests with:
+
+.. code:: console
+
+ pdm run pytest
+
+
+Pip
+---
It's always a good idea to work from within a Python virtual environment.
PyGObject is built with `Meson `_.
@@ -171,7 +198,7 @@ Meson-python, Meson, and Ninja should be installed in the virtual environment.
python3 -m venv .venv
source .venv/bin/activate
- pip install meson-python meson ninja pycairo
+ pip install meson-python meson ninja pycairo pytest
.. note::
@@ -181,14 +208,14 @@ Install PyGObject in your local environment with the ``--no-build-isolation`` to
.. code:: console
- pip install --no-build-isolation -e '.[dev]'
+ pip install --no-build-isolation --config-settings=setup-args="-Dtests=true" -e '.[dev]'
By default the C libraries are built in "release" mode (no debug symbols).
To compile the C libraries with debug symbols, run
.. code:: console
- pip install --no-build-isolation --config-settings=setup-args="-Dbuildtype=debug" -e '.[dev]'
+ pip install --no-build-isolation --config-settings=setup-args="-Dbuildtype=debug" --config-settings=setup-args="-Dtests=true" -e '.[dev]'
Open a Python console:
@@ -202,19 +229,16 @@ Run the unittests:
pytest
-It's also not possible to run the tests from meson:
-
-.. code:: console
-
- meson setup _build # Needed only once
- meson test -C _build
+Meson
+-----
-Create a release tarball and wheel:
+It's also possible to run the tests from Meson. Tests are still run with Pytest, so it's important
+that Pytest is installed.
.. code:: console
- pip install build
- python -m build
+ meson setup _build # Needed only once
+ meson test -C _build
.. _pyenv: https://github.com/pyenv/pyenv
\ No newline at end of file
diff --git a/docs/devguide/override_guidelines.rst b/docs/devguide/override_guidelines.rst
index 35f3f4b..5d2d91f 100644
--- a/docs/devguide/override_guidelines.rst
+++ b/docs/devguide/override_guidelines.rst
@@ -5,8 +5,7 @@ Python Override Guidelines
This document serves as a guide for developers creating new PyGObject
overrides or modifying existing ones. This document is not intended as hard
rules as there may always be pragmatic exceptions to what is listed here. It
-is also a good idea to study the `Zen of Python by Tim Peters
-`__.
+is also a good idea to study the Zen of Python by Tim Peters in :pep:`20`.
In general, overrides should be minimized and preference should always be
placed on updating the underlying API to be more bindable, adding features to
diff --git a/docs/devguide/style_guide.rst b/docs/devguide/style_guide.rst
index 0cd01fd..c0971ab 100644
--- a/docs/devguide/style_guide.rst
+++ b/docs/devguide/style_guide.rst
@@ -5,8 +5,7 @@ Style Guidelines
Python Code
-----------
-* Generally follow Python's `PEP8
- `__ style guidelines. We run the
+* Generally follow Python's :pep:`8` style guidelines. We run the
pep8 command to verify this during unittest runs.
* Break up logical blocks of related code with a newline. Specifically add a
@@ -46,8 +45,8 @@ Python Doc Strings
------------------
* Doc strings should generally follow
- `PEP257 `__ unless noted here.
-* Use `reStructuredText (resST) `__
+ :pep:`257` unless noted here.
+* Use `reStructuredText (reST) `__
annotations.
* Use three double quotes for doc strings (``"""``).
* Use a brief description on the same line as the triple quote.
diff --git a/docs/further.rst b/docs/further.rst
index 9f35338..c410f3b 100644
--- a/docs/further.rst
+++ b/docs/further.rst
@@ -5,9 +5,6 @@ Further Resources
`GNOME Developer Documentation `__
Tutorials for creating a GNOME application using PyGObject, GTK 4, and Libadwaita.
-`PyGObject Guide `__
- Many examples showing how to build an application using PyGObject and GTK 4.
-
`GNOME Python API documentation `__
Auto generated API documentation for many libraries accessible through
PyGObject.
diff --git a/docs/getting_started.rst b/docs/getting_started.rst
index 078ee56..7bd1433 100644
--- a/docs/getting_started.rst
+++ b/docs/getting_started.rst
@@ -43,17 +43,18 @@ and their dependencies. Follow the instructions for your platform below.
|windows-logo| :ref:`Windows ` |macosx-logo| :ref:`macOS ` |opensuse-logo| :ref:`openSUSE `
======================================================= ==================================================== ==========================================================
-After running the example application have a look at the `PyGObject Guide
-`__ for tutorials on how to create GTK apps and the `GNOME Python API docs
+After running the example application have a look at the :doc:`/tutorials/index` for an overview of how to create GTK apps and the `GNOME Python API docs
`__ for API documentation for all supported
-libraries. There are also typing stubs available here `PyGObject-stubs `_.
+libraries.
+
+For full IDE support (incl. autocomplete) you will also need typing stubs available here `PyGObject-stubs `_.
.. _windows-getting-started:
|windows-logo| Windows
----------------------
-#) Go to http://www.msys2.org/ and download the x86_64 installer
+#) Go to https://www.msys2.org/ and download the x86_64 installer
#) Follow the instructions on the page for setting up the basic environment
#) Run ``C:\msys64\ucrt64.exe`` - a terminal window should pop up
#) Execute ``pacman -Suy``
diff --git a/docs/guide/api/api.rst b/docs/guide/api/api.rst
index c5e019f..46a8629 100644
--- a/docs/guide/api/api.rst
+++ b/docs/guide/api/api.rst
@@ -1,3 +1,5 @@
+.. _guide-api:
+
================
GI Documentation
================
@@ -9,7 +11,7 @@ This is the API provided by the toplevel "gi" package.
:param str namespace: The namespace
:param str version: The version of the namespace which should be loaded
- :raises: :obj:`ValueError `
+ :raises: ..py:exception:: ValueError
Ensures the namespace gets loaded with the given version. If the namespace
was already loaded with a different version or a different version was
@@ -28,7 +30,7 @@ This is the API provided by the toplevel "gi" package.
:param symbol:
Optional symbol typename to ensure a converter exists.
:type symbol: :obj:`str` or :obj:`None`
- :raises: :obj:`ImportError `
+ :raises: ..py:exception:: ImportError
Ensure the given foreign marshaling module is available and loaded.
@@ -45,7 +47,7 @@ This is the API provided by the toplevel "gi" package.
.. function:: gi.check_version(version)
:param tuple version: A version tuple
- :raises: :obj:`ValueError `
+ :raises: ..py:exception:: ValueError
Compares the passed in version tuple with the gi version and does nothing
if gi version is the same or newer. Otherwise raises ValueError.
diff --git a/docs/guide/api/basic_types.rst b/docs/guide/api/basic_types.rst
index 6248f94..9520570 100644
--- a/docs/guide/api/basic_types.rst
+++ b/docs/guide/api/basic_types.rst
@@ -10,7 +10,7 @@ cases where it's appropriate it will use default Python types like :obj:`int`,
Number Types
------------
-All glib integer types get mapped to :obj:`int`, :obj:`long` and :obj:`float`.
+All glib integer types get mapped to :obj:`int` and :obj:`float`.
Since the glib integer types are always range limited, conversions from Python
int/long can fail with :class:`OverflowError`:
@@ -28,17 +28,7 @@ int/long can fail with :class:`OverflowError`:
Text Types
----------
-In case you use Python 2 then text is utf-8 encoded :obj:`str`, in case of
-Python 3 :obj:`str` is used.
-
-
-Platform String Types
----------------------
-
-* Windows + Python 2: utf-8 encoded :obj:`str`
-* Windows + Python 3: :obj:`str`
-* Unix + Python 2: :obj:`str`
-* Unix + Python 3: :obj:`str`
+Text types are mapped to :obj:`str`.
Other Types
diff --git a/docs/guide/api/error_handling.rst b/docs/guide/api/error_handling.rst
index e392cca..8f66a2e 100644
--- a/docs/guide/api/error_handling.rst
+++ b/docs/guide/api/error_handling.rst
@@ -1,3 +1,5 @@
+.. currentmodule:: gi.repository
+
==============
Error Handling
==============
diff --git a/docs/guide/api/flags_enums.rst b/docs/guide/api/flags_enums.rst
index 0a90735..6edc8ad 100644
--- a/docs/guide/api/flags_enums.rst
+++ b/docs/guide/api/flags_enums.rst
@@ -1,3 +1,5 @@
+.. currentmodule:: gi.repository
+
=============
Flags & Enums
=============
diff --git a/docs/guide/api/gobject.rst b/docs/guide/api/gobject.rst
index 63aa051..fda0e13 100644
--- a/docs/guide/api/gobject.rst
+++ b/docs/guide/api/gobject.rst
@@ -1,3 +1,5 @@
+.. currentmodule:: gi.repository
+
==============
GObject.Object
==============
diff --git a/docs/guide/api/properties.rst b/docs/guide/api/properties.rst
index 0241109..8c12369 100644
--- a/docs/guide/api/properties.rst
+++ b/docs/guide/api/properties.rst
@@ -1,3 +1,5 @@
+.. currentmodule:: gi.repository
+
==========
Properties
==========
diff --git a/docs/guide/api/signals.rst b/docs/guide/api/signals.rst
index 4353b21..4bdea98 100644
--- a/docs/guide/api/signals.rst
+++ b/docs/guide/api/signals.rst
@@ -1,3 +1,5 @@
+.. currentmodule:: gi.repository
+
=======
Signals
=======
diff --git a/docs/guide/api/weakrefs.rst b/docs/guide/api/weakrefs.rst
index 6ab9f28..c1831a3 100644
--- a/docs/guide/api/weakrefs.rst
+++ b/docs/guide/api/weakrefs.rst
@@ -8,7 +8,7 @@ The wrapper can get garbage collected and a new wrapper created again at a
later point.
If you want to get notified when the underlying GObject gets finalized use
-``GObject.Object.weak_ref``:
+:meth:`GObject.Object.weak_ref`:
.. method:: GObject.Object.weak_ref(callback, *user_data)
diff --git a/docs/guide/cairo_integration.rst b/docs/guide/cairo_integration.rst
index 84ea3f3..244a347 100644
--- a/docs/guide/cairo_integration.rst
+++ b/docs/guide/cairo_integration.rst
@@ -22,7 +22,7 @@ If your application requires the cairo integration you can use
print("No pycairo integration :(")
Note that PyGObject currently does not support `cairocffi
-`__, only pycairo.
+`__, only pycairo.
Demo
diff --git a/docs/guide/debug_profile.rst b/docs/guide/debug_profile.rst
index 6b43a80..d167ca5 100644
--- a/docs/guide/debug_profile.rst
+++ b/docs/guide/debug_profile.rst
@@ -69,7 +69,7 @@ SnakeViz - cProfile Based Visualization
Sysprof - System-wide Performance Profiler for Linux
----------------------------------------------------
-* http://sysprof.com/
+* https://www.sysprof.com/
::
diff --git a/docs/guide/deploy.rst b/docs/guide/deploy.rst
index 323ec72..2b4d696 100644
--- a/docs/guide/deploy.rst
+++ b/docs/guide/deploy.rst
@@ -16,9 +16,9 @@ SCons. Gramps uses distutils.
|macosx-logo| macOS
-------------------
-On OSX you can use `gtk-osx `__ which is
+On OSX you can use `gtk-osx `__ which is
based on jhbuild and then `gtk-mac-bundler
-`__ for packaging things up and
+`__ for packaging things up and
making libraries relocatable. With macOS bundles you generally have a startup
shell script which sets all the various env vars relative to the bundle,
similar to jhbuild.
@@ -37,11 +37,11 @@ Example Deployments
* `Quod Libet `__ provides a Windows
installer based on MSYS2 and NSIS3. On macOS, jhbuild is used for building,
gtk.mac-bundler for packing things up and `dmgbuild
- `__ for creating a dmg. distutis is
+ `__ for creating a dmg. distutis is
used for building/installing the application into the final environment.
Most of this is automated and scripts can be found in the git repo.
-* `MyPaint `__ provides a Windows installer based on
+* `MyPaint `__ provides a Windows installer based on
MSYS2 and Inno Setup. It uses SCons for building/installing the application.
* `Passphraser `__ uses the Hello World
@@ -50,5 +50,5 @@ Example Deployments
Other options
-------------
-* `PyInstaller `_ is a program that freezes (packages) Python programs into stand-alone executables, under Windows, Linux, Mac OS X, and more. PyInstaller's packager has built-in support for automatically including PyGObject dependencies with your application without requiring additional configuration.
+* `PyInstaller `_ is a program that freezes (packages) Python programs into stand-alone executables, under Windows, Linux, Mac OS X, and more. PyInstaller's packager has built-in support for automatically including PyGObject dependencies with your application without requiring additional configuration.
* `Hello World GTK `_ is a template build system for distributing Python-based GTK applications on Windows, macOS, and Linux. First, an application directory is assembled using PyInstaller. Then, a different program is used to package the resulting directory. For Windows, NSIS3 is used. For macOS, the built-in hdiutil is used. For Linux, AppImageKit is used.
diff --git a/docs/guide/flatpaking.rst b/docs/guide/flatpaking.rst
new file mode 100644
index 0000000..a99c057
--- /dev/null
+++ b/docs/guide/flatpaking.rst
@@ -0,0 +1,9 @@
+Flatpaking
+==========
+
+`Flatpak `_ is perfect for packaging applications for Linux.
+
+Flatpak comes with
+`great documentation `_ and a
+specific guide about using it to package Python applications can be found
+`here `_.
diff --git a/docs/guide/gtk_template.rst b/docs/guide/gtk_template.rst
index 2ba8324..8c0b239 100644
--- a/docs/guide/gtk_template.rst
+++ b/docs/guide/gtk_template.rst
@@ -1,9 +1,11 @@
+.. _guide-gtk-template:
+
============
Gtk.Template
============
A GtkWidget subclass can use a
-`GtkBuilder UI Definition `__
+`GtkBuilder UI Definition `__
XML document as a template to create child widgets and set its own
properties, without creating a GtkBuilder instance. This is implemented
for Python by PyGObject with Gtk.Template.
diff --git a/docs/guide/imports.rst b/docs/guide/imports.rst
new file mode 100644
index 0000000..c7d2135
--- /dev/null
+++ b/docs/guide/imports.rst
@@ -0,0 +1,44 @@
+Imports
+=======
+
+The toplevel ``gi`` package allows you to import the different libraries
+namespaces and ensure specific versions of them.
+
+The next code line will import the ``GTK`` and ``GLib`` libraries from the
+``gi.repository`` module. ``gi.repository`` holds the libraries bindings.
+
+.. code:: python
+
+ from gi.repository import Gtk, GLib
+
+
+If you want to ensure a specific version of a library you can use :func:`gi.require_version`.
+
+.. code:: python
+
+ import gi
+ gi.require_version('Gtk', '4.0')
+ gi.require_version('GLib', '2.0')
+ from gi.repository import Gtk, GLib
+
+
+To avoid `PEP8/E402 `_ you can
+use a try block.
+
+.. code:: python
+
+ import sys
+
+ import gi
+ try:
+ gi.require_version('Gtk', '4.0')
+ gi.require_version('Adw', '1')
+ from gi.repository import Adw, Gtk
+ except ImportError or ValueError as exc:
+ print('Error: Dependencies not met.', exc)
+ sys.exit(1)
+
+
+.. seealso::
+ For more detailed information of the methods provided by the ``gi`` module
+ checkout :ref:`guide-api`.
diff --git a/docs/guide/index.rst b/docs/guide/index.rst
index 758329d..848526e 100644
--- a/docs/guide/index.rst
+++ b/docs/guide/index.rst
@@ -7,6 +7,7 @@ User Guide
:titlesonly:
:maxdepth: 1
+ imports
api/index
cairo_integration
gtk_template
@@ -16,4 +17,5 @@ User Guide
testing
porting
sysdeps
+ flatpaking
faq
diff --git a/docs/guide/porting.rst b/docs/guide/porting.rst
index 0e51853..1fb92ea 100644
--- a/docs/guide/porting.rst
+++ b/docs/guide/porting.rst
@@ -28,6 +28,8 @@ to move to PyGObject and GStreamer 1.0 at the same time.
**pygobject 2** supports glib 2.0 and Python 2. The new bindings also support
glib 2.0 and Python 2/3.
+.. note::
+ Python 2 is no longer supported since PyGObject 3.38.0.
General Porting Tips
--------------------
@@ -58,7 +60,7 @@ to port your code to GTK 3.0 right away.
For some general advice regarding the migration from GTK 2.0 to 3.0 see the
`offical migration guide
-`__. If you
+`__. If you
need to know how a C symbol is exposed in Python have a look at the `symbol
mapping listing `__.
diff --git a/docs/index.rst b/docs/index.rst
index fc3111b..3477878 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -8,6 +8,7 @@
:maxdepth: 1
getting_started
+ tutorials/index
changelog
bugs_repo
guide/index
@@ -32,8 +33,8 @@ If you want to write a Python application for `GNOME
`__ or a Python GUI application using GTK, then
PyGObject is the way to go. To get started, check out the "`GNOME Developer Documentation
`__". For more
-information on specific libraries, check out the "`Python GI API
-Reference `__".
+information on specific libraries, check out the
+`GNOME Python API documentation `__.
.. code:: python
@@ -88,14 +89,14 @@ Who Is Using PyGObject?
-----------------------
* `Anaconda `__ - an installation program used by Fedora, RHEL and others
-* `Apostrophe `__ - a Markdown editor
-* `Blanket `__ - listen to different sounds
+* `Apostrophe `__ - a Markdown editor
+* `Blanket `__ - listen to different sounds
* `BleachBit `__ - delete unnecessary files from the system
* `Bottles `__ - run Windows software on Linux
* `Cambalache `__ - a user interface maker for GTK
* `D-Feet `__ - an easy to use D-Bus debugger
* `Deluge `__ - a BitTorrent client
-* `Dialect `__ - a translation app
+* `Dialect `__ - a translation app
* `Drawing `__ - a drawing application
* `Feeds `__ - an RSS/Atom feed reader
* `Gajim `__ - a fully-featured XMPP client
@@ -103,23 +104,23 @@ Who Is Using PyGObject?
* `Gaphor `__ - a simple modeling tool
* `Getting Things GNOME! `__ - a personal task organizer
* `Girens `__ - a Plex client for playing movies, TV shows and music from your Plex library
-* `GNOME Music `__ - a music player for GNOME
+* `GNOME Music `__ - a music player for GNOME
* `GNOME Tweaks `__ - a tool to customize advanced GNOME options
* `Gramps `__ - a genealogy program
* `Komikku `__ - a manga reader
* `Lollypop `__ - a modern music player
* `Lutris `__ - a video game manager
* `Meld `__ - a visual diff and merge tool
-* `Metadata Cleaner `__ - an application to view and clean metadata in files
-* `MyPaint `__ - a nimble, distraction-free, and easy tool for digital painters
+* `Metadata Cleaner `__ - an application to view and clean metadata in files
+* `MyPaint `__ - a nimble, distraction-free, and easy tool for digital painters
* `Nicotine+ `__ - a graphical client for the Soulseek peer-to-peer network
* `Orca `__ - a flexible and extensible screen reader
* `Paperwork `__ - a personal document manager
* `Pithos `__ - a Pandora Radio client
* `Pitivi `__ - a free and open source video editor
-* `Plots `__ - a graph plotting app
+* `Plots `__ - a graph plotting app
* `Quod Libet `__ - a music library manager / player
-* `Secrets `__ - a password manager
+* `Secrets `__ - a password manager
* `Setzer `__ - a LaTeX editor
* `Terminator `__ - The Robot Future of Terminals
* `Wike `__ - a Wikipedia reader
@@ -128,7 +129,7 @@ Who Is Using PyGObject?
The following applications or libraries use PyGObject for optional features,
such as plugins or as optional backends:
-* `beets `__ - a music library manager and MusicBrainz tagger
+* `beets `__ - a music library manager and MusicBrainz tagger
* `gedit `_- a GNOME text editor
-* `matplotlib `__ - a python 2D plotting library
+* `matplotlib `__ - a python 2D plotting library
* `Totem `__ - a video player for GNOME
diff --git a/docs/maintguide.rst b/docs/maintguide.rst
index a515184..f18a16d 100644
--- a/docs/maintguide.rst
+++ b/docs/maintguide.rst
@@ -5,7 +5,7 @@ Maintainer Guide
Making a Release
----------------
-#. Make sure the pyproject.toml has the right version number
+#. Make sure the `meson.build` file contains the right version number
#. Update the NEWS file
#. Build new version using ``python3 -m build --sdist``
#. Commit NEWS as ``"release 3.X.Y"`` and push
@@ -18,16 +18,16 @@ Making a Release
#. Install tarball:
``ssh user@master.gnome.org 'ftpadmin install pygobject-3.X.Y.tar.xz'``
#. In case the release happens on a stable branch copy the NEWS changes to
- the master branch
+ the main branch
Branching
---------
Each cycle after the feature freeze, we create a stable branch so development
-can continue in the master branch unaffected by the freezes.
+can continue in the main branch unaffected by the freezes.
#. Create the branch locally with: ``git checkout -b pygobject-3-2``
#. Push new branch: ``git push origin pygobject-3-2``
-#. In master, update pyproject.toml to what will be the next version number
+#. In main, update pyproject.toml to what will be the next version number
(3.3.0)
diff --git a/docs/packagingguide.rst b/docs/packagingguide.rst
index 58e20c7..3ca01c7 100644
--- a/docs/packagingguide.rst
+++ b/docs/packagingguide.rst
@@ -8,7 +8,7 @@ https://download.gnome.org/sources/pygobject
Existing Packages:
-* https://www.archlinux.org/packages/extra/x86_64/python-gobject
+* https://archlinux.org/packages/extra/x86_64/python-gobject
* https://tracker.debian.org/pkg/pygobject
* https://github.com/MSYS2/MINGW-packages/tree/master/mingw-w64-pygobject
diff --git a/docs/requirements.txt b/docs/requirements.txt
deleted file mode 100644
index 7cd890e..0000000
--- a/docs/requirements.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-sphinx>=7.0,<8.0
-furo>=2022,<2025
diff --git a/docs/tutorials/_static/custom.css b/docs/tutorials/_static/custom.css
new file mode 100644
index 0000000..21f0791
--- /dev/null
+++ b/docs/tutorials/_static/custom.css
@@ -0,0 +1,5 @@
+.toctree-wrapper .reference.external::after {
+ content: url("data:image/svg+xml;charset=utf-8,%3Csvg width='16' height='16' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' stroke-width='1.5' stroke='white' fill='none' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M0 0h24v24H0z' stroke='none'/%3E%3Cpath d='M11 7H6a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h9a2 2 0 0 0 2-2v-5M10 14 20 4M15 4h5v5'/%3E%3C/svg%3E");
+ margin: 0 .25rem;
+ vertical-align: middle;
+}
diff --git a/docs/tutorials/gobject.rst b/docs/tutorials/gobject.rst
new file mode 100644
index 0000000..a20b2a9
--- /dev/null
+++ b/docs/tutorials/gobject.rst
@@ -0,0 +1,22 @@
+GObject
+=======
+
+GObject is the foundation for object-oriented programming in the GNOME
+libraries.
+For example :class:`GObject.Object` is the base providing the common attributes
+and methods for all object types in GTK and the other libraries in this guide.
+
+The :class:`GObject.Object` class provides methods for object construction and
+destruction, property access methods, and signal support.
+
+This chapter will introduce some important aspects about the GObject
+implementation in Python.
+
+.. toctree::
+ :maxdepth: 3
+ :caption: Contents
+
+ gobject/basics
+ gobject/subclassing
+ gobject/interfaces
+ Weak References
diff --git a/docs/tutorials/gobject/basics.rst b/docs/tutorials/gobject/basics.rst
new file mode 100644
index 0000000..b9cc1d5
--- /dev/null
+++ b/docs/tutorials/gobject/basics.rst
@@ -0,0 +1,214 @@
+.. currentmodule:: gi.repository
+
+Basics
+======
+
+.. hint::
+ In this example, we will use GTK widgets to demonstrate GObject
+ capabilities.
+
+GObject Initialization
+----------------------
+
+GObjects are initialized like any other Python class.
+
+.. code:: python
+
+ label = Gtk.Label()
+
+.. _basics-properties:
+
+Properties
+----------
+
+GObject has a powerful properties system.
+
+Properties describe the configuration and state of a gobject. Each gobject has
+its own particular set of properties. For example, a GTK button has the property
+``label`` which contains the text of the label widget inside the button.
+
+You can specify the name and value of any number of properties as keyword
+arguments when creating an instance of a gobject. To create a label aligned to
+the right with the text "Hello World", use:
+
+.. code:: python
+
+ label = Gtk.Label(label='Hello World', halign=Gtk.Align.END)
+
+which is equivalent to
+
+.. code:: python
+
+ label = Gtk.Label()
+ label.set_label('Hello World')
+ label.set_halign(Gtk.Align.END)
+
+There are various ways of interacting with a gobject properties from Python, we
+already have seen the two first ways, these are setting them on initialization
+or using the getters and setters functions that the gobject might provide.
+
+Other option is to use :class:`GObject.Object` builtin methods :meth:`GObject.Object.get_property`
+and :meth:`GObject.Object.set_property`. Using these methods is more common when
+you have created a :class:`GObject.Object` subclass and you don't have getters
+and setters functions.
+
+.. code:: python
+
+ label = Gtk.Label()
+ label.set_property('label', 'Hello World')
+ label.set_property('halign', Gtk.Align.END)
+ print(label.get_property('label'))
+
+Instead of using getters and setters you can also get and set the gobject
+properties through the ``props`` property such as ``label.props.label = 'Hello World'``.
+This is equivalent to the more verbose methods that we saw before, and it's a
+more pythonic way of interacting with properties.
+
+To see which properties are available for a gobject you can ``dir`` the
+``props`` property:
+
+.. code:: python
+
+ widget = Gtk.Box()
+ print(dir(widget.props))
+
+This will print to the console the list of properties that a :class:`Gtk.Box`
+has.
+
+Property Bindings
+^^^^^^^^^^^^^^^^^
+
+GObject provides a practical way to bind properties of two different gobjects.
+This is done using the :meth:`GObject.Object.bind_property` method.
+
+The behavior of this binding can be controlled by passing a
+:class:`GObject.BindingFlags` of choice.
+:attr:`GObject.BindingFlags.DEFAULT` will update the target property every time
+the source property changes.
+:attr:`GObject.BindingFlags.BIDIRECTIONAL` creates a bidirectional binding; if
+either the property of the source or the property of the target changes, the
+other is updated.
+:attr:`GObject.BindingFlags.SYNC_CREATE` is similar to ``DEFAULT`` but it will
+also synchronize the values of the source and target properties when creating
+the binding.
+:attr:`GObject.BindingFlags.INVERT_BOOLEAN` works only for boolean properties
+and setting one property to ``True`` will result in the other being set to
+``False`` and vice versa (this flag cannot be used when passing custom
+transformation functions to :meth:`GObject.Object.bind_property`).
+
+.. code:: python
+
+ entry = Gtk.Entry()
+ label = Gtk.Label()
+
+ entry.bind_property('text', label, 'label', GObject.BindingFlags.DEFAULT)
+
+In this example **entry** is our source object and ``text`` the source property
+to bind.
+**label** is the target object and the namesake property ``label`` is the
+target property.
+Every time someone changes the ``text`` property of the entry the label
+``label`` will be updated as well with the same value.
+
+Property Bindings with Transformations
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Sometimes you may want to bind two properties that are incompatible, or you
+simply need to apply some transformation between these values.
+For these scenarios :meth:`GObject.Object.bind_property` also accepts custom
+transformation functions that serve to this purpose.
+
+The transformation functions take as first argument the :class:`GObject.Binding`
+instance for this binding and as second argument the property value depending
+on the direction of the transformation.
+For ``transform_to`` this will be the value of the source property and for
+``transform_from`` the value of the target property.
+Each function should return the value to be set in the other object's property,
+with the correct type.
+
+In this example we'll do an ``int`` to ``bool`` type conversion between two
+objects:
+
+.. code:: python
+
+ def transform_to(_binding, value):
+ return bool(value) # Return int converted to a bool
+
+ def transform_from(_binding, value):
+ return int(value) # Return bool converted to a int
+
+ source.bind_property(
+ 'int_prop',
+ target,
+ 'bool_prop',
+ GObject.BindingFlags.BIDIRECTIONAL,
+ transform_to,
+ transform_from
+ )
+
+.. _basics-signals:
+
+Signals
+-------
+
+GObject signals are a system for registering callbacks for specific events.
+
+A generic example is:
+
+.. code:: python
+
+ handler_id = gobject.connect('event', callback, data)
+
+Firstly, *gobject* is an instance of a gobject we created earlier. Next, the
+event we are interested in. Each gobject has its own particular events which
+can occur.
+This means that when the gobject emits the event, the signal is issued.
+Thirdly, the *callback* argument is the name of the callback function.
+It contains the code which runs when signals of the specified type are issued.
+Finally, the *data* argument includes any data which should be passed when the
+signal is issued. However, this argument is completely optional and can be left
+out if not required.
+
+The function returns a number that identifies this particular signal-callback
+pair.
+It is required to disconnect from a signal such that the callback function will
+not be called during any future or currently ongoing emissions of the signal it
+has been connected to:
+
+.. code:: python
+
+ gobject.disconnect(handler_id)
+
+When creating the callback function for a signal, the arguments it accepts will
+depend on the specific signal, but for a signal with no arguments it will look
+like this:
+
+.. code:: python
+
+ def on_event(gobject, data):
+ ...
+
+ my_object.connect('event', on_event, data)
+
+Where ``gobject`` is the object that triggered the signal and ``data`` is the
+additional data that we previously passed to the :meth:`GObject.Object.connect`
+method.
+If the signal had arguments, they will come before the optional data argument.
+
+The ``notify`` signal
+^^^^^^^^^^^^^^^^^^^^^
+
+When any of a GObject's properties change, it will emit the ``notify`` signal.
+This is a "detailed" signal, meaning that you can listen to a subset of the
+signal, in this case a specific property.
+For example, you can connect to the signal in the form of
+``notify::property-name``:
+
+.. code:: python
+
+ def callback(label, _pspec):
+ print(f'The label prop changed to {label.props.label}')
+
+ label = Gtk.Label()
+ label.connect('notify::label', callback)
+
diff --git a/docs/tutorials/gobject/examples/listmodel.py b/docs/tutorials/gobject/examples/listmodel.py
new file mode 100644
index 0000000..6b5597d
--- /dev/null
+++ b/docs/tutorials/gobject/examples/listmodel.py
@@ -0,0 +1,62 @@
+from gi.repository import Gio, GObject
+
+
+class Person(GObject.Object):
+ __gtype_name__ = 'Person'
+
+ name = GObject.Property(type=str)
+
+ def __init__(self, name):
+ super().__init__()
+
+ self.name = name
+
+
+class PersonsModel(GObject.GObject, Gio.ListModel):
+ __gtype_name__ = 'PersonsModel'
+
+ def __init__(self):
+ super().__init__()
+
+ # Private list to store the persons
+ self._persons = []
+
+ '''
+ Interface Methods
+ '''
+
+ def do_get_item(self, position):
+ return self._persons[position]
+
+ def do_get_item_type(self):
+ return Person
+
+ def do_get_n_items(self):
+ return len(self._persons)
+
+ '''
+ Our Helper Methods
+ '''
+
+ def add(self, person):
+ self._persons.append(person)
+
+ '''
+ We must call Gio.ListModel.items_changed() every time we change the list.
+
+ It's a helper to emit the "items-changed" signal, so consumer can know
+ that the list changed at some point. We pass the position of the change,
+ the number of removed items and the number of added items.
+ '''
+ self.items_changed(len(self._persons) - 1, 0, 1)
+
+ def remove(self, position):
+ del self._persons[position]
+ self.items_changed(position, 1, 0)
+
+ def get_index_by_name(self, name):
+ for i, person in enumerate(self._persons):
+ if person.name == name:
+ return i
+
+ return None
diff --git a/docs/tutorials/gobject/interfaces.rst b/docs/tutorials/gobject/interfaces.rst
new file mode 100644
index 0000000..44c487c
--- /dev/null
+++ b/docs/tutorials/gobject/interfaces.rst
@@ -0,0 +1,44 @@
+.. currentmodule:: gi.repository
+
+Interfaces
+==========
+GObject interfaces are a way of ensuring that objects passed to C code have the
+right capabilities.
+
+When a GObject implements an interface it should implement an expected set of
+methods, properties and signals. In the Python sense, an interface is another
+class that is inherited.
+
+For example in GTK, :class:`Gtk.Image` supports various sources for the image
+that it will display.
+Some of these sources can be a :class:`Gio.Icon` or a :class:`Gdk.Paintable`,
+both are actually interfaces so you don't pass a direct instance of these,
+instead you should use some of the gobjects that implement the interface.
+For :class:`Gio.Icon` those can be :class:`Gio.ThemedIcon` that represents an
+icon from the icon theme, or :class:`Gio.FileIcon` that represents an icon
+created from an image file.
+
+Another important interface of reference is :class:`Gio.ListModel`.
+It represents a mutable list of :class:`GObject.Objects `.
+If you want to implement :class:`Gio.ListModel` you must implement three methods,
+these are :meth:`Gio.ListModel.get_item_type`, :meth:`Gio.ListModel.get_n_items`
+and :meth:`Gio.ListModel.get_item`.
+The interfaces methods that you should implement are exposed as
+:ref:`virtual methods `.
+With these methods any consumer can iterate the list and use the objects for any
+purpose.
+
+.. tip::
+ A generic implementation of :class:`Gio.ListModel` is :class:`Gio.ListStore`.
+ It allows you to set the :class:`GObject.Object` type that it will store and
+ provides methods to append, insert, sort, find and remove gobjects.
+
+Example
+-------
+
+In this examples we'll be implementing a :class:`Gio.ListModel` in Python.
+It will store a custom :class:`GObject.Object` and provide some helper methods
+for it.
+
+.. literalinclude:: examples/listmodel.py
+ :linenos:
diff --git a/docs/tutorials/gobject/subclassing.rst b/docs/tutorials/gobject/subclassing.rst
new file mode 100644
index 0000000..b7db37e
--- /dev/null
+++ b/docs/tutorials/gobject/subclassing.rst
@@ -0,0 +1,344 @@
+.. currentmodule:: gi.repository
+
+Subclassing
+===========
+
+Before entering in detail, you should know some important points about GObject
+subclassing:
+
+1. It is possible to subclass a :class:`GObject.Object`. Subclassing creates a
+ new :class:`GObject.GType` which is connected to the new Python type.
+ This means you can use it with API which takes :class:`GObject.GType`.
+
+2. :class:`GObject.Object` only supports single inheritance, this means you can
+ only subclass one :class:`GObject.Object`, but multiple Python classes.
+
+3. The Python wrapper instance for a GObject.Object is always the same. For the
+ same C instance you will always get the same Python instance.
+
+
+Inherit from GObject.GObject
+----------------------------
+A native GObject is accessible via :class:`GObject.Object`.
+It is rarely instantiated directly, we generally use an inherited classes.
+A :class:`Gtk.Widget` is an inherited class of a :class:`GObject.Object`.
+It may be interesting to make an inherited class to create a new widget, like a
+settings dialog.
+
+To inherit from :class:`GObject.Object`, you must call `super().__init__`
+in your constructor to initialize the gobjects you are inheriting, like in the
+example below:
+
+.. code:: python
+
+ from gi.repository import GObject
+
+ class MyObject(GObject.Object):
+
+ def __init__(self):
+ super().__init__(self)
+
+You can also pass arguments to `super().__init__`, for example to change
+some property of your parent gobject:
+
+.. code:: python
+
+ class MyWindow(Gtk.Window):
+
+ def __init__(self):
+ super().__init__(self, title='Custom title')
+
+
+In case you want to specify the GType name we have to provide a
+``__gtype_name__``:
+
+.. code:: python
+
+ class MyWindow(Gtk.Window):
+ __gtype_name__ = 'MyWindow'
+
+ def __init__(self):
+ super().__init__(self)
+
+
+Properties
+----------
+One of the nice features of GObject is its generic get/set mechanism for object
+properties.
+Any class that inherits from GObject.Object can define new properties.
+Each property has a type that never changes (e.g. ``str``, ``float``,
+``int``...).
+
+Create new properties
+^^^^^^^^^^^^^^^^^^^^^
+
+A property is defined with a name and a type. Even if Python itself is
+dynamically typed, you can't change the type of a property once it is defined. A
+property can be created using :func:`GObject.Property`.
+
+.. code:: python
+
+ from gi.repository import GObject
+
+ class MyObject(GObject.Object):
+
+ foo = GObject.Property(type=str, default='bar')
+ property_float = GObject.Property(type=float)
+
+ def __init__(self):
+ super().__init__(self)
+
+Properties can also be read-only, if you want some properties to be readable but
+not writable. To do so, you can add some flags to the property definition, to
+control read/write access.
+Flags are :attr:`GObject.ParamFlags.READABLE` (only read access for external
+code),
+:attr:`GObject.ParamFlags.WRITABLE` (only write access),
+:attr:`GObject.ParamFlags.READWRITE` (public):
+
+.. there is also construct things, but they
+.. doesn't seem to be functional in Python
+
+.. code:: python
+
+ foo = GObject.Property(type=str, flags=GObject.ParamFlags.READABLE) # not writable
+ bar = GObject.Property(type=str, flags=GObject.ParamFlags.WRITABLE) # not readable
+
+
+You can also define new read-only properties with a new method decorated with
+:func:`GObject.Property`:
+
+.. code:: python
+
+ from gi.repository import GObject
+
+ class MyObject(GObject.Object):
+
+ def __init__(self):
+ super().__init__(self)
+
+ @GObject.Property
+ def readonly(self):
+ return 'This is read-only.'
+
+You can get this property using:
+
+.. code-block:: python
+
+ my_object = MyObject()
+ print(my_object.readonly)
+ print(my_object.get_property('readonly'))
+
+The API of :func:`GObject.Property` is similar to the builtin
+:py:class:`property`.
+You can create property setters in a way similar to Python property:
+
+.. code-block:: python
+
+ class AnotherObject(GObject.Object):
+ value = 0
+
+ @GObject.Property
+ def prop(self):
+ """Read only property."""
+ return 1
+
+ @GObject.Property(type=int)
+ def prop_int(self):
+ """Read-write integer property."""
+ return self.value
+
+ @prop_int.setter
+ def prop_int(self, value):
+ self.value = value
+
+There is also a way to define minimum and maximum values for numbers:
+
+.. code-block:: python
+
+ class AnotherObject(GObject.Object):
+ value = 0
+
+ @GObject.Property(type=int, minimum=0, maximum=100)
+ def prop_int(self):
+ """Integer property with min-max.'"""
+ return self.value
+
+ @prop_int.setter
+ def prop_int(self, value):
+ self.value = value
+
+
+ my_object = AnotherObject()
+ my_object.prop_int = 200 # This will fail
+
+Alternatively you can use the more verbose `__gproperties__` class
+attribute to define properties:
+
+.. code:: python
+
+ from gi.repository import GObject
+
+ class MyObject(GObject.Object):
+
+ __gproperties__ = {
+ 'int-prop': (
+ int, # type
+ 'integer prop', # nick
+ 'A property that contains an integer', # blurb
+ 1, # min
+ 5, # max
+ 2, # default
+ GObject.ParamFlags.READWRITE # flags
+ ),
+ }
+
+ def __init__(self):
+ super().__init__(self)
+ self.int_prop = 2
+
+ def do_get_property(self, prop):
+ if prop.name == 'int-prop':
+ return self.int_prop
+ else:
+ raise AttributeError('unknown property %s' % prop.name)
+
+ def do_set_property(self, prop, value):
+ if prop.name == 'int-prop':
+ self.int_prop = value
+ else:
+ raise AttributeError('unknown property %s' % prop.name)
+
+
+For this approach properties must be defined in the ``__gproperties__`` class
+attribute, a dictionary, and handled in :meth:`GObject.Object.do_get_property`
+and :meth:`GObject.Object.do_set_property`
+:ref:`virtual methods `.
+
+.. hint::
+ Changes to custom properties are also signaled by the ``notify`` detailed
+ signal. But remember that it will normalize your property name to hyphens
+ instead of underscores, so you will write ``notify::prop-int`` and not
+ ``notify::prop_int``.
+
+Signals
+-------
+Each signal is registered in the type system together with the type on which it
+can be emitted: users of the type are said to connect to the signal on a given
+type instance when they register a function to be invoked upon the signal
+emission. Users can also emit the signal by themselves or stop the emission of
+the signal from within one of the functions connected to the signal.
+
+Create new signals
+^^^^^^^^^^^^^^^^^^
+
+New signals can be created by using the :func:`GObject.Signal` decorator.
+The decorated methods are the object method handlers, these will be called when
+the signal is emitted.
+
+The time at which the method handlers are invoked depends on the signal flags.
+:attr:`GObject.SignalFlags.RUN_FIRST` indicates that this signal will invoke the
+object method handler in the first emission stage.
+Alternatives are :attr:`GObject.SignalFlags.RUN_LAST` (the method handler will be
+invoked in the third emission stage) and :attr:`GObject.SignalFlags.RUN_CLEANUP`
+(invoke the method handler in the last emission stage).
+
+Signals can also have arguments, the number and type of each argument is defined
+as a tuple of types.
+
+Signals can be emitted using :meth:`GObject.Object.emit`.
+
+.. code:: python
+
+ from gi.repository import GObject
+
+ class MyObject(GObject.Object):
+
+ def __init__(self):
+ super().__init__(self)
+
+ @GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=(int,))
+ def arg_signal(self, number):
+ """Called every time the signal is emitted"""
+ print('number:', number)
+
+ @GObject.Signal
+ def noarg_signal(self):
+ """Called every time the signal is emitted"""
+ print('noarg_signal')
+
+
+ my_object = MyObject()
+
+ def signal_callback(object_, number):
+ """Called every time the signal is emitted until disconnection"""
+ print(object_, number)
+
+ my_object.connect('arg_signal', signal_callback)
+ my_object.emit('arg_signal', 100) # emit the signal "arg_signal", with the
+ # argument 100
+
+ my_object.emit('noarg_signal')
+
+
+Alternatively you can use the more verbose `__gsignals__` class
+attribute to define signals.
+When a new signal is created, a method handler can also be defined in the form
+of ``do_signal_name``, it will be called each time the signal is emitted.
+
+.. code:: python
+
+ class MyObject(GObject.Object):
+ __gsignals__ = {
+ 'my_signal': (
+ GObject.SignalFlags.RUN_FIRST, # flag
+ None, # return type
+ (int,) # arguments
+ )
+ }
+
+ def do_my_signal(self, arg):
+ print("method handler for `my_signal' called with argument", arg)
+
+.. _virtual-methods:
+
+Virtual Methods
+---------------
+
+GObject and its based libraries usually have gobjects that expose virtual
+methods. These methods serve to override functionality of the base gobject or
+to run code on a specific scenario.
+In that case you should call the base gobject virtual method to preserve its
+original behavior.
+
+In PyGObject these methods are prefixed with ``do_``. Some examples are
+:meth:`GObject.Object.do_get_property` or :meth:`Gio.Application.do_activate`.
+
+.. important::
+ The Python :py:class:`super` class only works for the immediate parent.
+ If you want to chain some virtual method from a object that is more
+ up in the hierarchy of the one you are subclassing you must call the method
+ directly from the object class:
+ ``SomeOject.method(self, args)``.
+
+.. code:: python
+
+ class SomeOject(OtherObject):
+ ...
+
+ class MyObject(SomeOject):
+
+ def __init__(self):
+ super().__init__(self)
+
+ def do_virtual_method(self):
+ # Call the original method to keep its original behavior
+ super().do_virtual_method(self)
+
+ # Run some extra code
+ ...
+
+ """This is a virtual method from SomeOject parent"""
+ def do_other(self):
+ OtherObject.do_other(self) # We can't use super()
+ ...
diff --git a/docs/tutorials/gtk3.rst b/docs/tutorials/gtk3.rst
new file mode 100644
index 0000000..f49df23
--- /dev/null
+++ b/docs/tutorials/gtk3.rst
@@ -0,0 +1,8 @@
+GTK3
+====
+
+You can find help about using Python with GTK3 in the following resources.
+
+* `The Python GTK+ 3 Tutorial `_
+
+* `PyGObject API Reference `_
diff --git a/docs/tutorials/gtk4.rst b/docs/tutorials/gtk4.rst
new file mode 100644
index 0000000..be16a1a
--- /dev/null
+++ b/docs/tutorials/gtk4.rst
@@ -0,0 +1,21 @@
+GTK4
+====
+
+GTK is a library for creating graphical user interfaces.
+The main objects of GTK are "widgets" which are components such as buttons, text
+input, or windows.
+
+.. toctree::
+ :maxdepth: 2
+ :caption: Contents
+
+ gtk4/introduction
+ gtk4/basics
+ gtk4/application
+ gtk4/layout-widgets
+ gtk4/controls
+ gtk4/display-widgets
+ gtk4/popovers
+ gtk4/textview
+ gtk4/clipboard
+ gtk4/drag-and-drop
diff --git a/docs/tutorials/gtk4/application.rst b/docs/tutorials/gtk4/application.rst
new file mode 100644
index 0000000..6b279bf
--- /dev/null
+++ b/docs/tutorials/gtk4/application.rst
@@ -0,0 +1,76 @@
+.. currentmodule:: gi.repository
+
+Application
+===========
+
+.. seealso::
+
+ For more detailed information about ``Gtk.Application`` checkout the
+ :devdocs:`Using GtkApplication ` tutorial.
+
+
+:class:`Gtk.Application` is the foundation for creating GTK apps. It encompasses
+many repetitive tasks that a modern application needs such as handling multiple
+instances, D-Bus activation, opening files, command line parsing,
+startup/shutdown, menu management, window management, and more.
+
+In this example we will be also using :class:`Gtk.ApplicationWindow`, it
+provides some extra features over regular :class:`Gtk.Window` for main
+application windows.
+
+Actions
+-------
+
+:class:`Gio.Action` is a way to expose any single task your application or widget
+does by a name. These actions can be disabled/enabled at runtime and they can
+either be activated or have a state changed (if they contain state).
+
+The reason to use actions is to separate out the logic from the UI. For example
+this allows using a menubar on OSX and a gear menu on GNOME both simply
+referencing the name of an action. The main implementation of this you will
+be using is :class:`Gio.SimpleAction` which will be demonstrated later.
+
+Many classes such as :class:`Gio.MenuItem` and :class:`Gtk.Actionable` interface
+implementations like :class:`Gtk.Button` support properties to set an action
+name.
+
+These actions can be grouped together into a :class:`Gio.ActionGroup` and
+when these groups are added to a widget with :meth:`Gtk.Widget.insert_action_group()`
+they will gain a prefix. Such as "win" when added to a :class:`Gtk.ApplicationWindow`.
+You will use the full action name when referencing it such as "app.about" but when
+you create the action it will just be "about" until added to the application.
+
+You can also very easily make keybindings for actions by setting the `accel`
+property in the :class:`Gio.Menu` file or by using :meth:`Gtk.Application.set_accels_for_action()`.
+
+Menus
+-----
+
+Your menus should be defined in XML using :class:`Gio.Menu` and would reference
+the previously mentioned actions you defined. :class:`Gtk.Application` allows you
+to set a menu via :meth:`Gtk.Application.set_menubar()`. If you make use of :class:`Gio.Resource`
+this can automatically load the menu, otherwise you can set them manually.
+A detailed example is shown below.
+
+Command Line
+------------
+
+When creating your application it takes a flag property of :class:`Gio.ApplicationFlags`.
+Using this you can let it handle everything itself or have more custom behavior.
+
+You can use ``HANDLES_COMMAND_LINE`` to allow custom behavior in :meth:`Gio.Application.do_command_line()`.
+In combination with :meth:`Gio.Application.add_main_option()` to add custom options.
+
+Using ``HANDLES_OPEN`` will do the work of simply taking file arguments for you and
+let you handle it in :meth:`Gio.Application.do_open()`.
+
+If your application is already open these will all be sent to the existing instance
+unless you use ``NON_UNIQUE`` to allow multiple instances.
+
+Example
+-------
+
+.. image:: images/application.png
+
+.. literalinclude:: examples/application.py
+ :linenos:
diff --git a/docs/tutorials/gtk4/basics.rst b/docs/tutorials/gtk4/basics.rst
new file mode 100644
index 0000000..19e35b1
--- /dev/null
+++ b/docs/tutorials/gtk4/basics.rst
@@ -0,0 +1,36 @@
+.. currentmodule:: gi.repository
+
+GTK4 Basics
+===========
+
+Main loop and Signals
+---------------------
+Like most GUI toolkits, GTK uses an event-driven programming model.
+When the user is doing nothing, GTK+ sits in the main loop and waits for input.
+If the user performs some action - say, a mouse click - then the main loop
+"wakes up" and delivers an event to GTK.
+
+When widgets receive an event, they frequently emit one or more signals.
+Signals notify your program that "something interesting happened" by invoking
+functions you've connected to the signal. Such functions are commonly known
+as *callbacks*.
+When your callbacks are invoked, you would typically take some action - for
+example, when an Open button is clicked you might display a file chooser
+dialog. After a callback finishes, GTK will return to the main loop and await
+more user input.
+
+:class:`Gtk.Application` will run the main loop for you, so you don't need to
+worry about it.
+
+A :class:`Gtk.Widget` it's also a :class:`GObject.Object`, so to know how to
+interact with these signals you must read the
+:ref:`GObject Basics `.
+
+.. seealso:: `Library initialization and main loop`_ in GTK documentation.
+
+Properties
+----------
+Read: :ref:`GObject Basics: Properties `.
+
+
+.. _Library initialization and main loop: https://docs.gtk.org/gtk4/initialization.html
diff --git a/docs/tutorials/gtk4/clipboard.rst b/docs/tutorials/gtk4/clipboard.rst
new file mode 100644
index 0000000..5dc3037
--- /dev/null
+++ b/docs/tutorials/gtk4/clipboard.rst
@@ -0,0 +1,38 @@
+.. currentmodule:: gi.repository
+
+Clipboard
+=========
+
+:class:`Gdk.Clipboard` provides a storage area for a variety of data, including
+text and images. Using a clipboard allows this data to be shared between
+applications through actions such as copying, cutting, and pasting.
+
+There are multiple clipboard selections for different purposes.
+In most circumstances, the selection named ``CLIPBOARD`` is used for everyday
+copying and pasting. ``PRIMARY`` is another common selection which stores text
+selected by the user with the cursor.
+
+:class:`Gdk.Display` will allow us to access these different clipboards.
+You can get the default display with :meth:`Gdk.Display.get_default`, then get
+the clipboard that you want; :meth:`Gdk.Display.get_clipboard` for ``CLIPBOARD``
+and :meth:`Gdk.Display.get_primary_clipboard` for ``PRIMARY``.
+
+You can set any simple value like text with :meth:`Gdk.Clipboard.set`.
+For more complex data you must use the :meth:`Gdk.Clipboard.set_content` method
+were you have to pass a :class:`Gdk.ContentProvider`.
+A content provider is usually created using
+:meth:`Gdk.ContentProvider.new_for_value` where you only pass the value.
+
+To read the clipboard values :class:`Gdk.Clipboard` provides three async methods.
+For textual or image data use :meth:`Gdk.Clipboard.read_text_async` or
+:meth:`Gdk.Clipboard.read_texture_async`.
+For other data use :meth:`Gdk.Clipboard.read_value_async`.
+
+
+Example
+-------
+
+.. image:: images/clipboard.png
+
+.. literalinclude:: examples/clipboard.py
+ :linenos:
diff --git a/docs/tutorials/gtk4/controls.rst b/docs/tutorials/gtk4/controls.rst
new file mode 100644
index 0000000..8220685
--- /dev/null
+++ b/docs/tutorials/gtk4/controls.rst
@@ -0,0 +1,17 @@
+Controls
+========
+
+Learn how to use the most basic interactive UI elements from GTK, such as
+entries, buttons and switches.
+
+.. toctree::
+ :maxdepth: 1
+ :caption: Contents
+
+ controls/entries
+ controls/buttons
+ controls/check-radio-buttons
+ controls/spinbutton
+ controls/switch
+ controls/dropdown
+ controls/scale
diff --git a/docs/tutorials/gtk4/controls/buttons.rst b/docs/tutorials/gtk4/controls/buttons.rst
new file mode 100644
index 0000000..41590a0
--- /dev/null
+++ b/docs/tutorials/gtk4/controls/buttons.rst
@@ -0,0 +1,66 @@
+.. currentmodule:: gi.repository
+
+Buttons
+=======
+
+Button
+------
+The Button widget is another commonly used widget. It is generally used to
+attach a function that is called when the button is pressed.
+
+The :class:`Gtk.Button` widget can hold any valid child widget. That is it can
+hold most any other standard :class:`Gtk.Widget`.
+The most commonly used child is the :class:`Gtk.Label`.
+Normally you will use :attr:`Gtk.Button.props.label` to set the button label, or
+:attr:`Gtk.Button.props.icon_name` if you want an icon instead.
+
+Usually, you want to connect to the button's ``clicked`` signal which is emitted
+when the button has been pressed and released.
+
+Example
+^^^^^^^
+
+.. image:: images/button.png
+
+.. literalinclude:: examples/button.py
+ :linenos:
+
+
+ToggleButton
+------------
+
+A :class:`Gtk.ToggleButton` is very similar to a normal :class:`Gtk.Button`,
+but when clicked they remain activated, or pressed, until clicked again.
+When the state of the button is changed, the `toggled` signal is emitted.
+
+To retrieve the state of the :class:`Gtk.ToggleButton`, you can use
+:attr:`Gtk.ToggleButton.props.active`. This returns ``True`` if the button
+is "down". You can also set the toggle button's state, with
+:attr:`Gtk.ToggleButton.props.active`. Note that, if you do this, and the state
+actually changes, it causes the "toggled" signal to be emitted.
+
+Example
+^^^^^^^
+
+.. image:: images/togglebutton.png
+
+.. literalinclude:: examples/togglebutton.py
+ :linenos:
+
+
+LinkButton
+----------
+A :class:`Gtk.LinkButton` is a :class:`Gtk.Button` with a hyperlink, similar
+to the one used by web browsers, which triggers an action when clicked. It is
+useful to show quick links to resources.
+
+The URI bound to a :class:`Gtk.LinkButton` can be set specifically using
+:attr:`Gtk.LinkButton.props.uri`.
+
+Example
+^^^^^^^
+
+.. image:: images/linkbutton.png
+
+.. literalinclude:: examples/linkbutton.py
+ :linenos:
diff --git a/docs/tutorials/gtk4/controls/check-radio-buttons.rst b/docs/tutorials/gtk4/controls/check-radio-buttons.rst
new file mode 100644
index 0000000..1b8f9ff
--- /dev/null
+++ b/docs/tutorials/gtk4/controls/check-radio-buttons.rst
@@ -0,0 +1,24 @@
+Check & Radio Buttons
+=====================
+A :class:`Gtk.CheckButton` places a label next to an indicator.
+Check or Radio buttons are created through :class:`Gtk.CheckButton`, you create
+one or another depending grouping.
+
+:class:`Gtk.CheckButton` can be grouped together, to form mutually exclusive
+groups so only one of the buttons can be toggled at a time, this create what we
+usually refer to as a radio button.
+
+In addition to "on" and "off", :class:`Gtk.CheckButton` can be an "in between"
+state that is neither on nor off. This can be used e.g. when the user has
+selected a range of elements (such as some text or spreadsheet cells) that are
+affected by a check button, and the current values in that range are
+inconsistent.
+For this purpose use :attr:`Gtk.CheckButton.props.inconsistent`.
+
+Example
+-------
+
+.. image:: images/check_radio_buttons.png
+
+.. literalinclude:: examples/check_radio_buttons.py
+ :linenos:
diff --git a/docs/tutorials/gtk4/controls/dropdown.rst b/docs/tutorials/gtk4/controls/dropdown.rst
new file mode 100644
index 0000000..f551130
--- /dev/null
+++ b/docs/tutorials/gtk4/controls/dropdown.rst
@@ -0,0 +1,43 @@
+.. currentmodule:: gi.repository
+
+DropDown
+========
+:class:`Gtk.DropDown` allows the user to choose an item from a list of options.
+They are preferable to having many radio buttons on screen as they take up less
+room.
+
+To populate its options :class:`Gtk.DropDown` uses a :class:`Gio.ListModel`.
+:class:`Gio.ListModel` it's an interface that represents a mutable list of
+:class:`GObject.Objects `. For text-only uses cases GTK provides
+:class:`Gtk.StringList`, a list model that wraps an array of strings wrapped on
+:class:`Gtk.StringObject` and :class:`Gtk.DropDown` knows how to use it.
+
+:class:`Gtk.DropDown` can optionally allow search in the popup, which is useful
+if the list of options is long. To enable the search entry, use
+:attr:`Gtk.DropDown.props.enable_search`.
+
+.. attention::
+ Currently :class:`Gtk.DropDown` search only works fine in Python if you are
+ using a :class:`Gtk.StringList`.
+ If you use custom list models with custom gobjects you must provide a
+ :class:`Gtk.Expression` through :attr:`Gtk.DropDown.props.expression` so
+ :class:`Gtk.DropDown` can know how to filter the gobjects.
+ The problem is :class:`Gtk.Expression` is broken in PyGObject for now
+ (`see bug report `_).
+ So search won´t work for at all.
+
+:class:`Gtk.DropDown` stores the selected item from the list model in
+:attr:`Gtk.DropDown.props.selected_item`, and the position of that item on
+:attr:`Gtk.DropDown.props.selected`. To know when the selection has changed just
+connect to ``notify::selected-item`` or ``notify::selected``.
+
+
+Example
+^^^^^^^
+
+We are creating a simple :class:`Gtk.DropDown` using :class:`Gtk.StringList`.
+
+.. image:: images/dropdown.png
+
+.. literalinclude:: examples/dropdown.py
+ :linenos:
diff --git a/docs/tutorials/gtk4/controls/entries.rst b/docs/tutorials/gtk4/controls/entries.rst
new file mode 100644
index 0000000..9f9b06e
--- /dev/null
+++ b/docs/tutorials/gtk4/controls/entries.rst
@@ -0,0 +1,84 @@
+.. currentmodule:: gi.repository
+
+Entries
+=======
+
+Entries allows the user to enter text.
+GTK provides a few entry widgets for different use cases.
+Those are the generic :class:`Gtk.Entry`, :class:`Gtk.PasswordEntry` and
+:class:`Gtk.SearchEntry`.
+Although none of these widgets derive from each other, they implement the
+:class:`Gtk.Editable` :doc:`interface `, so they share some
+properties and methods.
+You can change and get the contents with the :attr:`Gtk.Editable.props.text`
+property.
+You can also limit the number of characters the entry can take with
+:attr:`Gtk.Editable.props.max_width_chars`.
+
+Occasionally you might want to make an Entry widget read-only. This can be done
+by setting :attr:`Gtk.Editable.props.editable` to ``False``.
+
+Generic Entry
+-------------
+
+:class:`Gtk.Entry` is the standard entry.
+
+:class:`Gtk.Entry` can be set to show a invisible character using
+:attr:`Gtk.Entry.props.visibility` and :attr:`Gtk.Entry.props.invisible_char`,
+this is useful to hide the text of the entry when it is used for example to
+retrieve passwords.
+Though :ref:`password-entry` exist for this specific use
+case.
+
+:class:`Gtk.Entry` has the ability to display progress or activity information
+behind the text. This is similar to :class:`Gtk.ProgressBar` widget and is
+commonly found in web browsers to indicate how much of a page download has been
+completed. To make an entry display such information, use
+:attr:`Gtk.Entry.props.progress_fraction`,
+:attr:`Gtk.Entry.props.progress_pulse_step`, or :meth:`Gtk.Entry.progress_pulse`.
+
+Additionally, a :class:`Gtk.Entry` can show icons at either side of the entry.
+These icons can be activatable by clicking, can be set up as drag source and can
+have tooltips.
+To add an icon, use :meth:`Gtk.Entry.set_icon_from_icon_name` or one of the
+various other properties and methods that set an icon from an icon name,
+:class:`Gio.Icon`, or a :class:`Gdk.Paintable`.
+To set a tooltip on an icon, use :meth:`Gtk.Entry.set_icon_tooltip_text` or the
+corresponding function for markup.
+
+Entries can have a placeholder text,
+just use :attr:`Gtk.Entry.props.placeholder_text`.
+
+.. _password-entry:
+
+Password Entry
+--------------
+
+:class:`Gtk.PasswordEntry` brings some features for password handing.
+It can show a button to toggle the visibility of the text if you set
+:attr:`Gtk.PasswordEntry.props.show_peek_icon` to ``True``.
+
+Search Entry
+------------
+
+:class:`Gtk.SearchEntry` is an entry specially designed for use as a search
+entry.
+:class:`Gtk.SearchEntry` allows you to implement the popular "type to search"
+feature.
+You can use :meth:`Gtk.SearchEntry.set_key_capture_widget` to set the parent
+widget that will redirect its key events to the entry.
+
+:class:`Gtk.SearchEntry` has the
+:func:`search-changed ` signal, it
+differs from :class:`Gtk.Editable`'s :func:`changed `
+in the sense that it gets emitted after a short delay that you can configure
+with :attr:`Gtk.SearchEntry.props.search_delay`.
+This way you can get reactive searching without over loading your backend.
+
+Example
+-------
+
+.. image:: images/entries.png
+
+.. literalinclude:: examples/entries.py
+ :linenos:
diff --git a/docs/tutorials/gtk4/controls/examples/button.py b/docs/tutorials/gtk4/controls/examples/button.py
new file mode 100644
index 0000000..5bb820e
--- /dev/null
+++ b/docs/tutorials/gtk4/controls/examples/button.py
@@ -0,0 +1,45 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk
+
+
+class ButtonWindow(Gtk.ApplicationWindow):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, title='Button Demo')
+
+ hbox = Gtk.Box(spacing=6)
+ self.set_child(hbox)
+
+ button = Gtk.Button.new_with_label('Click Me')
+ button.connect('clicked', self.on_click_me_clicked)
+ hbox.append(button)
+
+ button = Gtk.Button.new_with_mnemonic('_Open')
+ button.connect('clicked', self.on_open_clicked)
+ hbox.append(button)
+
+ button = Gtk.Button.new_with_mnemonic('_Close')
+ button.connect('clicked', self.on_close_clicked)
+ hbox.append(button)
+
+ def on_click_me_clicked(self, _button):
+ print('[Click me] button was clicked')
+
+ def on_open_clicked(self, _button):
+ print('[Open] button was clicked')
+
+ def on_close_clicked(self, _button):
+ print('Closing application')
+ self.close()
+
+
+def on_activate(app):
+ win = ButtonWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/controls/examples/check_radio_buttons.py b/docs/tutorials/gtk4/controls/examples/check_radio_buttons.py
new file mode 100644
index 0000000..e03470d
--- /dev/null
+++ b/docs/tutorials/gtk4/controls/examples/check_radio_buttons.py
@@ -0,0 +1,55 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk
+
+
+class CheckButtonWindow(Gtk.ApplicationWindow):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, title='CheckButton Demo')
+
+ box = Gtk.Box(spacing=6)
+ self.set_child(box)
+
+ check = Gtk.CheckButton(label='Checkbox')
+ check.connect('toggled', self.on_check_toggled)
+ box.append(check)
+
+ radio1 = Gtk.CheckButton(label='Radio 1')
+ radio1.connect('toggled', self.on_radio_toggled, '1')
+ box.append(radio1)
+
+ radio2 = Gtk.CheckButton(label='Radio 2')
+ radio2.set_group(radio1)
+ radio2.connect('toggled', self.on_radio_toggled, '2')
+ box.append(radio2)
+
+ radio3 = Gtk.CheckButton.new_with_mnemonic('R_adio 3')
+ radio3.set_group(radio1)
+ radio3.connect('toggled', self.on_radio_toggled, '3')
+ box.append(radio3)
+
+ def on_check_toggled(self, check):
+ if check.props.active:
+ state = 'on'
+ else:
+ state = 'off'
+ print('Checkbox was turned', state)
+
+ def on_radio_toggled(self, radio, name):
+ if radio.props.active:
+ state = 'on'
+ else:
+ state = 'off'
+ print('Radio', name, 'was turned', state)
+
+
+def on_activate(app):
+ win = CheckButtonWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/controls/examples/dropdown.py b/docs/tutorials/gtk4/controls/examples/dropdown.py
new file mode 100644
index 0000000..3d5c597
--- /dev/null
+++ b/docs/tutorials/gtk4/controls/examples/dropdown.py
@@ -0,0 +1,38 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk
+
+
+class DropDownWindow(Gtk.ApplicationWindow):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, title='DropDown Demo')
+
+ dropdown = Gtk.DropDown()
+ dropdown.connect('notify::selected-item', self.on_string_selected)
+ self.set_child(dropdown)
+
+ strings = Gtk.StringList()
+ dropdown.props.model = strings
+ items = 'This is a long list of words to populate the dropdown'.split()
+
+ # Populate the list
+ for item in items:
+ strings.append(item)
+
+ def on_string_selected(self, dropdown, _pspec):
+ # Selected Gtk.StringObject
+ selected = dropdown.props.selected_item
+ if selected is not None:
+ print('Selected', selected.props.string)
+
+
+def on_activate(app):
+ win = DropDownWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/controls/examples/entries.py b/docs/tutorials/gtk4/controls/examples/entries.py
new file mode 100644
index 0000000..2c846eb
--- /dev/null
+++ b/docs/tutorials/gtk4/controls/examples/entries.py
@@ -0,0 +1,105 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk, GLib
+
+
+class EntryWindow(Gtk.ApplicationWindow):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, title='Entry Demo')
+
+ self.set_size_request(200, 100)
+
+ self.timeout_id = None
+
+ header = Gtk.HeaderBar()
+ self.set_titlebar(header)
+
+ vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
+ vbox.props.margin_start = 24
+ vbox.props.margin_end = 24
+ vbox.props.margin_top = 24
+ vbox.props.margin_bottom = 24
+ self.set_child(vbox)
+
+ # Gtk.SearchEntry
+ search = Gtk.SearchEntry()
+ search.props.placeholder_text = 'Search Entry'
+ search.set_key_capture_widget(self)
+ header.set_title_widget(search)
+ self.set_focus(search)
+
+ # Gtk.Entry
+ self.entry = Gtk.Entry()
+ self.entry.set_text('Hello World')
+ vbox.append(self.entry)
+
+ hbox = Gtk.Box(spacing=6)
+ vbox.append(hbox)
+
+ self.check_editable = Gtk.CheckButton(label='Editable')
+ self.check_editable.connect('toggled', self.on_editable_toggled)
+ self.check_editable.props.active = True
+ hbox.append(self.check_editable)
+
+ self.check_visible = Gtk.CheckButton(label='Visible')
+ self.check_visible.connect('toggled', self.on_visible_toggled)
+ self.check_visible.props.active = True
+ hbox.append(self.check_visible)
+
+ self.pulse = Gtk.CheckButton(label='Pulse')
+ self.pulse.connect('toggled', self.on_pulse_toggled)
+ hbox.append(self.pulse)
+
+ self.icon = Gtk.CheckButton(label='Icon')
+ self.icon.connect('toggled', self.on_icon_toggled)
+ hbox.append(self.icon)
+
+ # Gtk.PasswordEntry
+ pass_entry = Gtk.PasswordEntry()
+ pass_entry.props.placeholder_text = 'Password Entry'
+ pass_entry.props.show_peek_icon = True
+ pass_entry.props.margin_top = 24
+ vbox.append(pass_entry)
+
+ def on_editable_toggled(self, button):
+ value = button.get_active()
+ self.entry.set_editable(value)
+
+ def on_visible_toggled(self, button):
+ self.entry.props.visibility = button.props.active
+
+ def on_pulse_toggled(self, button):
+ if button.get_active():
+ self.entry.props.progress_pulse_step = 0.2
+ # Call self.do_pulse every 100 ms
+ self.timeout_id = GLib.timeout_add(100, self.do_pulse)
+ else:
+ # Don't call self.do_pulse anymore
+ GLib.source_remove(self.timeout_id)
+ self.timeout_id = None
+ self.entry.props.progress_pulse_step = 0
+
+ def do_pulse(self):
+ self.entry.progress_pulse()
+ return True
+
+ def on_icon_toggled(self, button):
+ if button.props.active:
+ icon_name = 'system-search-symbolic'
+ else:
+ icon_name = None
+ self.entry.set_icon_from_icon_name(
+ Gtk.EntryIconPosition.PRIMARY, icon_name
+ )
+
+
+def on_activate(app):
+ win = EntryWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/controls/examples/linkbutton.py b/docs/tutorials/gtk4/controls/examples/linkbutton.py
new file mode 100644
index 0000000..cdffd88
--- /dev/null
+++ b/docs/tutorials/gtk4/controls/examples/linkbutton.py
@@ -0,0 +1,25 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk
+
+
+class LinkButtonWindow(Gtk.ApplicationWindow):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, title='LinkButton Demo')
+
+ button = Gtk.LinkButton(
+ uri='https://www.gtk.org', label='Visit GTK Homepage'
+ )
+ self.set_child(button)
+
+
+def on_activate(app):
+ win = LinkButtonWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/controls/examples/spinbutton.py b/docs/tutorials/gtk4/controls/examples/spinbutton.py
new file mode 100644
index 0000000..36335d2
--- /dev/null
+++ b/docs/tutorials/gtk4/controls/examples/spinbutton.py
@@ -0,0 +1,52 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk
+
+
+class SpinButtonWindow(Gtk.ApplicationWindow):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, title='SpinButton Demo')
+
+ hbox = Gtk.Box(spacing=6)
+ self.set_child(hbox)
+
+ adjustment = Gtk.Adjustment(
+ upper=100, step_increment=1, page_increment=10
+ )
+ self.spinbutton = Gtk.SpinButton()
+ self.spinbutton.props.adjustment = adjustment
+ self.spinbutton.connect('value-changed', self.on_value_changed)
+ hbox.append(self.spinbutton)
+
+ check_numeric = Gtk.CheckButton(label='Numeric')
+ check_numeric.connect('toggled', self.on_numeric_toggled)
+ hbox.append(check_numeric)
+
+ check_ifvalid = Gtk.CheckButton(label='If Valid')
+ check_ifvalid.connect('toggled', self.on_ifvalid_toggled)
+ hbox.append(check_ifvalid)
+
+ def on_value_changed(self, _scroll):
+ print(self.spinbutton.get_value_as_int())
+
+ def on_numeric_toggled(self, button):
+ self.spinbutton.props.numeric = button.props.active
+
+ def on_ifvalid_toggled(self, button):
+ if button.get_active():
+ policy = Gtk.SpinButtonUpdatePolicy.IF_VALID
+ else:
+ policy = Gtk.SpinButtonUpdatePolicy.ALWAYS
+ self.spinbutton.props.update_policy = policy
+
+
+def on_activate(app):
+ win = SpinButtonWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/controls/examples/switch.py b/docs/tutorials/gtk4/controls/examples/switch.py
new file mode 100644
index 0000000..fcd294d
--- /dev/null
+++ b/docs/tutorials/gtk4/controls/examples/switch.py
@@ -0,0 +1,44 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk
+
+
+class SwitcherWindow(Gtk.ApplicationWindow):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, title='Switch Demo')
+
+ hbox = Gtk.Box(spacing=6, homogeneous=True)
+ hbox.props.margin_top = 24
+ hbox.props.margin_bottom = 24
+ self.set_child(hbox)
+
+ switch = Gtk.Switch()
+ switch.connect('notify::active', self.on_switch_activated)
+ switch.props.active = False
+ switch.props.halign = Gtk.Align.CENTER
+ hbox.append(switch)
+
+ switch = Gtk.Switch()
+ switch.connect('notify::active', self.on_switch_activated)
+ switch.props.active = True
+ switch.props.halign = Gtk.Align.CENTER
+ hbox.append(switch)
+
+ def on_switch_activated(self, switch, _gparam):
+ if switch.props.active:
+ state = 'on'
+ else:
+ state = 'off'
+ print('Switch was turned', state)
+
+
+def on_activate(app):
+ win = SwitcherWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/controls/examples/togglebutton.py b/docs/tutorials/gtk4/controls/examples/togglebutton.py
new file mode 100644
index 0000000..e2a1c67
--- /dev/null
+++ b/docs/tutorials/gtk4/controls/examples/togglebutton.py
@@ -0,0 +1,39 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk
+
+
+class ToggleButtonWindow(Gtk.ApplicationWindow):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, title='ToggleButton Demo')
+
+ hbox = Gtk.Box(spacing=6)
+ self.set_child(hbox)
+
+ button = Gtk.ToggleButton(label='Button 1')
+ button.connect('toggled', self.on_button_toggled, '1')
+ hbox.append(button)
+
+ button = Gtk.ToggleButton(label='B_utton 2', use_underline=True)
+ button.set_active(True)
+ button.connect('toggled', self.on_button_toggled, '2')
+ hbox.append(button)
+
+ def on_button_toggled(self, button, name):
+ if button.props.active:
+ state = 'on'
+ else:
+ state = 'off'
+ print('Button', name, 'was turned', state)
+
+
+def on_activate(app):
+ win = ToggleButtonWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/controls/images/button.png b/docs/tutorials/gtk4/controls/images/button.png
new file mode 100644
index 0000000..8d1c873
Binary files /dev/null and b/docs/tutorials/gtk4/controls/images/button.png differ
diff --git a/docs/tutorials/gtk4/controls/images/check_radio_buttons.png b/docs/tutorials/gtk4/controls/images/check_radio_buttons.png
new file mode 100644
index 0000000..f12b527
Binary files /dev/null and b/docs/tutorials/gtk4/controls/images/check_radio_buttons.png differ
diff --git a/docs/tutorials/gtk4/controls/images/dropdown.png b/docs/tutorials/gtk4/controls/images/dropdown.png
new file mode 100644
index 0000000..812c043
Binary files /dev/null and b/docs/tutorials/gtk4/controls/images/dropdown.png differ
diff --git a/docs/tutorials/gtk4/controls/images/entries.png b/docs/tutorials/gtk4/controls/images/entries.png
new file mode 100644
index 0000000..286ca47
Binary files /dev/null and b/docs/tutorials/gtk4/controls/images/entries.png differ
diff --git a/docs/tutorials/gtk4/controls/images/linkbutton.png b/docs/tutorials/gtk4/controls/images/linkbutton.png
new file mode 100644
index 0000000..0b659af
Binary files /dev/null and b/docs/tutorials/gtk4/controls/images/linkbutton.png differ
diff --git a/docs/tutorials/gtk4/controls/images/spinbutton.png b/docs/tutorials/gtk4/controls/images/spinbutton.png
new file mode 100644
index 0000000..069c23a
Binary files /dev/null and b/docs/tutorials/gtk4/controls/images/spinbutton.png differ
diff --git a/docs/tutorials/gtk4/controls/images/switch.png b/docs/tutorials/gtk4/controls/images/switch.png
new file mode 100644
index 0000000..a3d4510
Binary files /dev/null and b/docs/tutorials/gtk4/controls/images/switch.png differ
diff --git a/docs/tutorials/gtk4/controls/images/togglebutton.png b/docs/tutorials/gtk4/controls/images/togglebutton.png
new file mode 100644
index 0000000..303b0de
Binary files /dev/null and b/docs/tutorials/gtk4/controls/images/togglebutton.png differ
diff --git a/docs/tutorials/gtk4/controls/scale.rst b/docs/tutorials/gtk4/controls/scale.rst
new file mode 100644
index 0000000..edbdefa
--- /dev/null
+++ b/docs/tutorials/gtk4/controls/scale.rst
@@ -0,0 +1,5 @@
+.. currentmodule:: gi.repository
+
+Scale
+=====
+A :class:`Gtk.Scale` is a slider control used to select a numeric value.
\ No newline at end of file
diff --git a/docs/tutorials/gtk4/controls/spinbutton.rst b/docs/tutorials/gtk4/controls/spinbutton.rst
new file mode 100644
index 0000000..e6e0cf0
--- /dev/null
+++ b/docs/tutorials/gtk4/controls/spinbutton.rst
@@ -0,0 +1,38 @@
+.. currentmodule:: gi.repository
+
+SpinButton
+==========
+A :class:`Gtk.SpinButton` is an ideal way to allow the user to set the value of
+some attribute. Rather than having to directly type a number into a
+:class:`Gtk.Entry`, :class:`Gtk.SpinButton` allows the user to click on one of
+two arrows to increment or decrement the displayed value. A value can still be
+typed in, with the bonus that it can be checked to ensure it is in a given range.
+The main properties of a :class:`Gtk.SpinButton` are set through
+:class:`Gtk.Adjustment`.
+
+To change the value that :class:`Gtk.SpinButton` is showing, use
+:attr:`Gtk.SpinButton.props.value`. The value entered can either be an integer
+or float, depending on your requirements, use
+:meth:`Gtk.SpinButton.get_value_as_int` or :meth:`Gtk.SpinButton.get_value`,
+respectively.
+
+When you allow the displaying of float values in the spin button, you may wish
+to adjust the number of decimal spaces displayed by calling
+:attr:`Gtk.SpinButton.props.digits`.
+
+By default, :class:`Gtk.SpinButton` accepts textual data. If you wish to limit
+this to numerical values only, set :attr:`Gtk.SpinButton.props.numeric` to ``True``.
+
+We can also adjust the update policy of :class:`Gtk.SpinButton`. There are two
+options here; by default the spin button updates the value even if the data
+entered is invalid. Alternatively, we can set the policy to only update when the
+value entered is valid by changing :attr:`Gtk.SpinButton.props.update_policy` to
+:attr:`Gtk.SpinButtonUpdatePolicy.IF_VALID`.
+
+Example
+^^^^^^^
+
+.. image:: images/spinbutton.png
+
+.. literalinclude:: examples/spinbutton.py
+ :linenos:
diff --git a/docs/tutorials/gtk4/controls/switch.rst b/docs/tutorials/gtk4/controls/switch.rst
new file mode 100644
index 0000000..ab7c9d9
--- /dev/null
+++ b/docs/tutorials/gtk4/controls/switch.rst
@@ -0,0 +1,20 @@
+.. currentmodule:: gi.repository
+
+Switch
+======
+A :class:`Gtk.Switch` is a widget that has two states: on or off. The user can
+control which state should be active by clicking the empty area, or by dragging
+the handle.
+
+You shouldn't use the ``activate`` signal on the Gtk.Switch which is an action
+signal and emitting it causes the switch to animate. Applications should never
+connect to this signal, but use the ``notify::active`` signal, see the example
+here below.
+
+Example
+^^^^^^^
+
+.. image:: images/switch.png
+
+.. literalinclude:: examples/switch.py
+ :linenos:
diff --git a/docs/tutorials/gtk4/display-widgets.rst b/docs/tutorials/gtk4/display-widgets.rst
new file mode 100644
index 0000000..102a442
--- /dev/null
+++ b/docs/tutorials/gtk4/display-widgets.rst
@@ -0,0 +1,15 @@
+Display Widgets
+===============
+
+Learn how to use the most basic elements to display things, like text, images,
+icons or ongoing progress.
+
+.. toctree::
+ :maxdepth: 1
+ :caption: Contents
+
+ display-widgets/label
+ display-widgets/image
+ display-widgets/picture
+ display-widgets/progressbar
+ display-widgets/spinner
diff --git a/docs/tutorials/gtk4/display-widgets/examples/label.py b/docs/tutorials/gtk4/display-widgets/examples/label.py
new file mode 100644
index 0000000..cfdfa26
--- /dev/null
+++ b/docs/tutorials/gtk4/display-widgets/examples/label.py
@@ -0,0 +1,102 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk
+
+
+class LabelWindow(Gtk.ApplicationWindow):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, title='Label Demo')
+
+ box = Gtk.Box(spacing=10)
+ self.set_child(box)
+
+ box_left = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
+ box_left.props.hexpand = True
+ box_left.props.homogeneous = True
+ box_right = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
+
+ box.append(box_left)
+ box.append(box_right)
+
+ label = Gtk.Label(label='This is a normal label')
+ box_left.append(label)
+
+ label = Gtk.Label(label='This is a normal label with xalign set to 0')
+ label.props.xalign = 0
+ box_left.append(label)
+
+ label = Gtk.Label()
+ label.props.label = (
+ 'This is a left-justified label.\nWith multiple lines.'
+ )
+ label.props.justify = Gtk.Justification.LEFT
+ box_left.append(label)
+
+ label = Gtk.Label(
+ label='This is a right-justified label.\nWith multiple lines.'
+ )
+ label.props.justify = Gtk.Justification.RIGHT
+ box_left.append(label)
+
+ label = Gtk.Label(
+ label='This is an example of a line-wrapped label. It '
+ 'should not be taking up the entire '
+ 'width allocated to it, but automatically '
+ 'wraps the words to fit.\n'
+ ' It supports multiple paragraphs correctly, '
+ 'and correctly adds '
+ 'many extra spaces. '
+ )
+ label.props.wrap = True
+ label.props.max_width_chars = 32
+ box_right.append(label)
+
+ label = Gtk.Label(
+ label='This is an example of a line-wrapped, filled label. '
+ 'It should be taking '
+ 'up the entire width allocated to it. '
+ 'Here is a sentence to prove '
+ 'my point. Here is another sentence. '
+ 'Here comes the sun, do de do de do.\n'
+ ' This is a new paragraph.\n'
+ ' This is another newer, longer, better '
+ 'paragraph. It is coming to an end, '
+ 'unfortunately.'
+ )
+ label.props.wrap = True
+ label.props.justify = Gtk.Justification.FILL
+ label.props.max_width_chars = 32
+ box_right.append(label)
+
+ label = Gtk.Label()
+ label.set_markup(
+ 'Text can be small, big, '
+ 'bold, italic and even point to '
+ 'somewhere in the internets.'
+ )
+ label.props.wrap = True
+ label.props.max_width_chars = 48
+ box_left.append(label)
+
+ label = Gtk.Label.new_with_mnemonic(
+ '_Press Alt + P to select button to the right'
+ )
+ box_left.append(label)
+ label.props.selectable = True
+
+ button = Gtk.Button(label='Click at your own risk')
+ label.props.mnemonic_widget = button
+ box_right.append(button)
+
+
+def on_activate(app):
+ win = LabelWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/display-widgets/examples/picture.py b/docs/tutorials/gtk4/display-widgets/examples/picture.py
new file mode 100644
index 0000000..3b3d662
--- /dev/null
+++ b/docs/tutorials/gtk4/display-widgets/examples/picture.py
@@ -0,0 +1,38 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk
+
+
+class PictureWindow(Gtk.ApplicationWindow):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, title='Picture Demo')
+
+ # Let's set a windows size so pictures don't start at their default size
+ self.set_default_size(500, 400)
+
+ box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
+ self.set_child(box)
+
+ label = Gtk.Label(label='Here we can see some nice pictures:')
+ box.append(label)
+
+ picture = Gtk.Picture.new_for_filename('../images/spinner_ext.png')
+ box.append(picture)
+
+ cover_picture = Gtk.Picture.new_for_filename(
+ '../images/spinner_ext.png'
+ )
+ cover_picture.props.content_fit = Gtk.ContentFit.COVER
+ box.append(cover_picture)
+
+
+def on_activate(app):
+ win = PictureWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/display-widgets/examples/progressbar.py b/docs/tutorials/gtk4/display-widgets/examples/progressbar.py
new file mode 100644
index 0000000..a3e8860
--- /dev/null
+++ b/docs/tutorials/gtk4/display-widgets/examples/progressbar.py
@@ -0,0 +1,79 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk, GLib
+
+
+class ProgressBarWindow(Gtk.ApplicationWindow):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, title='ProgressBar Demo')
+
+ vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
+ self.set_child(vbox)
+
+ self.progressbar = Gtk.ProgressBar()
+ vbox.append(self.progressbar)
+
+ button = Gtk.CheckButton(label='Show text')
+ button.connect('toggled', self.on_show_text_toggled)
+ vbox.append(button)
+
+ button = Gtk.CheckButton(label='Activity mode')
+ button.connect('toggled', self.on_activity_mode_toggled)
+ vbox.append(button)
+
+ button = Gtk.CheckButton(label='Right to Left')
+ button.connect('toggled', self.on_right_to_left_toggled)
+ vbox.append(button)
+
+ self.timeout_id = GLib.timeout_add(50, self.on_timeout)
+ self.activity_mode = False
+
+ def on_show_text_toggled(self, button):
+ show_text = button.props.active
+ if show_text:
+ text = 'some text'
+ else:
+ text = None
+ self.progressbar.props.text = text
+ self.progressbar.props.show_text = show_text
+
+ def on_activity_mode_toggled(self, button):
+ self.activity_mode = button.props.active
+ if self.activity_mode:
+ self.progressbar.pulse()
+ else:
+ self.progressbar.props.fraction = 0.0
+
+ def on_right_to_left_toggled(self, button):
+ value = button.props.active
+ self.progressbar.props.inverted = value
+
+ def on_timeout(self):
+ '''
+ Update value on the progress bar
+ '''
+ if self.activity_mode:
+ self.progressbar.pulse()
+ else:
+ new_value = self.progressbar.props.fraction + 0.01
+
+ if new_value > 1:
+ new_value = 0
+
+ self.progressbar.props.fraction = new_value
+
+ # As this is a timeout function, return True so that it
+ # continues to get called
+ return True
+
+
+def on_activate(app):
+ win = ProgressBarWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/display-widgets/examples/spinner.py b/docs/tutorials/gtk4/display-widgets/examples/spinner.py
new file mode 100644
index 0000000..3a71a4f
--- /dev/null
+++ b/docs/tutorials/gtk4/display-widgets/examples/spinner.py
@@ -0,0 +1,40 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk
+
+
+class SpinnerAnimation(Gtk.ApplicationWindow):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, title='Spinner Demo')
+
+ button = Gtk.ToggleButton(label='Start Spinning')
+ button.connect('toggled', self.on_button_toggled)
+ button.props.active = False
+
+ self.spinner = Gtk.Spinner()
+
+ box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, homogeneous=True)
+ box.append(button)
+ box.append(self.spinner)
+ self.set_child(box)
+
+ def on_button_toggled(self, button):
+ if button.props.active:
+ self.spinner.start()
+ button.set_label('Stop Spinning')
+
+ else:
+ self.spinner.stop()
+ button.set_label('Start Spinning')
+
+
+def on_activate(app):
+ win = SpinnerAnimation(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/display-widgets/examples/spinner_ext.py b/docs/tutorials/gtk4/display-widgets/examples/spinner_ext.py
new file mode 100644
index 0000000..e48a7d0
--- /dev/null
+++ b/docs/tutorials/gtk4/display-widgets/examples/spinner_ext.py
@@ -0,0 +1,93 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk, GLib
+
+
+class SpinnerAnimation(Gtk.ApplicationWindow):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, title='Spinner Demo')
+
+ main_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
+ self.set_child(main_box)
+
+ self.spinner = Gtk.Spinner()
+ main_box.append(self.spinner)
+
+ self.label = Gtk.Label()
+ main_box.append(self.label)
+
+ self.entry = Gtk.Entry()
+ self.entry.props.text = '10'
+ main_box.append(self.entry)
+
+ self.button_start = Gtk.Button(label='Start timer')
+ self.button_start.connect('clicked', self.on_button_start_clicked)
+ main_box.append(self.button_start)
+
+ self.button_stop = Gtk.Button(label='Stop timer')
+ self.button_stop.props.sensitive = False
+ self.button_stop.connect('clicked', self.on_button_stop_clicked)
+ main_box.append(self.button_stop)
+
+ self.timeout_id = None
+ self.connect('unrealize', self.on_window_destroy)
+
+ def on_button_start_clicked(self, _widget):
+ '''Handles 'clicked' event of button_start.'''
+ self.start_timer()
+
+ def on_button_stop_clicked(self, _widget):
+ '''Handles 'clicked' event of button_stop.'''
+ self.stop_timer('Stopped from button')
+
+ def on_window_destroy(self, _widget):
+ '''Handles unrealize event of main window.'''
+ # Ensure the timeout function is stopped
+ if self.timeout_id:
+ GLib.source_remove(self.timeout_id)
+ self.timeout_id = None
+
+ def on_timeout(self):
+ '''A timeout function.
+ Return True to stop it.
+ This is not a precise timer since next timeout
+ is recalculated based on the current time.
+ '''
+ self.counter -= 1
+ if self.counter <= 0:
+ self.stop_timer('Reached time out')
+ return False
+ self.label.props.label = f'Remaining: {str(int(self.counter / 4))}'
+ return True
+
+ def start_timer(self):
+ '''Start the timer.'''
+ self.button_start.props.sensitive = False
+ self.button_stop.props.sensitive = True
+ # time out will check every 250 milliseconds (1/4 of a second)
+ self.counter = 4 * int(self.entry.props.text)
+ self.label.props.label = f'Remaining: {str(int(self.counter / 4))}'
+ self.spinner.start()
+ self.timeout_id = GLib.timeout_add(250, self.on_timeout)
+
+ def stop_timer(self, label_text):
+ '''Stop the timer.'''
+ if self.timeout_id:
+ GLib.source_remove(self.timeout_id)
+ self.timeout_id = None
+ self.spinner.stop()
+ self.button_start.props.sensitive = True
+ self.button_stop.props.sensitive = False
+ self.label.props.label = label_text
+
+
+def on_activate(app):
+ win = SpinnerAnimation(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/display-widgets/image.rst b/docs/tutorials/gtk4/display-widgets/image.rst
new file mode 100644
index 0000000..1b5f0e3
--- /dev/null
+++ b/docs/tutorials/gtk4/display-widgets/image.rst
@@ -0,0 +1,20 @@
+.. currentmodule:: gi.repository
+
+Image
+=====
+
+:class:`Gtk.Image` is a widget to display images.
+Various kinds of object can be displayed as an image.
+Most typically, you would load a :class:`Gdk.Texture` from a file, using the
+convenience function :meth:`Gtk.Image.new_from_file`, or
+:meth:`Gtk.Image.new_from_icon_name`.
+
+:class:`Gtk.Image` displays its image as an icon, with a size that is determined
+by the application. See :doc:`/tutorials/gtk4/display-widgets/picture` if you want to show
+an image at is actual size.
+
+Sometimes an application will want to avoid depending on external data files,
+such as image files.
+See the documentation of :class:`Gio.Resource` inside GIO, for details.
+In this case, :attr:`Gtk.Image.props.resource` and
+:meth:`Gtk.Image.new_from_resource`, should be used.
diff --git a/docs/tutorials/gtk4/display-widgets/images/label.png b/docs/tutorials/gtk4/display-widgets/images/label.png
new file mode 100644
index 0000000..fc22d3b
Binary files /dev/null and b/docs/tutorials/gtk4/display-widgets/images/label.png differ
diff --git a/docs/tutorials/gtk4/display-widgets/images/picture.png b/docs/tutorials/gtk4/display-widgets/images/picture.png
new file mode 100644
index 0000000..c70f216
Binary files /dev/null and b/docs/tutorials/gtk4/display-widgets/images/picture.png differ
diff --git a/docs/tutorials/gtk4/display-widgets/images/progressbar.png b/docs/tutorials/gtk4/display-widgets/images/progressbar.png
new file mode 100644
index 0000000..7cac8ac
Binary files /dev/null and b/docs/tutorials/gtk4/display-widgets/images/progressbar.png differ
diff --git a/docs/tutorials/gtk4/display-widgets/images/spinner.png b/docs/tutorials/gtk4/display-widgets/images/spinner.png
new file mode 100644
index 0000000..42aa319
Binary files /dev/null and b/docs/tutorials/gtk4/display-widgets/images/spinner.png differ
diff --git a/docs/tutorials/gtk4/display-widgets/images/spinner_ext.png b/docs/tutorials/gtk4/display-widgets/images/spinner_ext.png
new file mode 100644
index 0000000..dc7b170
Binary files /dev/null and b/docs/tutorials/gtk4/display-widgets/images/spinner_ext.png differ
diff --git a/docs/tutorials/gtk4/display-widgets/label.rst b/docs/tutorials/gtk4/display-widgets/label.rst
new file mode 100644
index 0000000..2d144cd
--- /dev/null
+++ b/docs/tutorials/gtk4/display-widgets/label.rst
@@ -0,0 +1,64 @@
+.. currentmodule:: gi.repository
+
+Label
+=====
+Labels are the main method of placing non-editable text in windows, for instance
+to place a title next to a :class:`Gtk.Entry` widget. You can specify the text
+in the constructor, or later with the :attr:`Gtk.Label.props.label` property.
+
+The width of the label will be adjusted automatically. You can produce
+multi-line labels by putting line breaks (``\n``) in the label string.
+
+Labels can be made selectable with :attr:`Gtk.Label.props.selectable`.
+Selectable labels allow the user to copy the label contents to the
+clipboard. Only labels that contain useful-to-copy information —
+such as error messages — should be made selectable.
+
+The label text can be justified using the :attr:`Gtk.Label.props.justify` prop.
+The widget is also capable of word-wrapping, which can be activated with
+:attr:`Gtk.Label.props.wrap`. You can configure this wrapping by changing
+:attr:`Gtk.Label.props.wrap_mode`, in can be :attr:`Pango.WrapMode.WORD`,
+:attr:`Pango.WrapMode.CHAR` or :attr:`Pango.WrapMode.WORD_CHAR`.
+
+:class:`Gtk.Label` support some simple formatting, for instance allowing you to
+make some text bold, colored, or larger. You can do this by enabling markup
+setting :attr:`Gtk.Label.props.use_markup` to ``True``, then you can use markup
+with :attr:`Gtk.Label.props.label` using the Pango Markup syntax [#pango]_.
+For instance, ``bold text and strikethrough text``.
+In addition, :class:`Gtk.Label` supports clickable hyperlinks.
+The markup for links is borrowed from HTML, using the a with href and title
+attributes. GTK renders links similar to the way they appear in web browsers,
+with colored, underlined text. The title attribute is displayed as a tooltip
+on the link. :meth:`Gtk.Label.set_markup` method can be used to set the text and
+enable markup at the same time.
+
+.. code-block:: python
+
+ label.set_markup("Go to GTK+ website for more")
+
+Labels may contain *mnemonics*. Mnemonics are underlined characters in the
+label, used for keyboard navigation. Mnemonics are created by providing a
+string with an underscore before the mnemonic character, such as "_File",
+to the functions :meth:`Gtk.Label.new_with_mnemonic` or
+:meth:`Gtk.Label.set_text_with_mnemonic`.
+Mnemonics automatically activate any activatable widget the label is inside,
+such as a :class:`Gtk.Button`; if the label is not inside the mnemonic's target
+widget, you have to tell the label about the target using
+:attr:`Gtk.Label.props.mnemonic_widget`.
+
+You can also change the alignment of the label text inside its size allocation.
+For example if you use :attr:`Gtk.Widget.props.hexpand` in a label, the label
+may take more space than its inner text.
+You can change this alignment using :attr:`Gtk.Label.props.xalign` for
+horizontal alignment and :attr:`Gtk.Label.props.yalign` for vertical.
+
+Example
+-------
+
+.. image:: images/label.png
+
+.. literalinclude:: examples/label.py
+ :linenos:
+
+.. [#pango] Pango Markup Syntax, https://docs.gtk.org/Pango/pango_markup.html
diff --git a/docs/tutorials/gtk4/display-widgets/picture.rst b/docs/tutorials/gtk4/display-widgets/picture.rst
new file mode 100644
index 0000000..4ff64a9
--- /dev/null
+++ b/docs/tutorials/gtk4/display-widgets/picture.rst
@@ -0,0 +1,32 @@
+.. currentmodule:: gi.repository
+
+Picture
+=======
+
+:class:`Gtk.Picture` displays an image at its natural size.
+Many convenience functions are provided to make pictures simple to use.
+For example, if you want to load an image from a file you can use
+:meth:`Gtk.Picture.new_for_filename`.
+
+You can influence how the image is displayed inside the :class:`Gtk.Picture` by
+changing :attr:`Gtk.Picture.props.content_fit`. See :class:`Gtk.ContentFit` for
+details.
+Also :attr:`Gtk.Widget.props.halign` and :attr:`Gtk.Widget.props.valign` can be
+used to set whether the picture will fill all available space or is displayed at its
+original size.
+
+Sometimes an application will want to avoid depending on external data files,
+such as image files.
+See the documentation of :class:`Gio.Resource` inside GIO, for details.
+In this case, :meth:`Gtk.Picture.new_for_resource` and
+:meth:`Gtk.Picture.set_resource`, should be used.
+
+.. note:: This example requires a GTK version higher o equal to ``4.8``.
+
+Example
+-------
+
+.. image:: images/picture.png
+
+.. literalinclude:: examples/picture.py
+ :linenos:
diff --git a/docs/tutorials/gtk4/display-widgets/progressbar.rst b/docs/tutorials/gtk4/display-widgets/progressbar.rst
new file mode 100644
index 0000000..84dce03
--- /dev/null
+++ b/docs/tutorials/gtk4/display-widgets/progressbar.rst
@@ -0,0 +1,39 @@
+.. currentmodule:: gi.repository
+
+ProgressBar
+===========
+The :class:`Gtk.ProgressBar` is typically used to display the progress of a
+long running operation. It provides a visual clue that processing is underway.
+The :class:`Gtk.ProgressBar` can be used in two different modes: *percentage
+mode* and *activity mode*.
+
+When an application can determine how much work needs to take place (e.g. read
+a fixed number of bytes from a file) and can monitor its progress, it can use
+the :class:`Gtk.ProgressBar` in *percentage mode* and the user sees a growing
+bar indicating the percentage of the work that has been completed.
+In this mode, the application is required to set
+:attr:`Gtk.ProgressBar.props.fraction` periodically to update the progress bar,
+setting a float between 0 and 1 to provide the new percentage value.
+
+When an application has no accurate way of knowing the amount of work to do, it
+can use *activity mode*, which shows activity by a block moving back and forth
+within the progress area. In this mode, the application is required to call
+:meth:`Gtk.ProgressBar.pulse` periodically to update the progress bar.
+You can also choose the step size, with the
+:attr:`Gtk.ProgressBar.props.pulse_step` property.
+
+By default, :class:`Gtk.ProgressBar` is horizontal and left-to-right, but you
+can change it to a vertical progress bar by changing the value of
+:attr:`Gtk.ProgressBar.props.orientation `.
+Changing the direction the progress bar grows can be done using
+:attr:`Gtk.ProgressBar.props.inverted`. :class:`Gtk.ProgressBar` can also
+contain text which can be set with :attr:`Gtk.ProgressBar.props.text` and
+:attr:`Gtk.ProgressBar.props.show_text`.
+
+Example
+-------
+
+.. image:: images/progressbar.png
+
+.. literalinclude:: examples/progressbar.py
+ :linenos:
diff --git a/docs/tutorials/gtk4/display-widgets/spinner.rst b/docs/tutorials/gtk4/display-widgets/spinner.rst
new file mode 100644
index 0000000..583e69a
--- /dev/null
+++ b/docs/tutorials/gtk4/display-widgets/spinner.rst
@@ -0,0 +1,35 @@
+.. currentmodule:: gi.repository
+
+Spinner
+=======
+The :class:`Gtk.Spinner` displays an icon-size spinning animation.
+It is often used as an alternative to a :class:`Gtk.ProgressBar`
+for displaying indefinite activity, instead of actual progress.
+
+To start the animation, use :meth:`Gtk.Spinner.start`,
+to stop it use :meth:`Gtk.Spinner.stop`.
+
+Example
+-------
+
+.. image:: images/spinner.png
+
+.. literalinclude:: examples/spinner.py
+ :linenos:
+
+
+Extended example
+----------------
+An extended example that uses a timeout function to start and stop
+the spinning animation.
+The :func:`on_timeout` function is called at regular intervals
+until it returns ``False``, at which point the timeout is automatically
+destroyed and the function will not be called again.
+
+Example
+^^^^^^^
+
+.. image:: images/spinner_ext.png
+
+.. literalinclude:: examples/spinner_ext.py
+ :linenos:
diff --git a/docs/tutorials/gtk4/drag-and-drop.rst b/docs/tutorials/gtk4/drag-and-drop.rst
new file mode 100644
index 0000000..3e3a082
--- /dev/null
+++ b/docs/tutorials/gtk4/drag-and-drop.rst
@@ -0,0 +1,73 @@
+.. currentmodule:: gi.repository
+
+Drag and Drop
+=============
+
+.. seealso:: `Drag-and-Drop`_ in the GTK documentation.
+
+GTK drag-and-drop works with drag sources and drop targets.
+These are event controllers that can be set to any widget using
+:meth:`Gtk.Widget.add_controller`. The data begin moved in the operation is
+provided through a :class:`Gdk.ContentProvider`.
+
+
+Drag sources
+------------
+:class:`Gtk.DragSource` is the event controller that allows a widget to be used
+as a drag source.
+You can set up everything needed for the drag-and-drop operation ahead of time
+or do it on the fly using the signals provided by :class:`Gtk.DragSource`.
+
+You can use :meth:`Gtk.DragSource.set_content` to set the
+:class:`Gdk.ContentProvider` that will be sent to drop targets.
+A content provider is usually created using
+:meth:`Gdk.ContentProvider.new_for_value` where you only pass the value to send.
+To pass different values for multiple possible targets you can use
+:meth:`Gdk.ContentProvider.new_union` were you can pass a list of
+:class:`Gdk.ContentProviders `.
+
+:class:`Gtk.DragSource` provides signals for the different stages of the drag
+event.
+The :func:`prepare ` signal is emitted when a
+drag is about to be initiated, here you should return the
+:class:`Gdk.ContentProvider` that will be sent, otherwise the one set with
+:meth:`Gtk.DragSource.set_content` will be used.
+The :func:`drag-begin ` signal is emitted
+when the drag is started, here you can do things like changing the icon attached
+to the cursor when dragging using :meth:`Gtk.DragSource.set_icon`.
+Also the :func:`drag-end ` signal is provided,
+you can use it to undo things done in the previous signals.
+Finally :func:`drag-cancel ` allows you
+to do things when the operation has been cancelled.
+
+Drop targets
+------------
+:class:`Gtk.DropTarget` is the event controller to receive drag-and-drop
+operations in a widget.
+When creating a new drop target with :meth:`Gtk.DropTarget.new` you should
+provide the data type and :class:`Gdk.DragAction` that your target accepts.
+If you want to support multiple data types you can pass :attr:`GObject.TYPE_NONE`
+and then use :meth:`Gtk.DropTarget.set_gtypes` where you can pass a list of
+types, be aware that the order of the list establish the priorities.
+
+:class:`Gtk.DropTarget` provides multiple signals for the process. These are
+:func:`accept `,
+:func:`drop `,
+:func:`enter `,
+:func:`leave `, and
+:func:`motion `.
+Generally connecting to :func:`drop ` is only
+needed, this signal will receive the value sended by the :class:`Gtk.DragSource`.
+
+For more complex use cases checkout :class:`Gtk.DropTargetAsync`.
+
+Example
+-------
+
+.. image:: images/drag_and_drop.png
+
+.. literalinclude:: examples/drag_and_drop.py
+ :linenos:
+
+
+.. _Drag-and-Drop: https://docs.gtk.org/gtk4/drag-and-drop.html
diff --git a/docs/tutorials/gtk4/examples/application.py b/docs/tutorials/gtk4/examples/application.py
new file mode 100644
index 0000000..69ea099
--- /dev/null
+++ b/docs/tutorials/gtk4/examples/application.py
@@ -0,0 +1,167 @@
+import sys
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import GLib, Gio, Gtk
+
+# This would typically be its own file
+MENU_XML = """
+
+
+
+
+"""
+
+
+class AppWindow(Gtk.ApplicationWindow):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ self.set_default_size(200, 200)
+
+ # By default the title bar will be hide, let's show it
+ self.props.show_menubar = True
+
+ # This will be in the windows group and have the 'win' prefix
+ max_action = Gio.SimpleAction.new_stateful(
+ 'maximize', None, GLib.Variant.new_boolean(False)
+ )
+ max_action.connect('change-state', self.on_maximize_toggle)
+ self.add_action(max_action)
+
+ # Keep it in sync with the actual state
+ self.connect(
+ 'notify::maximized',
+ lambda obj, _pspec: max_action.set_state(
+ GLib.Variant.new_boolean(obj.props.maximized)
+ ),
+ )
+
+ lbl_variant = GLib.Variant.new_string('String 1')
+ lbl_action = Gio.SimpleAction.new_stateful(
+ 'change_label', lbl_variant.get_type(), lbl_variant
+ )
+ lbl_action.connect('change-state', self.on_change_label_state)
+ self.add_action(lbl_action)
+
+ self.label = Gtk.Label(label=lbl_variant.get_string())
+ self.set_child(self.label)
+
+ def on_change_label_state(self, action, value):
+ action.set_state(value)
+ self.label.set_text(value.get_string())
+
+ def on_maximize_toggle(self, action, value):
+ action.set_state(value)
+ if value.get_boolean():
+ self.maximize()
+ else:
+ self.unmaximize()
+
+
+class Application(Gtk.Application):
+ def __init__(self, *args, **kwargs):
+ super().__init__(
+ *args,
+ application_id='org.example.App',
+ flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE,
+ **kwargs
+ )
+ self.window = None
+
+ self.add_main_option(
+ 'test',
+ ord('t'),
+ GLib.OptionFlags.NONE,
+ GLib.OptionArg.NONE,
+ 'Command line test',
+ None,
+ )
+
+ def do_startup(self):
+ Gtk.Application.do_startup(self)
+
+ action = Gio.SimpleAction.new('about', None)
+ action.connect('activate', self.on_about)
+ self.add_action(action)
+
+ action = Gio.SimpleAction.new('quit', None)
+ action.connect('activate', self.on_quit)
+ self.add_action(action)
+
+ builder = Gtk.Builder.new_from_string(MENU_XML, -1)
+ self.set_menubar(builder.get_object('menubar'))
+
+ def do_activate(self):
+ # We only allow a single window and raise any existing ones
+ if not self.window:
+ # Windows are associated with the application
+ # when the last one is closed the application shuts down
+ self.window = AppWindow(application=self, title='Main Window')
+
+ self.window.present()
+
+ def do_command_line(self, command_line):
+ options = command_line.get_options_dict()
+ # convert GVariantDict -> GVariant -> dict
+ options = options.end().unpack()
+
+ if 'test' in options:
+ # This is printed on the main instance
+ print('Test argument recieved: %s' % options['test'])
+
+ self.activate()
+ return 0
+
+ def on_about(self, _action, _param):
+ about_dialog = Gtk.AboutDialog(transient_for=self.window, modal=True)
+ about_dialog.present()
+
+ def on_quit(self, _action, _param):
+ self.quit()
+
+
+if __name__ == '__main__':
+ app = Application()
+ app.run(sys.argv)
diff --git a/docs/tutorials/gtk4/examples/clipboard.py b/docs/tutorials/gtk4/examples/clipboard.py
new file mode 100644
index 0000000..c92c6dc
--- /dev/null
+++ b/docs/tutorials/gtk4/examples/clipboard.py
@@ -0,0 +1,84 @@
+import gi
+
+gi.require_version('Gdk', '4.0')
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gdk, Gtk
+
+
+class ClipboardWindow(Gtk.ApplicationWindow):
+ def __init__(self, *args, **kargs):
+ super().__init__(*args, **kargs, title='Clipboard Example')
+
+ box = Gtk.Box(spacing=12, orientation=Gtk.Orientation.VERTICAL)
+ self.set_child(box)
+
+ self.clipboard = Gdk.Display.get_default().get_clipboard()
+
+ text_box = Gtk.Box(spacing=6, homogeneous=True)
+ box.append(text_box)
+
+ self.entry = Gtk.Entry(text='Some text you can copy')
+ button_copy_text = Gtk.Button(label='Copy Text')
+ button_copy_text.connect('clicked', self.copy_text)
+ button_paste_text = Gtk.Button(label='Paste Text')
+ button_paste_text.connect('clicked', self.paste_text)
+
+ text_box.append(self.entry)
+ text_box.append(button_copy_text)
+ text_box.append(button_paste_text)
+
+ image_box = Gtk.Box(spacing=6)
+ box.append(image_box)
+
+ self.picture = Gtk.Picture.new_for_filename(
+ '../images/application.png'
+ )
+ self.picture.props.hexpand = True
+ button_copy_image = Gtk.Button(
+ label='Copy Image', valign=Gtk.Align.CENTER
+ )
+ button_copy_image.connect('clicked', self.copy_image)
+ button_paste_image = Gtk.Button(
+ label='Paste Image', valign=Gtk.Align.CENTER
+ )
+ button_paste_image.connect('clicked', self.paste_image)
+
+ image_box.append(self.picture)
+ image_box.append(button_copy_image)
+ image_box.append(button_paste_image)
+
+ def copy_text(self, _button):
+ self.clipboard.set(self.entry.get_text())
+
+ def paste_text(self, _button):
+ self.clipboard.read_text_async(None, self.on_paste_text)
+
+ def on_paste_text(self, _clipboard, result):
+ text = self.clipboard.read_text_finish(result)
+ if text is not None:
+ self.entry.set_text(text)
+
+ def copy_image(self, _button):
+ texture = self.picture.get_paintable()
+ gbytes = texture.save_to_png_bytes()
+ content = Gdk.ContentProvider.new_for_bytes('image/png', gbytes)
+ self.clipboard.set_content(content)
+
+ def paste_image(self, _button):
+ self.clipboard.read_texture_async(None, self.on_paste_image)
+
+ def on_paste_image(self, _clipboard, result):
+ texture = self.clipboard.read_texture_finish(result)
+ if texture is not None:
+ self.picture.set_paintable(texture)
+
+
+def on_activate(app):
+ win = ClipboardWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/examples/drag_and_drop.py b/docs/tutorials/gtk4/examples/drag_and_drop.py
new file mode 100644
index 0000000..be7b0b8
--- /dev/null
+++ b/docs/tutorials/gtk4/examples/drag_and_drop.py
@@ -0,0 +1,122 @@
+import gi
+
+gi.require_version('Gdk', '4.0')
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gdk, GObject, Gtk
+
+
+class DragDropWindow(Gtk.ApplicationWindow):
+ def __init__(self, *args, **kargs):
+ super().__init__(*args, **kargs, title='Drag and Drop Example')
+
+ self.set_default_size(500, 400)
+
+ views_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
+ views_box.props.vexpand = True
+ self.set_child(views_box)
+
+ flow_box = Gtk.FlowBox()
+ views_box.append(flow_box)
+ flow_box.props.selection_mode = Gtk.SelectionMode.NONE
+ flow_box.append(SourceFlowBoxChild('Item 1', 'image-missing'))
+ flow_box.append(SourceFlowBoxChild('Item 2', 'help-about'))
+ flow_box.append(SourceFlowBoxChild('Item 3', 'edit-copy'))
+
+ views_box.append(Gtk.Separator())
+
+ self.target_view = TargetView(vexpand=True)
+ views_box.append(self.target_view)
+
+
+class SourceFlowBoxChild(Gtk.FlowBoxChild):
+ def __init__(self, name, icon_name):
+ super().__init__()
+
+ self.name = name
+ self.icon_name = icon_name
+
+ box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
+ self.set_child(box)
+
+ icon = Gtk.Image(icon_name=self.icon_name)
+ label = Gtk.Label(label=self.name)
+
+ box.append(icon)
+ box.append(label)
+
+ drag_controller = Gtk.DragSource()
+ drag_controller.connect('prepare', self.on_drag_prepare)
+ drag_controller.connect('drag-begin', self.on_drag_begin)
+ self.add_controller(drag_controller)
+
+ def on_drag_prepare(self, _ctrl, _x, _y):
+ item = Gdk.ContentProvider.new_for_value(self)
+ string = Gdk.ContentProvider.new_for_value(self.name)
+ return Gdk.ContentProvider.new_union([item, string])
+
+ def on_drag_begin(self, ctrl, _drag):
+ icon = Gtk.WidgetPaintable.new(self)
+ ctrl.set_icon(icon, 0, 0)
+
+
+class TargetView(Gtk.Box):
+ def __init__(self, **kargs):
+ super().__init__(**kargs)
+
+ self.stack = Gtk.Stack(hexpand=True)
+ self.append(self.stack)
+
+ empty_label = Gtk.Label(label='Drag some item, text, or files here.')
+ self.stack.add_named(empty_label, 'empty')
+ self.stack.set_visible_child_name('empty')
+
+ box = Gtk.Box(
+ orientation=Gtk.Orientation.VERTICAL,
+ vexpand=True,
+ valign=Gtk.Align.CENTER,
+ )
+ self.stack.add_named(box, 'item')
+
+ self.icon = Gtk.Image()
+ box.append(self.icon)
+ self.label = Gtk.Label()
+ box.append(self.label)
+
+ self.text = Gtk.Label()
+ self.stack.add_named(self.text, 'other')
+
+ drop_controller = Gtk.DropTarget.new(
+ type=GObject.TYPE_NONE, actions=Gdk.DragAction.COPY
+ )
+ drop_controller.set_gtypes([SourceFlowBoxChild, Gdk.FileList, str])
+ drop_controller.connect('drop', self.on_drop)
+ self.add_controller(drop_controller)
+
+ def on_drop(self, _ctrl, value, _x, _y):
+ if isinstance(value, SourceFlowBoxChild):
+ self.label.props.label = value.name
+ self.icon.props.icon_name = value.icon_name
+ self.stack.set_visible_child_name('item')
+
+ elif isinstance(value, Gdk.FileList):
+ files = value.get_files()
+ names = ''
+ for file in files:
+ names += f'Loaded file {file.get_basename()}\n'
+ self.text.props.label = names
+ self.stack.set_visible_child_name('other')
+
+ elif isinstance(value, str):
+ self.text.props.label = value
+ self.stack.set_visible_child_name('other')
+
+
+def on_activate(app):
+ win = DragDropWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/examples/extended_example.py b/docs/tutorials/gtk4/examples/extended_example.py
new file mode 100644
index 0000000..c642cc8
--- /dev/null
+++ b/docs/tutorials/gtk4/examples/extended_example.py
@@ -0,0 +1,29 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk
+
+
+class MyWindow(Gtk.ApplicationWindow):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, title='Hello World')
+
+ self.button = Gtk.Button(label='Click Here')
+ self.button.connect('clicked', self.on_button_clicked)
+ self.set_child(self.button)
+
+ def on_button_clicked(self, _widget):
+ print('Hello World')
+ self.close()
+
+
+def on_activate(app):
+ # Create window
+ win = MyWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/examples/layout_box.py b/docs/tutorials/gtk4/examples/layout_box.py
new file mode 100644
index 0000000..d388463
--- /dev/null
+++ b/docs/tutorials/gtk4/examples/layout_box.py
@@ -0,0 +1,39 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk
+
+
+class MyWindow(Gtk.ApplicationWindow):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, title='Hello World')
+
+ box = Gtk.Box(spacing=6)
+ self.set_child(box)
+
+ button1 = Gtk.Button(label='Hello')
+ button1.connect('clicked', self.on_button1_clicked)
+ box.append(button1)
+
+ button2 = Gtk.Button(label='Goodbye')
+ button2.props.hexpand = True
+ button2.connect('clicked', self.on_button2_clicked)
+ box.append(button2)
+
+ def on_button1_clicked(self, _widget):
+ print('Hello')
+
+ def on_button2_clicked(self, _widget):
+ print('Goodbye')
+
+
+def on_activate(app):
+ # Create window
+ win = MyWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/examples/layout_center.py b/docs/tutorials/gtk4/examples/layout_center.py
new file mode 100644
index 0000000..ccd20f2
--- /dev/null
+++ b/docs/tutorials/gtk4/examples/layout_center.py
@@ -0,0 +1,33 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk
+
+
+class CenterBoxWindow(Gtk.ApplicationWindow):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, default_width=400, title='CenterBox Example')
+
+ box = Gtk.CenterBox()
+ self.set_child(box)
+
+ button1 = Gtk.Button(label='Start')
+ box.set_start_widget(button1)
+
+ label = Gtk.Label(label='Center')
+ box.set_center_widget(label)
+
+ button2 = Gtk.Button(label='End')
+ box.set_end_widget(button2)
+
+
+def on_activate(app):
+ # Create window
+ win = CenterBoxWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/examples/layout_flowbox.py b/docs/tutorials/gtk4/examples/layout_flowbox.py
new file mode 100644
index 0000000..dc5d614
--- /dev/null
+++ b/docs/tutorials/gtk4/examples/layout_flowbox.py
@@ -0,0 +1,131 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk, Gdk
+
+
+class FlowBoxWindow(Gtk.ApplicationWindow):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, title='FlowBox Demo')
+
+ self.set_default_size(300, 250)
+
+ header = Gtk.HeaderBar()
+ self.set_titlebar(header)
+
+ scrolled = Gtk.ScrolledWindow()
+ scrolled.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
+ self.set_child(scrolled)
+
+ flowbox = Gtk.FlowBox()
+ flowbox.props.valign = Gtk.Align.START
+ flowbox.props.max_children_per_line = 30
+ flowbox.props.selection_mode = Gtk.SelectionMode.NONE
+ scrolled.set_child(flowbox)
+
+ self.create_flowbox(flowbox)
+
+ def draw_button_color(self, area, cr, width, height, rgba):
+ context = area.get_style_context()
+
+ Gtk.render_background(context, cr, 0, 0, width, height)
+
+ cr.set_source_rgba(rgba.red, rgba.green, rgba.blue, rgba.alpha)
+ cr.rectangle(0, 0, width, height)
+ cr.fill()
+
+ def color_swatch_new(self, str_color):
+ rgba = Gdk.RGBA()
+ rgba.parse(str_color)
+
+ button = Gtk.Button()
+
+ area = Gtk.DrawingArea()
+ area.set_size_request(24, 24)
+ area.set_draw_func(self.draw_button_color, rgba)
+
+ button.set_child(area)
+
+ return button
+
+ def create_flowbox(self, flowbox):
+ colors = [
+ 'AliceBlue',
+ 'AntiqueWhite',
+ 'AntiqueWhite1',
+ 'AntiqueWhite2',
+ 'AntiqueWhite3',
+ 'AntiqueWhite4',
+ 'aqua',
+ 'aquamarine',
+ 'aquamarine1',
+ 'aquamarine2',
+ 'aquamarine3',
+ 'aquamarine4',
+ 'azure',
+ 'azure1',
+ 'azure2',
+ 'azure3',
+ 'azure4',
+ 'beige',
+ 'bisque',
+ 'bisque1',
+ 'bisque2',
+ 'bisque3',
+ 'bisque4',
+ 'black',
+ 'BlanchedAlmond',
+ 'blue',
+ 'blue1',
+ 'blue2',
+ 'blue3',
+ 'blue4',
+ 'BlueViolet',
+ 'brown',
+ 'brown1',
+ 'brown2',
+ 'brown3',
+ 'brown4',
+ 'burlywood',
+ 'burlywood1',
+ 'burlywood2',
+ 'burlywood3',
+ 'burlywood4',
+ 'CadetBlue',
+ 'CadetBlue1',
+ 'CadetBlue2',
+ 'CadetBlue3',
+ 'CadetBlue4',
+ 'chartreuse',
+ 'chartreuse1',
+ 'chartreuse2',
+ 'chartreuse3',
+ 'chartreuse4',
+ 'chocolate',
+ 'chocolate1',
+ 'chocolate2',
+ 'chocolate3',
+ 'chocolate4',
+ 'coral',
+ 'coral1',
+ 'coral2',
+ 'coral3',
+ 'coral4',
+ ]
+
+ for color in colors:
+ button = self.color_swatch_new(color)
+ button.props.tooltip_text = color
+ flowbox.append(button)
+
+
+def on_activate(app):
+ # Create window
+ win = FlowBoxWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/examples/layout_grid.py b/docs/tutorials/gtk4/examples/layout_grid.py
new file mode 100644
index 0000000..4691cea
--- /dev/null
+++ b/docs/tutorials/gtk4/examples/layout_grid.py
@@ -0,0 +1,38 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk
+
+
+class GridWindow(Gtk.ApplicationWindow):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, title='Grid Example')
+
+ button1 = Gtk.Button(label='Button 1')
+ button2 = Gtk.Button(label='Button 2')
+ button3 = Gtk.Button(label='Button 3')
+ button4 = Gtk.Button(label='Button 4')
+ button5 = Gtk.Button(label='Button 5')
+ button6 = Gtk.Button(label='Button 6')
+
+ grid = Gtk.Grid()
+ grid.attach(button1, 0, 0, 1, 1)
+ grid.attach(button2, 1, 0, 2, 1)
+ grid.attach_next_to(button3, button1, Gtk.PositionType.BOTTOM, 1, 2)
+ grid.attach_next_to(button4, button3, Gtk.PositionType.RIGHT, 2, 1)
+ grid.attach(button5, 1, 2, 1, 1)
+ grid.attach_next_to(button6, button5, Gtk.PositionType.RIGHT, 1, 1)
+
+ self.set_child(grid)
+
+
+def on_activate(app):
+ # Create window
+ win = GridWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/examples/layout_headerbar.py b/docs/tutorials/gtk4/examples/layout_headerbar.py
new file mode 100644
index 0000000..08f7aff
--- /dev/null
+++ b/docs/tutorials/gtk4/examples/layout_headerbar.py
@@ -0,0 +1,30 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk
+
+
+class HeaderBarWindow(Gtk.ApplicationWindow):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, default_width=400, title='HeaderBar Example')
+
+ header_bar = Gtk.HeaderBar()
+ self.set_titlebar(header_bar)
+
+ button = Gtk.Button(label='Button')
+ header_bar.pack_start(button)
+
+ icon_button = Gtk.Button(icon_name='open-menu-symbolic')
+ header_bar.pack_end(icon_button)
+
+
+def on_activate(app):
+ # Create window
+ win = HeaderBarWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/examples/layout_listbox.py b/docs/tutorials/gtk4/examples/layout_listbox.py
new file mode 100644
index 0000000..2805e27
--- /dev/null
+++ b/docs/tutorials/gtk4/examples/layout_listbox.py
@@ -0,0 +1,100 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk
+
+
+class ListBoxRowWithData(Gtk.ListBoxRow):
+ def __init__(self, data):
+ super().__init__()
+ self.data = data
+ self.set_child(Gtk.Label(label=data))
+
+
+class ListBoxWindow(Gtk.ApplicationWindow):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, default_width=400, title='ListBox Demo')
+
+ # Main box of out window
+ box_outer = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=24)
+ box_outer.props.margin_start = 24
+ box_outer.props.margin_end = 24
+ box_outer.props.margin_top = 24
+ box_outer.props.margin_bottom = 24
+ self.set_child(box_outer)
+
+ # Let's create our first ListBox
+ listbox = Gtk.ListBox()
+ listbox.props.selection_mode = Gtk.SelectionMode.NONE
+ listbox.props.show_separators = True
+ box_outer.append(listbox)
+
+ # Let's create our first ListBoxRow
+ row = Gtk.ListBoxRow()
+ hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=24)
+ row.set_child(hbox) # We set the Box as the ListBoxRow child
+ vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
+ hbox.append(vbox)
+ label1 = Gtk.Label(label='Automatic Date & Time', xalign=0)
+ label2 = Gtk.Label(label='Requires internet access', xalign=0)
+ vbox.append(label1)
+ vbox.append(label2)
+
+ switch = Gtk.Switch()
+ switch.props.hexpand = (
+ True # Lets make the Switch expand to the window width
+ )
+ switch.props.halign = Gtk.Align.END # Horizontally aligned to the end
+ switch.props.valign = (
+ Gtk.Align.CENTER
+ ) # Vertically aligned to the center
+ hbox.append(switch)
+
+ listbox.append(row) # Add the row to the list
+
+ # Our second row. We will omit the ListBoxRow and directly append a Box
+ hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=24)
+ label = Gtk.Label(label='Enable Automatic Update', xalign=0)
+ check = Gtk.CheckButton()
+ check.props.hexpand = True
+ check.props.halign = Gtk.Align.END
+ hbox.append(label)
+ hbox.append(check)
+ listbox.append(hbox) # Add the second row to the list
+
+ # Let's create a second ListBox
+ listbox_2 = Gtk.ListBox()
+ box_outer.append(listbox_2)
+ items = 'This is a sorted ListBox Fail'.split()
+
+ # Populate the list
+ for item in items:
+ listbox_2.append(ListBoxRowWithData(item))
+
+ # Set sorting and filter functions
+ listbox_2.set_sort_func(self.sort_func)
+ listbox_2.set_filter_func(self.filter_func)
+
+ # Connect to "row-activated" signal
+ listbox_2.connect('row-activated', self.on_row_activated)
+
+ def sort_func(self, row_1, row_2):
+ return row_1.data.lower() > row_2.data.lower()
+
+ def filter_func(self, row):
+ return False if row.data == 'Fail' else True
+
+ def on_row_activated(self, _listbox, row):
+ print(row.data)
+
+
+def on_activate(app):
+ # Create window
+ win = ListBoxWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/examples/layout_notebook.py b/docs/tutorials/gtk4/examples/layout_notebook.py
new file mode 100644
index 0000000..0f09119
--- /dev/null
+++ b/docs/tutorials/gtk4/examples/layout_notebook.py
@@ -0,0 +1,32 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk
+
+
+class NotebookWindow(Gtk.Window):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, title='Simple Notebook Example')
+
+ notebook = Gtk.Notebook()
+ self.set_child(notebook)
+
+ page1 = Gtk.Box()
+ page1.append(Gtk.Label(label='Default Page!'))
+ notebook.append_page(page1, Gtk.Label(label='Plain Title'))
+
+ page2 = Gtk.Box()
+ page2.append(Gtk.Label(label='A page with an image for a Title.'))
+ notebook.append_page(page2, Gtk.Image(icon_name='help-about'))
+
+
+def on_activate(app):
+ # Create window
+ win = NotebookWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/examples/layout_stack.py b/docs/tutorials/gtk4/examples/layout_stack.py
new file mode 100644
index 0000000..4027388
--- /dev/null
+++ b/docs/tutorials/gtk4/examples/layout_stack.py
@@ -0,0 +1,50 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk, GObject
+
+
+class StackWindow(Gtk.ApplicationWindow):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, title='Stack Demo')
+
+ self.set_default_size(300, 250)
+
+ header = Gtk.HeaderBar()
+ self.set_titlebar(header)
+
+ stack = Gtk.Stack()
+ stack.props.transition_type = Gtk.StackTransitionType.SLIDE_LEFT_RIGHT
+ stack.props.transition_duration = 1000
+ self.set_child(stack)
+
+ checkbutton = Gtk.CheckButton(label='Click me!')
+ checkbutton.props.hexpand = True
+ checkbutton.props.halign = Gtk.Align.CENTER
+ page1 = stack.add_titled(checkbutton, 'check', 'Check Button')
+ checkbutton.bind_property(
+ 'active', page1, 'needs-attention', GObject.BindingFlags.DEFAULT
+ )
+
+ label = Gtk.Label()
+ label.set_markup('A fancy label')
+ stack.add_titled(label, 'label', 'A label')
+
+ stack_switcher = Gtk.StackSwitcher()
+ stack_switcher.set_stack(stack)
+ header.set_title_widget(stack_switcher)
+
+ # Let's start in the second page
+ stack.set_visible_child_name('label')
+
+
+def on_activate(app):
+ # Create window
+ win = StackWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/examples/popover.py b/docs/tutorials/gtk4/examples/popover.py
new file mode 100644
index 0000000..a17b159
--- /dev/null
+++ b/docs/tutorials/gtk4/examples/popover.py
@@ -0,0 +1,46 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk
+
+
+class PopoverWindow(Gtk.ApplicationWindow):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, title='Popover Demo')
+
+ self.set_default_size(300, 200)
+
+ box = Gtk.Box(spacing=6, orientation=Gtk.Orientation.VERTICAL)
+ box.props.halign = box.props.valign = Gtk.Align.CENTER
+ self.set_child(box)
+
+ popover = Gtk.Popover()
+ popover_box = Gtk.Box()
+ popover_box.append(Gtk.Label(label='Item'))
+ popover.set_child(popover_box)
+
+ button = Gtk.MenuButton(label='Click Me', popover=popover)
+ box.append(button)
+
+ button2 = Gtk.Button(label='Click Me 2')
+ button2.connect('clicked', self.on_button_clicked)
+ box.append(button2)
+
+ self.popover2 = Gtk.Popover()
+ self.popover2.set_child(Gtk.Label(label='Another Popup!'))
+ self.popover2.set_parent(button2)
+ self.popover2.props.position = Gtk.PositionType.LEFT
+
+ def on_button_clicked(self, _button):
+ self.popover2.popup()
+
+
+def on_activate(app):
+ win = PopoverWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/examples/popover_menu.py b/docs/tutorials/gtk4/examples/popover_menu.py
new file mode 100644
index 0000000..451eb5c
--- /dev/null
+++ b/docs/tutorials/gtk4/examples/popover_menu.py
@@ -0,0 +1,76 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gio, Gtk
+
+# This would typically be its own file
+MENU_XML = """
+
+
+
+
+"""
+
+
+class AppWindow(Gtk.ApplicationWindow):
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+
+ self.set_default_size(300, 200)
+
+ headerbar = Gtk.HeaderBar()
+ self.set_titlebar(headerbar)
+
+ builder = Gtk.Builder.new_from_string(MENU_XML, -1)
+ menu_model = builder.get_object('app-menu')
+
+ button = Gtk.MenuButton(menu_model=menu_model)
+ headerbar.pack_end(button)
+
+
+class Application(Gtk.Application):
+ def __init__(self, **kwargs):
+ super().__init__(application_id='com.example.App', **kwargs)
+ self.window = None
+
+ def do_startup(self):
+ Gtk.Application.do_startup(self)
+
+ action = Gio.SimpleAction(name='about')
+ action.connect('activate', self.on_about)
+ self.add_action(action)
+
+ action = Gio.SimpleAction(name='quit')
+ action.connect('activate', self.on_quit)
+ self.add_action(action)
+
+ def do_activate(self):
+ # We only allow a single window and raise any existing ones
+ if not self.window:
+ # Windows are associated with the application
+ # when the last one is closed the application shuts down
+ self.window = AppWindow(application=self, title='Main Window')
+
+ self.window.present()
+
+ def on_about(self, action, param):
+ about_dialog = Gtk.AboutDialog(transient_for=self.window, modal=True)
+ about_dialog.present()
+
+ def on_quit(self, action, param):
+ self.quit()
+
+
+app = Application()
+app.run(None)
diff --git a/docs/tutorials/gtk4/examples/simple_example.py b/docs/tutorials/gtk4/examples/simple_example.py
new file mode 100644
index 0000000..728f2c3
--- /dev/null
+++ b/docs/tutorials/gtk4/examples/simple_example.py
@@ -0,0 +1,18 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk
+
+
+def on_activate(app):
+ # Create window
+ win = Gtk.ApplicationWindow(application=app)
+ win.present()
+
+
+# Create a new application
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+# Run the application
+app.run(None)
diff --git a/docs/tutorials/gtk4/examples/textview.py b/docs/tutorials/gtk4/examples/textview.py
new file mode 100644
index 0000000..c62c386
--- /dev/null
+++ b/docs/tutorials/gtk4/examples/textview.py
@@ -0,0 +1,237 @@
+import gi
+
+gi.require_version('Gtk', '4.0')
+from gi.repository import Gtk, Pango
+
+
+class SearchDialog(Gtk.Window):
+ def __init__(self, parent):
+ super().__init__(title='Search', transient_for=parent)
+
+ box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
+ self.set_child(box)
+
+ label = Gtk.Label(label='Insert text you want to search for:')
+ box.append(label)
+
+ self.entry = Gtk.Entry()
+ box.append(self.entry)
+
+ self.button = Gtk.Button(label='Find')
+ box.append(self.button)
+
+
+class TextViewWindow(Gtk.ApplicationWindow):
+ def __init__(self, **kargs):
+ super().__init__(**kargs, title='TextView Demo')
+
+ self.set_default_size(500, 400)
+
+ self.box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
+ self.set_child(self.box)
+
+ self.create_textview()
+ self.create_toolbar()
+ self.create_buttons()
+
+ def create_toolbar(self):
+ toolbar = Gtk.Box(spacing=6)
+ toolbar.props.margin_top = 6
+ toolbar.props.margin_start = 6
+ toolbar.props.margin_end = 6
+ self.box.prepend(toolbar)
+
+ button_bold = Gtk.Button(icon_name='format-text-bold-symbolic')
+ toolbar.append(button_bold)
+
+ button_italic = Gtk.Button(icon_name='format-text-italic-symbolic')
+ toolbar.append(button_italic)
+
+ button_underline = Gtk.Button(
+ icon_name='format-text-underline-symbolic'
+ )
+ toolbar.append(button_underline)
+
+ button_bold.connect('clicked', self.on_button_clicked, self.tag_bold)
+ button_italic.connect(
+ 'clicked', self.on_button_clicked, self.tag_italic
+ )
+ button_underline.connect(
+ 'clicked', self.on_button_clicked, self.tag_underline
+ )
+
+ toolbar.append(Gtk.Separator())
+
+ justifyleft = Gtk.ToggleButton(
+ icon_name='format-justify-left-symbolic'
+ )
+ toolbar.append(justifyleft)
+
+ justifycenter = Gtk.ToggleButton(
+ icon_name='format-justify-center-symbolic'
+ )
+ justifycenter.set_group(justifyleft)
+ toolbar.append(justifycenter)
+
+ justifyright = Gtk.ToggleButton(
+ icon_name='format-justify-right-symbolic'
+ )
+ justifyright.set_group(justifyleft)
+ toolbar.append(justifyright)
+
+ justifyfill = Gtk.ToggleButton(
+ icon_name='format-justify-fill-symbolic'
+ )
+ justifyfill.set_group(justifyleft)
+ toolbar.append(justifyfill)
+
+ justifyleft.connect(
+ 'toggled', self.on_justify_toggled, Gtk.Justification.LEFT
+ )
+ justifycenter.connect(
+ 'toggled', self.on_justify_toggled, Gtk.Justification.CENTER
+ )
+ justifyright.connect(
+ 'toggled', self.on_justify_toggled, Gtk.Justification.RIGHT
+ )
+ justifyfill.connect(
+ 'toggled', self.on_justify_toggled, Gtk.Justification.FILL
+ )
+
+ toolbar.append(Gtk.Separator())
+
+ button_clear = Gtk.Button(icon_name='edit-clear-symbolic')
+ button_clear.connect('clicked', self.on_clear_clicked)
+ toolbar.append(button_clear)
+
+ toolbar.append(Gtk.Separator())
+
+ button_search = Gtk.Button(icon_name='system-search-symbolic')
+ button_search.connect('clicked', self.on_search_clicked)
+ toolbar.append(button_search)
+
+ def create_textview(self):
+ scrolledwindow = Gtk.ScrolledWindow()
+ scrolledwindow.props.hexpand = True
+ scrolledwindow.props.vexpand = True
+ self.box.append(scrolledwindow)
+
+ self.textview = Gtk.TextView()
+ self.textbuffer = self.textview.get_buffer()
+ self.textbuffer.set_text(
+ 'This is some text inside of a Gtk.TextView. ' +
+ 'Select text and click one of the buttons "bold", "italic", ' +
+ 'or "underline" to modify the text accordingly.'
+ )
+ scrolledwindow.set_child(self.textview)
+
+ self.tag_bold = self.textbuffer.create_tag(
+ 'bold', weight=Pango.Weight.BOLD
+ )
+ self.tag_italic = self.textbuffer.create_tag(
+ 'italic', style=Pango.Style.ITALIC
+ )
+ self.tag_underline = self.textbuffer.create_tag(
+ 'underline', underline=Pango.Underline.SINGLE
+ )
+ self.tag_found = self.textbuffer.create_tag(
+ 'found', background='yellow'
+ )
+
+ def create_buttons(self):
+ grid = Gtk.Grid()
+ self.box.append(grid)
+
+ check_editable = Gtk.CheckButton(label='Editable')
+ check_editable.props.active = True
+ check_editable.connect('toggled', self.on_editable_toggled)
+ grid.attach(check_editable, 0, 0, 1, 1)
+
+ check_cursor = Gtk.CheckButton(label='Cursor Visible')
+ check_cursor.props.active = True
+ check_editable.connect('toggled', self.on_cursor_toggled)
+ grid.attach_next_to(
+ check_cursor, check_editable, Gtk.PositionType.RIGHT, 1, 1
+ )
+
+ radio_wrapnone = Gtk.CheckButton(label='No Wrapping')
+ radio_wrapnone.props.active = True
+ grid.attach(radio_wrapnone, 0, 1, 1, 1)
+
+ radio_wrapchar = Gtk.CheckButton(label='Character Wrapping')
+ radio_wrapchar.set_group(radio_wrapnone)
+ grid.attach_next_to(
+ radio_wrapchar, radio_wrapnone, Gtk.PositionType.RIGHT, 1, 1
+ )
+
+ radio_wrapword = Gtk.CheckButton(label='Word Wrapping')
+ radio_wrapword.set_group(radio_wrapnone)
+ grid.attach_next_to(
+ radio_wrapword, radio_wrapchar, Gtk.PositionType.RIGHT, 1, 1
+ )
+
+ radio_wrapnone.connect(
+ 'toggled', self.on_wrap_toggled, Gtk.WrapMode.NONE
+ )
+ radio_wrapchar.connect(
+ 'toggled', self.on_wrap_toggled, Gtk.WrapMode.CHAR
+ )
+ radio_wrapword.connect(
+ 'toggled', self.on_wrap_toggled, Gtk.WrapMode.WORD
+ )
+
+ def on_button_clicked(self, _widget, tag):
+ bounds = self.textbuffer.get_selection_bounds()
+ if len(bounds) != 0:
+ start, end = bounds
+ self.textbuffer.apply_tag(tag, start, end)
+
+ def on_clear_clicked(self, _widget):
+ start = self.textbuffer.get_start_iter()
+ end = self.textbuffer.get_end_iter()
+ self.textbuffer.remove_all_tags(start, end)
+
+ def on_editable_toggled(self, widget):
+ self.textview.props.editable = widget.props.active
+
+ def on_cursor_toggled(self, widget):
+ self.textview.props.cursor_visible = widget.props.active
+
+ def on_wrap_toggled(self, _widget, mode):
+ self.textview.props.wrap_mode = mode
+
+ def on_justify_toggled(self, _widget, justification):
+ self.textview.props.justification = justification
+
+ def on_search_clicked(self, _widget):
+ self.search_dialog = SearchDialog(self)
+ self.search_dialog.button.connect('clicked', self.on_find_clicked)
+ self.search_dialog.present()
+
+ def on_find_clicked(self, _button):
+ cursor_mark = self.textbuffer.get_insert()
+ start = self.textbuffer.get_iter_at_mark(cursor_mark)
+ if start.get_offset() == self.textbuffer.get_char_count():
+ start = self.textbuffer.get_start_iter()
+
+ self.search_and_mark(self.search_dialog.entry.get_text(), start)
+
+ def search_and_mark(self, text, start):
+ end = self.textbuffer.get_end_iter()
+ match = start.forward_search(text, 0, end)
+
+ if match is not None:
+ match_start, match_end = match
+ self.textbuffer.apply_tag(self.tag_found, match_start, match_end)
+ self.search_and_mark(text, match_end)
+
+
+def on_activate(app):
+ win = TextViewWindow(application=app)
+ win.present()
+
+
+app = Gtk.Application(application_id='com.example.App')
+app.connect('activate', on_activate)
+
+app.run(None)
diff --git a/docs/tutorials/gtk4/images/application.png b/docs/tutorials/gtk4/images/application.png
new file mode 100644
index 0000000..17bed6f
Binary files /dev/null and b/docs/tutorials/gtk4/images/application.png differ
diff --git a/docs/tutorials/gtk4/images/basic_example.png b/docs/tutorials/gtk4/images/basic_example.png
new file mode 100644
index 0000000..922b5c4
Binary files /dev/null and b/docs/tutorials/gtk4/images/basic_example.png differ
diff --git a/docs/tutorials/gtk4/images/clipboard.png b/docs/tutorials/gtk4/images/clipboard.png
new file mode 100644
index 0000000..8b3b6ee
Binary files /dev/null and b/docs/tutorials/gtk4/images/clipboard.png differ
diff --git a/docs/tutorials/gtk4/images/drag_and_drop.png b/docs/tutorials/gtk4/images/drag_and_drop.png
new file mode 100644
index 0000000..b3331cb
Binary files /dev/null and b/docs/tutorials/gtk4/images/drag_and_drop.png differ
diff --git a/docs/tutorials/gtk4/images/extended_example.png b/docs/tutorials/gtk4/images/extended_example.png
new file mode 100644
index 0000000..cfe4d29
Binary files /dev/null and b/docs/tutorials/gtk4/images/extended_example.png differ
diff --git a/docs/tutorials/gtk4/images/layout_box.png b/docs/tutorials/gtk4/images/layout_box.png
new file mode 100644
index 0000000..8111baf
Binary files /dev/null and b/docs/tutorials/gtk4/images/layout_box.png differ
diff --git a/docs/tutorials/gtk4/images/layout_center.png b/docs/tutorials/gtk4/images/layout_center.png
new file mode 100644
index 0000000..73bacd0
Binary files /dev/null and b/docs/tutorials/gtk4/images/layout_center.png differ
diff --git a/docs/tutorials/gtk4/images/layout_flowbox.png b/docs/tutorials/gtk4/images/layout_flowbox.png
new file mode 100644
index 0000000..70f7ff1
Binary files /dev/null and b/docs/tutorials/gtk4/images/layout_flowbox.png differ
diff --git a/docs/tutorials/gtk4/images/layout_grid.png b/docs/tutorials/gtk4/images/layout_grid.png
new file mode 100644
index 0000000..bd4f4fb
Binary files /dev/null and b/docs/tutorials/gtk4/images/layout_grid.png differ
diff --git a/docs/tutorials/gtk4/images/layout_headerbar.png b/docs/tutorials/gtk4/images/layout_headerbar.png
new file mode 100644
index 0000000..3027a02
Binary files /dev/null and b/docs/tutorials/gtk4/images/layout_headerbar.png differ
diff --git a/docs/tutorials/gtk4/images/layout_listbox.png b/docs/tutorials/gtk4/images/layout_listbox.png
new file mode 100644
index 0000000..d0d6392
Binary files /dev/null and b/docs/tutorials/gtk4/images/layout_listbox.png differ
diff --git a/docs/tutorials/gtk4/images/layout_notebook.png b/docs/tutorials/gtk4/images/layout_notebook.png
new file mode 100644
index 0000000..ff5a0e8
Binary files /dev/null and b/docs/tutorials/gtk4/images/layout_notebook.png differ
diff --git a/docs/tutorials/gtk4/images/layout_stack.png b/docs/tutorials/gtk4/images/layout_stack.png
new file mode 100644
index 0000000..a58ccdb
Binary files /dev/null and b/docs/tutorials/gtk4/images/layout_stack.png differ
diff --git a/docs/tutorials/gtk4/images/popover.png b/docs/tutorials/gtk4/images/popover.png
new file mode 100644
index 0000000..c0f759a
Binary files /dev/null and b/docs/tutorials/gtk4/images/popover.png differ
diff --git a/docs/tutorials/gtk4/images/popover_menu.png b/docs/tutorials/gtk4/images/popover_menu.png
new file mode 100644
index 0000000..2947a80
Binary files /dev/null and b/docs/tutorials/gtk4/images/popover_menu.png differ
diff --git a/docs/tutorials/gtk4/images/textview.png b/docs/tutorials/gtk4/images/textview.png
new file mode 100644
index 0000000..353cf6e
Binary files /dev/null and b/docs/tutorials/gtk4/images/textview.png differ
diff --git a/docs/tutorials/gtk4/introduction.rst b/docs/tutorials/gtk4/introduction.rst
new file mode 100644
index 0000000..9c83d83
--- /dev/null
+++ b/docs/tutorials/gtk4/introduction.rst
@@ -0,0 +1,128 @@
+.. currentmodule:: gi.repository
+
+Getting Started
+===============
+
+This section will give you a first contact with GTK, explaining each line of
+code.
+
+.. seealso:: `Getting Started with GTK`_ in the GTK documentation.
+
+Basic Example
+-------------
+
+To start with our tutorial we create the simplest program possible.
+This program will create an empty 200 x 200 pixel window.
+
+.. image:: images/basic_example.png
+
+.. literalinclude:: examples/simple_example.py
+ :linenos:
+
+We will now explain each line of the example.
+
+.. literalinclude:: examples/simple_example.py
+ :lines: 1-4
+
+In the beginning, we have to import the Gtk module to be able to access GTK's
+classes and functions.
+Since a user's system can have multiple versions of GTK installed at the same,
+we want to make sure that when we import Gtk that it refers to GTK4
+and not any other version of the library, which is the purpose
+of the statement ``gi.require_version('Gtk', '4.0')``.
+
+.. literalinclude:: examples/simple_example.py
+ :lines: 14-15
+
+Now we create an application. The ``application_id`` argument is needed as
+method of identifying your application to the system, if you do not know what
+to set please :devdocs:`check this tutorial `.
+
+We are also connecting to the application's ``activate`` event, where we will
+create the window.
+
+.. literalinclude:: examples/simple_example.py
+ :lines: 7,9-10
+
+In the ``on_activate`` callback we will create an empty window, and then display
+it using the :meth:`Gtk.Window.present` method.
+
+.. literalinclude:: examples/simple_example.py
+ :lines: 18
+
+Finally, we start the application using the :meth:`Gio.Application.run` method.
+
+
+Minimal Example without GtkApplication
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+In GTK 4, if you don't want to use :class:`Gtk.Application` you can use this
+replacement that will iterate the default main loop until all windows have been
+closed:
+
+.. attention::
+ Doing this is only useful for very specific use cases like tests. For app
+ development you should always use :class:`Gtk.Application`.
+
+.. code:: python
+
+ import gi
+ gi.require_version('Gtk', '4.0')
+ from gi.repository import GLib, Gtk
+
+ win = Gtk.Window()
+ win.present()
+
+ while (len(Gtk.Window.get_toplevels()) > 0):
+ GLib.MainContext.default().iteration(True)
+
+.. _extended-example:
+
+Extended Example
+----------------
+
+For something a little more useful, here's the PyGObject version of the classic
+"Hello World" program.
+
+.. image:: images/extended_example.png
+
+.. literalinclude:: examples/extended_example.py
+ :linenos:
+
+This example differs from the simple example as we sub-class
+:class:`Gtk.ApplicationWindow` to define our own ``MyWindow`` class.
+
+.. seealso::
+ For more info about subclassing read
+ :doc:`GObject Subclassing `.
+
+.. literalinclude:: examples/extended_example.py
+ :lines: 7
+
+In the class's constructor we have to call the constructor of the super class.
+In addition, we tell it to set the value of the property title to *Hello World*.
+Note that we are also receiving and passing ``**kargs``, so we can redirect
+other arguments passed on ``MyWindow`` construction to the base class.
+
+.. literalinclude:: examples/extended_example.py
+ :lines: 8-9
+
+The next three lines are used to create a button widget, connect to its
+``clicked`` signal and add it as child to the top-level window.
+
+.. literalinclude:: examples/extended_example.py
+ :lines: 11-13
+
+Accordingly, the method `on_button_clicked` will be called if you click on
+the button. In this example we are using the method to print ``Hello World`` and
+calling the window :meth:`Gtk.Window.close` method to close the window.
+
+.. literalinclude:: examples/extended_example.py
+ :lines: 15-17
+
+The last block, outside of the class, is very similar to the simple example
+above, but instead of creating an instance of the generic
+:class:`Gtk.ApplicationWindow` or :class:`Gtk.Window` class, we create an
+instance of ``MyWindow``.
+
+.. _Getting Started with GTK: https://docs.gtk.org/gtk4/getting_started.html
diff --git a/docs/tutorials/gtk4/layout-widgets.rst b/docs/tutorials/gtk4/layout-widgets.rst
new file mode 100644
index 0000000..cb8a160
--- /dev/null
+++ b/docs/tutorials/gtk4/layout-widgets.rst
@@ -0,0 +1,292 @@
+.. currentmodule:: gi.repository
+
+Layout Containers
+=================
+
+While many GUI toolkits require you to precisely place widgets in a window,
+using absolute positioning, GTK uses a different approach.
+Rather than specifying the position and size of each widget in the window,
+you can arrange your widgets in rows, columns, and/or tables.
+The size of your window can be determined automatically, based on the sizes
+of the widgets it contains.
+And the sizes of the widgets are, in turn, determined by the amount of text
+they contain, or the minimum and maximum sizes that you specify, and/or how
+you have requested that the available space should be shared between sets of
+widgets. You can perfect your layout by specifying padding distance and
+centering values for each of your widgets. GTK then uses all this information
+to resize and reposition everything sensibly and smoothly when the user
+manipulates the window.
+
+GTK widgets can parent other widgets hierarchically, and the way those widgets
+are displayed depend on the :class:`Gtk.LayoutManager` set in the
+:attr:`Gtk.Widget.props.layout_manager` property. For ease of use, GTK provides
+"pre made" containers that have default layout managers for different needs.
+Most of these containers implement the :class:`Gtk.Orientable` interface, it
+allows to set the widget orientation using
+:attr:`Gtk.Orientable.props.orientation`, you can either set
+:attr:`Gtk.Orientation.HORIZONTAL` or :attr:`Gtk.Orientation.VERTICAL`.
+
+Some containers / layout managers like :class:`Gtk.Box` allow you to influence
+the allocation of a child using the :attr:`Gtk.Widget.props.halign`,
+:attr:`Gtk.Widget.props.valign`, :attr:`Gtk.Widget.props.hexpand` and
+:attr:`Gtk.Widget.props.vexpand` properties.
+
+The main container widgets are:
+
+* :class:`Gtk.Box`
+* :class:`Gtk.CenterBox`
+* :class:`Gtk.HeaderBar`
+* :class:`Gtk.Grid`
+* :class:`Gtk.ListBox`
+* :class:`Gtk.FlowBox`
+* :class:`Gtk.Stack`
+* :class:`Gtk.Notebook`
+
+We are looking into each one in the following sections.
+
+
+Boxes
+-----
+Boxes are invisible containers into which we can pack our widgets.
+When packing widgets into a horizontal box, the objects are inserted
+horizontally from left to right or right to left depending on whether
+:meth:`Gtk.Box.prepend` or :meth:`Gtk.Box.append` is used.
+You can also use the :meth:`Gtk.Box.insert_child_after` or
+:meth:`Gtk.Box.reorder_child_after` methods to insert a widget on a specific
+position.
+In a vertical box, widgets are packed from top to bottom or vice versa.
+You may use any combination of boxes inside or beside other boxes to create
+the desired effect.
+
+Example
+^^^^^^^
+
+Let's take a look at a slightly modified version of
+the :ref:`extended-example` with two buttons.
+
+.. image:: images/layout_box.png
+
+.. literalinclude:: examples/layout_box.py
+ :linenos:
+
+First, we create a horizontally orientated box container where 6 pixels are
+placed between children. This box becomes the child of the top-level window.
+
+.. literalinclude:: examples/layout_box.py
+ :lines: 11-12
+
+Subsequently, we add two different buttons to the box container.
+
+.. literalinclude:: examples/layout_box.py
+ :lines: 14-21
+
+
+CenterBox
+---------
+
+:class:`Gtk.CenterBox` arranges three children in a row or a column depending on
+its orientation, keeping the middle child centered as well as possible.
+
+To add children you use :meth:`Gtk.CenterBox.set_start_widget`,
+:meth:`Gtk.CenterBox.set_center_widget`, and :meth:`Gtk.CenterBox.set_end_widget`.
+
+Example
+^^^^^^^
+
+.. image:: images/layout_center.png
+
+.. literalinclude:: examples/layout_center.py
+ :linenos:
+
+
+HeaderBar
+---------
+A :class:`Gtk.HeaderBar` is similar to a horizontal :class:`Gtk.CenterBox`, it
+allows to place children at the start or the end. In addition, it allows a title
+to be displayed. The title will be centered with respect to the width of the box,
+even if the children at either side take up different amounts of space.
+
+:class:`Gtk.HeaderBar` is designed to be used as a window titlebar.
+This means that it can show typical window frame controls, such as minimize,
+maximize and close buttons, or the window icon.
+It is also draggable, meaning that you can move the parent window from it.
+You can use the :meth:`Gtk.Window.set_titlebar` method to set it as so.
+
+To add children you use :meth:`Gtk.HeaderBar.pack_start`,
+:meth:`Gtk.HeaderBar.pack_end`, and :meth:`Gtk.HeaderBar.set_title_widget` for
+the center one. By default if no ``title_widget`` is set
+it will have a label with the window's :attr:`Gtk.Window.props.title`.
+
+Example
+^^^^^^^
+
+.. image:: images/layout_headerbar.png
+
+.. literalinclude:: examples/layout_headerbar.py
+ :linenos:
+
+
+Grid
+----
+:class:`Gtk.Grid` is a container which arranges its child widgets in rows and
+columns, but you do not need to specify the dimensions in the constructor.
+Children are added using :meth:`Gtk.Grid.attach`. They can span multiple rows or
+columns. The :meth:`Gtk.Grid.attach` method takes five parameters:
+
+1. The ``child`` parameter is the :class:`Gtk.Widget` to add.
+2. ``left`` is the column number to attach the left side of ``child`` to.
+3. ``top`` indicates the row number to attach the top side of ``child`` to.
+4. ``width`` and ``height`` indicate the number of columns that the ``child``
+ will span, and the number of rows that the ``child`` will span, respectively.
+
+It is also possible to add a child next to an existing child, using
+:meth:`Gtk.Grid.attach_next_to`, which also takes five parameters:
+
+1. ``child`` is the :class:`Gtk.Widget` to add, as above.
+2. ``sibling`` is an existing child widget of ``self`` (a :class:`Gtk.Grid` instance)
+ or ``None``. The ``child`` widget will be placed next to ``sibling``, or
+ if ``sibling`` is ``None``, at the beginning or end of the grid.
+3. ``side`` is a :class:`Gtk.PositionType` indicating the side of
+ ``sibling`` that ``child`` is positioned next to.
+4. ``width`` and ``height`` indicate the number of columns and rows
+ the ``child`` widget will span, respectively.
+
+Example
+^^^^^^^
+
+.. image:: images/layout_grid.png
+
+.. literalinclude:: examples/layout_grid.py
+ :linenos:
+
+
+ListBox
+-------
+
+A :class:`Gtk.ListBox` is a vertical container that contains :class:`Gtk.ListBoxRow`
+children. These rows can be dynamically sorted and filtered, and headers can be
+added dynamically depending on the row content. It also allows keyboard and
+mouse navigation and selection like a typical list.
+
+Although a :class:`Gtk.ListBox` must have only :class:`Gtk.ListBoxRow` children,
+you can add any kind of widget to it via :meth:`Gtk.ListBox.append` or
+:meth:`Gtk.ListBox.insert` and a :class:`Gtk.ListBoxRow` widget will
+automatically be inserted between the list and the widget.
+
+:class:`Gtk.ListBox` allows activating and selecting its children.
+Selection can be configured with :attr:`Gtk.ListBox.props.selection_mode`,
+selection modes are :attr:`Gtk.SelectionMode.NONE` (not selection at all),
+:attr:`Gtk.SelectionMode.SINGLE` (one or none elements can be selected),
+:attr:`Gtk.SelectionMode.BROWSE` (user can't deselect a currently selected
+element except by selecting another element) and
+:attr:`Gtk.SelectionMode.MULTIPLE` (any number of elements may be selected).
+
+It will emit the :func:`row-activated `
+signal when a row is activated in any form, and
+:func:`row-selected ` when a row is selected.
+
+Example
+^^^^^^^
+
+.. image:: images/layout_listbox.png
+
+.. literalinclude:: examples/layout_listbox.py
+ :linenos:
+
+
+FlowBox
+-------
+
+A :class:`Gtk.FlowBox` is a container that positions child widgets in sequence
+according to its orientation.
+
+For instance, with the horizontal orientation, the widgets will be arranged
+from left to right, starting a new row under the previous row when necessary.
+Reducing the width in this case will require more rows, so a larger height
+will be requested.
+
+Likewise, with the vertical orientation, the widgets will be arranged from top
+to bottom, starting a new column to the right when necessary. Reducing the
+height will require more columns, so a larger width will be requested.
+
+:class:`Gtk.FlowBox` behaves similar to :class:`Gtk.ListBox`, we could say that
+is its "grid" counterpart. Just like :class:`Gtk.ListBox`, the children of a
+:class:`Gtk.FlowBox` can be dynamically sorted and filtered, and also activated
+and selected.
+
+Although a :class:`Gtk.FlowBox` must have only :class:`Gtk.FlowBoxChild`
+children, you can add any kind of widget to it via
+:meth:`Gtk.FlowBox.append` or :meth:`Gtk.FlowBox.insert`, and a
+:class:`Gtk.FlowBoxChild` widget will automatically be inserted between the box
+and the widget.
+
+Example
+^^^^^^^
+
+.. image:: images/layout_flowbox.png
+
+.. literalinclude:: examples/layout_flowbox.py
+ :linenos:
+
+Stack and StackSwitcher
+-----------------------
+
+A :class:`Gtk.Stack` is a container which only shows one of its children at a
+time. In contrast to :class:`Gtk.Notebook`, :class:`Gtk.Stack` does not provide
+a means for users to change the visible child. Instead, the
+:class:`Gtk.StackSwitcher` widget can be used with :class:`Gtk.Stack` to
+provide this functionality.
+
+Transitions between pages can be animated as slides or fades. This can be
+controlled with :attr:`Gtk.Stack.props.transition_type`. These animations
+respect the ``gtk-enable-animations`` setting.
+
+Transition speed can be adjusted with :attr:`Gtk.Stack.props.transition_duration`.
+
+The :class:`Gtk.StackSwitcher` widget acts as a controller for a
+:class:`Gtk.Stack`; it shows a row of buttons to switch between the various
+pages of the associated stack widget.
+
+:class:`Gtk.Stack` uses the auxiliary :class:`Gtk.StackPage` object.
+:class:`Gtk.Stack` will return a :class:`Gtk.StackPage` every time you add a new
+children, either with :meth:`Gtk.Stack.add_child`, :meth:`Gtk.Stack.add_named`
+or :meth:`Gtk.Stack.add_titled`.
+:class:`Gtk.StackPage` holds important properties for the stack's children, like
+the name, the title to display, or if the page needs attention, then this data
+can be used for example by :class:`Gtk.StackSwitcher`.
+
+It is possible to associate multiple :class:`Gtk.StackSwitcher` widgets with
+the same :class:`Gtk.Stack` widget.
+
+Example
+^^^^^^^
+
+.. image:: images/layout_stack.png
+
+.. literalinclude:: examples/layout_stack.py
+ :linenos:
+
+Notebook
+--------
+
+The :class:`Gtk.Notebook` is a container whose children are pages switched
+between using tabs.
+
+There are many configuration options for GtkNotebook. Among other things, you
+can choose on which edge the tabs appear (see :meth:`Gtk.Notebook.set_tab_pos`),
+whether, if there are too many tabs to fit the notebook should be made bigger or
+scrolling arrows added (see :meth:`Gtk.Notebook.set_scrollable`), and whether
+there will be a popup menu allowing the users to switch pages (see
+:meth:`Gtk.Notebook.popup_enable`, :meth:`Gtk.Notebook.popup_disable`).
+
+You can add children with :meth:`Gtk.Notebook.append_page`, it takes two widgets,
+the first is the widget to show as a page, and the second is the widget to show
+as the tab content.
+
+Example
+^^^^^^^
+
+.. image:: images/layout_notebook.png
+
+.. literalinclude:: examples/layout_notebook.py
+ :linenos:
diff --git a/docs/tutorials/gtk4/popovers.rst b/docs/tutorials/gtk4/popovers.rst
new file mode 100644
index 0000000..e255a55
--- /dev/null
+++ b/docs/tutorials/gtk4/popovers.rst
@@ -0,0 +1,57 @@
+.. currentmodule:: gi.repository
+
+Popovers
+========
+
+The :class:`Gtk.Popover` is an special kind of window used for displaying
+additional information and is often used with button menus and context menus.
+Popovers are attached to a parent widget and point to it.
+It's position can be configured with :attr:`Gtk.Popover.props.position`.
+:class:`Gtk.Popover` shows an arrow to visually connect where it points to,
+this can be disabled setting :attr:`Gtk.Popover.props.has_arrow` to ``False``.
+
+A :class:`Gtk.Popover` can be opened using :meth:`Gtk.Popover.popup` and hidden
+with :meth:`Gtk.Widget.hide`.
+
+GTK also provides :class:`Gtk.MenuButton`, it's an special button that can show
+and hide a :class:`Gtk.Popover` attached to it using
+:attr:`Gtk.MenuButton.props.popover`.
+
+Custom Popover
+--------------
+
+A child widget can be added to a popover using :meth:`Gtk.Popover.set_child`.
+The parent of the popover can be set using :meth:`Gtk.Widget.set_parent`.
+
+Example
+^^^^^^^
+
+.. image:: images/popover.png
+
+.. literalinclude:: examples/popover.py
+ :linenos:
+
+
+Menu Popover
+------------
+
+GTK also has :class:`Gtk.PopoverMenu`, it's a :class:`Gtk.Popover` subclass
+designed to display a menu model.
+
+A popover can be created from a :class:`Gio.MenuModel` using
+:meth:`Gtk.PopoverMenu.new_from_model` and can be changed after creation with
+:attr:`Gtk.PopoverMenu.props.menu_model`.
+
+:class:`Gtk.MenuButton` also can construct a :class:`Gtk.PopoverMenu` passing it
+a :class:`Gio.MenuModel` to :attr:`Gtk.MenuButton.props.menu_model`.
+
+.. seealso::
+ In :doc:`GTK Application ` we also showed examples of menu
+ models.
+
+Example
+^^^^^^^
+
+.. image:: images/popover_menu.png
+
+.. literalinclude:: examples/popover_menu.py
diff --git a/docs/tutorials/gtk4/textview.rst b/docs/tutorials/gtk4/textview.rst
new file mode 100644
index 0000000..50ef848
--- /dev/null
+++ b/docs/tutorials/gtk4/textview.rst
@@ -0,0 +1,137 @@
+.. currentmodule:: gi.repository
+
+Text View
+=========
+
+The :class:`Gtk.TextView` widget can be used to display and edit large amounts
+of formatted text. Like the :class:`Gtk.ListView`, it has a model/view
+design.
+In this case the :class:`Gtk.TextBuffer` is the model which represents the text
+being edited. This allows two or more :class:`Gtk.TextView` widgets to share the
+same :class:`Gtk.TextBuffer`, and allows those text buffers to be displayed
+slightly differently. Or you could maintain several text buffers and choose to
+display each one at different times in the same :class:`Gtk.TextView` widget.
+
+.. seealso:: `Text Widget Overview`_ in the GTK documentation.
+
+The View
+--------
+
+The :class:`Gtk.TextView` is the frontend with which the user can add, edit and
+delete textual data. They are commonly used to edit multiple lines of text.
+When creating a :class:`Gtk.TextView` it contains its own default
+:class:`Gtk.TextBuffer`, which is kept in the :attr:`Gtk.TextView.props.buffer`
+property.
+
+By default, text can be added, edited and removed from the :class:`Gtk.TextView`.
+You can disable this by changing :attr:`Gtk.TextView.props.editable`.
+If the text is not editable, you usually want to hide the text cursor with
+:attr:`Gtk.TextView.props.cursor_visible` as well.
+In some cases it may be useful to set the justification of the text with
+:attr:`Gtk.TextView.props.justification`.
+The text can be displayed at the left edge, (:attr:`Gtk.Justification.LEFT`),
+at the right edge (:attr:`Gtk.Justification.RIGHT`), centered
+(:attr:`Gtk.Justification.CENTER`), or distributed across the complete
+width (:attr:`Gtk.Justification.FILL`).
+
+Another default setting of the :class:`Gtk.TextView` widget is long lines of
+text will continue horizontally until a break is entered. To wrap the text and
+prevent it going off the edges of the screen set
+:attr:`Gtk.TextView.props.wrap_mode` similar to :doc:`/tutorials/gtk4/display-widgets/label`.
+
+The Model
+---------
+
+The :class:`Gtk.TextBuffer` is the core of the :class:`Gtk.TextView` widget, and
+is used to hold whatever text is being displayed in the :class:`Gtk.TextView`.
+Setting and retrieving the contents is possible with
+:attr:`Gtk.TextBuffer.props.text`.
+However, most text manipulation is accomplished with *iterators*, represented by
+a :class:`Gtk.TextIter`. An iterator represents a position between two
+characters in the text buffer.
+Iterators are not valid indefinitely; whenever the buffer is modified in a way
+that affects the contents of the buffer, all outstanding iterators become
+invalid.
+
+Because of this, iterators can't be used to preserve positions across buffer
+modifications. To preserve a position, use :class:`Gtk.TextMark`.
+A text buffer contains two built-in marks; an "insert" mark (which is the
+position of the cursor) and the "selection_bound" mark. Both of them can be
+retrieved using :meth:`Gtk.TextBuffer.get_insert` and
+:meth:`Gtk.TextBuffer.get_selection_bound`, respectively.
+By default, the location of a :class:`Gtk.TextMark` is not shown.
+This can be changed by calling :meth:`Gtk.TextMark.set_visible`.
+
+Many methods exist to retrieve a :class:`Gtk.TextIter`. For instance,
+:meth:`Gtk.TextBuffer.get_start_iter` returns an iterator pointing to the first
+position in the text buffer, whereas :meth:`Gtk.TextBuffer.get_end_iter` returns
+an iterator pointing past the last valid character. Retrieving the bounds of
+the selected text can be achieved by calling
+:meth:`Gtk.TextBuffer.get_selection_bounds`.
+
+To insert text at a specific position use :meth:`Gtk.TextBuffer.insert`.
+Another useful method is :meth:`Gtk.TextBuffer.insert_at_cursor` which inserts
+text wherever the cursor may be currently positioned. To remove portions of
+the text buffer use :meth:`Gtk.TextBuffer.delete`.
+
+In addition, :class:`Gtk.TextIter` can be used to locate textual matches in the
+buffer using :meth:`Gtk.TextIter.forward_search` and
+:meth:`Gtk.TextIter.backward_search`.
+The start and end iters are used as the starting point of the search and move
+forwards/backwards depending on requirements.
+
+Tags
+----
+
+Text in a buffer can be marked with tags.
+A tag is an attribute that can be applied to some range of text. For example, a
+tag might be called "bold" and make the text inside the tag bold.
+However, the tag concept is more general than that; tags don't have to affect
+appearance.
+They can instead affect the behavior of mouse and key presses, "lock" a range of
+text so the user can't edit it, or countless other things. A tag is represented
+by a :class:`Gtk.TextTag` object.
+One :class:`Gtk.TextTag` can be applied to any number of text ranges in any
+number of buffers.
+
+Each tag is stored in a :class:`Gtk.TextTagTable`.
+A tag table defines a set of tags that can be used together.
+Each buffer has one tag table associated with it; only tags from that tag table
+can be used with the buffer.
+A single tag table can be shared between multiple buffers, however.
+
+To specify that some text in the buffer should have specific formatting, you
+must define a tag to hold that formatting information, and then apply that tag
+to the region of text using :meth:`Gtk.TextBuffer.create_tag` and
+:meth:`Gtk.TextBuffer.apply_tag`:
+
+.. code:: python
+
+ tag = textbuffer.create_tag('orange_bg', background='orange')
+ textbuffer.apply_tag(tag, start_iter, end_iter)
+
+The following are some of the common styles applied to text:
+
+* Background colour ("background" property)
+* Foreground colour ("foreground" property)
+* Underline ("underline" property)
+* Bold ("weight" property)
+* Italics ("style" property)
+* Strikethrough ("strikethrough" property)
+* Justification ("justification" property)
+* Size ("size" and "size-points" properties)
+* Text wrapping ("wrap-mode" property)
+
+You can also delete particular tags later using :meth:`Gtk.TextBuffer.remove_tag`
+or delete all tags in a given region by calling :meth:`Gtk.TextBuffer.remove_all_tags`.
+
+Example
+-------
+
+.. image:: images/textview.png
+
+.. literalinclude:: examples/textview.py
+ :linenos:
+
+
+.. _Text Widget Overview: https://docs.gtk.org/gtk4/section-text-widget.html
diff --git a/docs/tutorials/index.rst b/docs/tutorials/index.rst
new file mode 100644
index 0000000..d6b37a6
--- /dev/null
+++ b/docs/tutorials/index.rst
@@ -0,0 +1,68 @@
+=========
+Tutorials
+=========
+
+These tutorials give an introduction to writing GTK/GNOME applications in
+Python.
+
+Prior to working through these tutorials, it is recommended that you have a
+reasonable grasp of the Python programming language. It is necessary for you to
+know how to create and run Python files, understand basic interpreter errors,
+and work with strings, integers, floats and boolean values. For the more
+advanced parts of these examples, good knowledge of lists and tuples will be
+needed.
+
+Although here we try to describe the most important classes and methods from
+GObject based libraries like GTK, it is not supposed to serve as an API
+reference. Please refer to the :ref:`api-references` list where you will
+find a detailed description of the API for each library. Also there's a
+`Python-specific reference `_
+available.
+
+.. note::
+ Our tutorial list is still not as extensive as we would like, so if you
+ have experience with PyGObject, contributing docs is a great way to help.
+
+ Some areas that could use your help: libadwaita components, GLib and Gio
+ features.
+
+
+.. _api-references:
+
+API References
+--------------
+
+* `GObject `_
+* `Gtk 4 `_
+* `Gdk 4 `_
+* `Gio `_
+* `GLib `_
+* `Adwaita `_
+* `Python-specific references `_
+
+Other Resources
+---------------
+
+* The :devdocs:`GNOME Developer Documentation `
+ has some tutorials that include Python examples.
+
+
+.. toctree::
+ :maxdepth: 1
+ :hidden:
+ :caption: Contents
+
+ gobject
+ gtk4
+ libadwaita
+ gtk3
+
+.. toctree::
+ :maxdepth: 1
+ :hidden:
+ :caption: External Resources
+
+.. toctree::
+ :maxdepth: 1
+ :hidden:
+ :caption: About
diff --git a/docs/tutorials/libadwaita.rst b/docs/tutorials/libadwaita.rst
new file mode 100644
index 0000000..293d1e4
--- /dev/null
+++ b/docs/tutorials/libadwaita.rst
@@ -0,0 +1,15 @@
+Adwaita
+=======
+
+`Adwaita `_ (``libadwaita``)
+offers application developers many widgets and objects to build GNOME
+applications scaling from desktop workstations to mobile phones.
+
+Adwaita is the library you must use if you want to build applications targeting
+the GNOME desktop and follow its `Human Interface Guidelines `_.
+
+.. toctree::
+ :maxdepth: 3
+ :caption: Contents
+
+ libadwaita/application
diff --git a/docs/tutorials/libadwaita/application.rst b/docs/tutorials/libadwaita/application.rst
new file mode 100644
index 0000000..cf2256d
--- /dev/null
+++ b/docs/tutorials/libadwaita/application.rst
@@ -0,0 +1,42 @@
+.. currentmodule:: gi.repository
+
+Adwaita Application
+===================
+
+:class:`Adw.Application` extends :class:`Gtk.Application` to ease some task
+related to creating applications for GNOME.
+
+.. seealso::
+
+ We previously touched :class:`Gtk.Application` in :doc:`this tutorial `.
+
+
+Adwaita also have :class:`Adw.ApplicationWindow`, it's a subclass of :class:`Gtk.ApplicationWindow`
+that provides the same "freform" features from :class:`Adw.Window`.
+
+.. note::
+ Using :class:`Adw.Application` will also call :func:`Adw.init` for you, this
+ function initialize de library, making sure that translations, types,
+ themes, icons and stylesheets needed by the library are set up properly.
+
+
+Stylesheets
+-----------
+
+If you make use of :class:`Gio.Resource`, :class:`Adw.Application` will
+automatically load stylesheets located in the application's resource base path.
+
+This way you don't need to manually load stylesheets, and it will load the
+matching stylesheets depending on the system appearance settings exposed by
+:class:`Adw.StyleManager`.
+
+
+* ``style.css`` contains the base styles.
+
+* ``style-dark.css`` contains styles only used when :attr:`Adw.StyleManager.props.dark`
+ is ``True``.
+
+* ``style-hc.css`` contains styles used when :attr:`Adw.StyleManager.props.high_contrast` is ``True``.
+
+* ``style-hc-dark.css`` contains styles used when :attr:`Adw.StyleManager.props.high_contrast`
+ and :attr:`Adw.StyleManager.props.dark` are both ``True``.
diff --git a/examples/cairo-demo.py b/examples/cairo-demo.py
deleted file mode 100755
index ee33cdd..0000000
--- a/examples/cairo-demo.py
+++ /dev/null
@@ -1,131 +0,0 @@
-#!/usr/bin/env python
-"""
-Based on cairo-demo/X11/cairo-demo.c
-"""
-
-import cairo
-from gi.repository import Gtk
-
-SIZE = 30
-
-
-def triangle(ctx):
- ctx.move_to(SIZE, 0)
- ctx.rel_line_to(SIZE, 2 * SIZE)
- ctx.rel_line_to(-2 * SIZE, 0)
- ctx.close_path()
-
-
-def square(ctx):
- ctx.move_to(0, 0)
- ctx.rel_line_to(2 * SIZE, 0)
- ctx.rel_line_to(0, 2 * SIZE)
- ctx.rel_line_to(-2 * SIZE, 0)
- ctx.close_path()
-
-
-def bowtie(ctx):
- ctx.move_to(0, 0)
- ctx.rel_line_to(2 * SIZE, 2 * SIZE)
- ctx.rel_line_to(-2 * SIZE, 0)
- ctx.rel_line_to(2 * SIZE, -2 * SIZE)
- ctx.close_path()
-
-
-def inf(ctx):
- ctx.move_to(0, SIZE)
- ctx.rel_curve_to(0, SIZE, SIZE, SIZE, 2 * SIZE, 0)
- ctx.rel_curve_to(SIZE, -SIZE, 2 * SIZE, -SIZE, 2 * SIZE, 0)
- ctx.rel_curve_to(0, SIZE, -SIZE, SIZE, - 2 * SIZE, 0)
- ctx.rel_curve_to(-SIZE, -SIZE, - 2 * SIZE, -SIZE, - 2 * SIZE, 0)
- ctx.close_path()
-
-
-def draw_shapes(ctx, x, y, fill):
- ctx.save()
-
- ctx.new_path()
- ctx.translate(x + SIZE, y + SIZE)
- bowtie(ctx)
- if fill:
- ctx.fill()
- else:
- ctx.stroke()
-
- ctx.new_path()
- ctx.translate(3 * SIZE, 0)
- square(ctx)
- if fill:
- ctx.fill()
- else:
- ctx.stroke()
-
- ctx.new_path()
- ctx.translate(3 * SIZE, 0)
- triangle(ctx)
- if fill:
- ctx.fill()
- else:
- ctx.stroke()
-
- ctx.new_path()
- ctx.translate(3 * SIZE, 0)
- inf(ctx)
- if fill:
- ctx.fill()
- else:
- ctx.stroke()
-
- ctx.restore()
-
-
-def fill_shapes(ctx, x, y):
- draw_shapes(ctx, x, y, True)
-
-
-def stroke_shapes(ctx, x, y):
- draw_shapes(ctx, x, y, False)
-
-
-def draw(da, ctx):
- ctx.set_source_rgb(0, 0, 0)
-
- ctx.set_line_width(SIZE / 4)
- ctx.set_tolerance(0.1)
-
- ctx.set_line_join(cairo.LINE_JOIN_ROUND)
- ctx.set_dash([SIZE / 4.0, SIZE / 4.0], 0)
- stroke_shapes(ctx, 0, 0)
-
- ctx.set_dash([], 0)
- stroke_shapes(ctx, 0, 3 * SIZE)
-
- ctx.set_line_join(cairo.LINE_JOIN_BEVEL)
- stroke_shapes(ctx, 0, 6 * SIZE)
-
- ctx.set_line_join(cairo.LINE_JOIN_MITER)
- stroke_shapes(ctx, 0, 9 * SIZE)
-
- fill_shapes(ctx, 0, 12 * SIZE)
-
- ctx.set_line_join(cairo.LINE_JOIN_BEVEL)
- fill_shapes(ctx, 0, 15 * SIZE)
- ctx.set_source_rgb(1, 0, 0)
- stroke_shapes(ctx, 0, 15 * SIZE)
-
-
-def main():
- win = Gtk.Window()
- win.connect('destroy', lambda w: Gtk.main_quit())
- win.set_default_size(450, 550)
-
- drawingarea = Gtk.DrawingArea()
- win.add(drawingarea)
- drawingarea.connect('draw', draw)
-
- win.show_all()
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demo.py b/examples/demo/demo.py
deleted file mode 100755
index 6e26994..0000000
--- a/examples/demo/demo.py
+++ /dev/null
@@ -1,363 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-
-import codecs
-import os
-import sys
-import textwrap
-
-import gi
-gi.require_version('Gtk', '3.0')
-gi.require_version('Pango', '1.0')
-gi.require_version('PangoCairo', '1.0')
-gi.require_version('GdkPixbuf', '2.0')
-gi.require_version('GtkSource', '4')
-
-from gi.repository import GLib, GObject, Pango, GdkPixbuf, Gtk, Gio
-
-try:
- from gi.repository import GtkSource
- GtkSource # PyFlakes
-except ImportError:
- GtkSource = None
-
-
-DEMOROOTDIR = os.path.abspath(os.path.dirname(__file__))
-DEMOCODEDIR = os.path.join(DEMOROOTDIR, 'demos')
-sys.path.insert(0, DEMOROOTDIR)
-
-
-class Demo(GObject.GObject):
- __gtype_name__ = 'GtkDemo'
-
- def __init__(self, title, module, filename):
- super(Demo, self).__init__()
-
- self.title = title
- self.module = module
- self.filename = filename
-
- @classmethod
- def new_from_file(cls, path):
- relpath = os.path.relpath(path, DEMOROOTDIR)
- packagename = os.path.dirname(relpath).replace(os.sep, '.')
- modulename = os.path.basename(relpath)[0:-3]
-
- package = __import__(packagename, globals(), locals(), [modulename], 0)
- module = getattr(package, modulename)
-
- try:
- return cls(module.title, module, path)
- except AttributeError as e:
- raise AttributeError('(%s): %s' % (path, e.message))
-
-
-class DemoTreeStore(Gtk.TreeStore):
- __gtype_name__ = 'GtkDemoTreeStore'
-
- def __init__(self, *args):
- super(DemoTreeStore, self).__init__(str, Demo, Pango.Style)
-
- self._parent_nodes = {}
-
- for filename in self._list_dir(DEMOCODEDIR):
- fullpath = os.path.join(DEMOCODEDIR, filename)
- initfile = os.path.join(os.path.dirname(fullpath), '__init__.py')
-
- if fullpath != initfile and os.path.isfile(initfile) and fullpath.endswith('.py'):
- parentname = os.path.dirname(os.path.relpath(fullpath, DEMOCODEDIR))
-
- if parentname:
- parent = self._get_parent_node(parentname)
- else:
- parent = None
-
- demo = Demo.new_from_file(fullpath)
- self.append(parent, (demo.title, demo, Pango.Style.NORMAL))
-
- def _list_dir(self, path):
- demo_file_list = []
-
- for filename in os.listdir(path):
- fullpath = os.path.join(path, filename)
-
- if os.path.isdir(fullpath):
- demo_file_list.extend(self._list_dir(fullpath))
- elif os.path.isfile(fullpath):
- demo_file_list.append(fullpath)
-
- return sorted(demo_file_list, key=str.lower)
-
- def _get_parent_node(self, name):
- if name not in self._parent_nodes.keys():
- node = self.append(None, (name, None, Pango.Style.NORMAL))
- self._parent_nodes[name] = node
-
- return self._parent_nodes[name]
-
-
-class GtkDemoApp(Gtk.Application):
- __gtype_name__ = 'GtkDemoWindow'
-
- def __init__(self):
- super(GtkDemoApp, self).__init__(application_id='org.gnome.pygobject.gtkdemo')
-
- # Use a GResource to hold the CSS files. Resource bundles are created by
- # the glib-compile-resources program shipped with Glib which takes an xml
- # file that describes the bundle, and a set of files that the xml
- # references. These are combined into a binary resource bundle.
- base_path = os.path.abspath(os.path.dirname(__file__))
- resource_path = os.path.join(base_path, 'demos/data/demo.gresource')
- resource = Gio.Resource.load(resource_path)
-
- # FIXME: method register() should be without the underscore
- # FIXME: see https://bugzilla.gnome.org/show_bug.cgi?id=684319
- # Once the resource has been globally registered it can be used
- # throughout the application.
- resource._register()
-
- def on_activate(self, app):
- self.window = Gtk.ApplicationWindow.new(self)
- self.window.set_title('PyGObject GTK Code Demos')
- self.window.set_default_size(600, 400)
- self.setup_default_icon()
-
- self.header_bar = Gtk.HeaderBar(show_close_button=True,
- subtitle='Foobar')
- self.window.set_titlebar(self.header_bar)
-
- stack = Gtk.Stack(transition_type=Gtk.StackTransitionType.SLIDE_LEFT_RIGHT,
- homogeneous=True)
- switcher = Gtk.StackSwitcher(stack=stack, halign=Gtk.Align.CENTER)
-
- self.header_bar.set_custom_title(switcher)
-
- hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL,
- homogeneous=False,
- spacing=0)
- self.window.add(hbox)
-
- tree = self.create_tree()
- hbox.pack_start(child=tree, expand=False, fill=False, padding=0)
- hbox.pack_start(child=stack, expand=True, fill=True, padding=0)
-
- text_widget, info_buffer = self.create_text_view()
- stack.add_titled(text_widget, name='info', title='Info')
-
- self.info_buffer = info_buffer
- self.info_buffer.create_tag('title', font='Sans 18')
-
- text_widget, self.source_buffer = self.create_source_view()
- stack.add_titled(text_widget, name='source', title='Source')
-
- self.window.show_all()
-
- self.selection_cb(self.tree_view.get_selection(),
- self.tree_view.get_model())
-
- def find_file(self, base=''):
- dir = os.path.join(DEMOCODEDIR, 'data')
- logo_file = os.path.join(dir, 'gtk-logo-rgb.gif')
- base_file = os.path.join(dir, base)
-
- if (GLib.file_test(logo_file, GLib.FileTest.EXISTS) and
- GLib.file_test(base_file, GLib.FileTest.EXISTS)):
- return base_file
- else:
- filename = os.path.join(DEMOCODEDIR, base)
-
- if GLib.file_test(filename, GLib.FileTest.EXISTS):
- return filename
-
- # can't find the file
- raise IOError('Cannot find demo data file "%s"' % base)
-
- def setup_default_icon(self):
- filename = self.find_file('gtk-logo-rgb.gif')
- pixbuf = GdkPixbuf.Pixbuf.new_from_file(filename)
- transparent = pixbuf.add_alpha(True, 0xff, 0xff, 0xff)
- list = []
- list.append(transparent)
- Gtk.Window.set_default_icon_list(list)
-
- def selection_cb(self, selection, model):
- sel = selection.get_selected()
- if sel == ():
- return
-
- treeiter = sel[1]
- title = model.get_value(treeiter, 0)
- demo = model.get_value(treeiter, 1)
-
- if demo is None:
- return
-
- # Split into paragraphs based on double newlines and use
- # textwrap to strip out all other formatting whitespace
- description = ''
- for paragraph in demo.module.description.split('\n\n'):
- description += '\n'.join(textwrap.wrap(paragraph, 99999))
- description += '\n\n' # Add paragraphs back in
-
- f = codecs.open(demo.filename, 'rU', 'utf-8')
- code = f.read()
- f.close()
-
- # output and style the title
- (start, end) = self.info_buffer.get_bounds()
- self.info_buffer.delete(start, end)
- (start, end) = self.source_buffer.get_bounds()
- self.source_buffer.delete(start, end)
-
- start = self.info_buffer.get_iter_at_offset(0)
- end = start.copy()
- self.info_buffer.insert(end, title)
- start = end.copy()
- start.backward_chars(len(title))
- self.info_buffer.apply_tag_by_name('title', start, end)
- self.info_buffer.insert(end, '\n')
-
- # output the description
- self.info_buffer.insert(end, description)
-
- # output the code
- start = self.source_buffer.get_iter_at_offset(0)
- end = start.copy()
- self.source_buffer.insert(end, code)
-
- def row_activated_cb(self, view, path, col, store):
- iter = store.get_iter(path)
- demo = store.get_value(iter, 1)
-
- if demo is not None:
- store.set_value(iter, 2, Pango.Style.ITALIC)
- try:
- demo.module.main(self)
- finally:
- store.set_value(iter, 2, Pango.Style.NORMAL)
-
- def create_tree(self):
- tree_store = DemoTreeStore()
- tree_view = Gtk.TreeView()
- self.tree_view = tree_view
- tree_view.set_model(tree_store)
- selection = tree_view.get_selection()
- selection.set_mode(Gtk.SelectionMode.BROWSE)
- tree_view.set_size_request(200, -1)
-
- cell = Gtk.CellRendererText()
- column = Gtk.TreeViewColumn(title='Widget (double click for demo)',
- cell_renderer=cell,
- text=0,
- style=2)
-
- first_iter = tree_store.get_iter_first()
- if first_iter is not None:
- selection.select_iter(first_iter)
-
- selection.connect('changed', self.selection_cb, tree_store)
- tree_view.connect('row_activated', self.row_activated_cb, tree_store)
-
- tree_view.append_column(column)
-
- tree_view.expand_all()
- tree_view.set_headers_visible(False)
- scrolled_window = Gtk.ScrolledWindow(hadjustment=None,
- vadjustment=None)
- scrolled_window.set_policy(Gtk.PolicyType.NEVER,
- Gtk.PolicyType.AUTOMATIC)
-
- scrolled_window.add(tree_view)
-
- label = Gtk.Label(label='Widget (double click for demo)')
-
- box = Gtk.Notebook()
- box.append_page(scrolled_window, label)
-
- tree_view.grab_focus()
-
- return box
-
- def create_scrolled_window(self):
- scrolled_window = Gtk.ScrolledWindow(hadjustment=None,
- vadjustment=None)
- scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC,
- Gtk.PolicyType.AUTOMATIC)
- scrolled_window.set_shadow_type(Gtk.ShadowType.IN)
- return scrolled_window
-
- def create_text_view(self):
- text_view = Gtk.TextView()
- buffer = Gtk.TextBuffer()
-
- text_view.set_buffer(buffer)
- text_view.set_editable(False)
- text_view.set_cursor_visible(False)
-
- scrolled_window = self.create_scrolled_window()
- scrolled_window.add(text_view)
-
- text_view.set_wrap_mode(Gtk.WrapMode.WORD)
- text_view.set_pixels_above_lines(2)
- text_view.set_pixels_below_lines(2)
-
- return scrolled_window, buffer
-
- def create_source_view(self):
- font_desc = Pango.FontDescription('monospace 11')
-
- if GtkSource:
- lang_mgr = GtkSource.LanguageManager()
- lang = lang_mgr.get_language('python')
-
- buffer = GtkSource.Buffer()
- buffer.set_language(lang)
- buffer.set_highlight_syntax(True)
-
- view = GtkSource.View()
- view.set_buffer(buffer)
- view.set_show_line_numbers(True)
-
- scrolled_window = self.create_scrolled_window()
- scrolled_window.add(view)
-
- else:
- scrolled_window, buffer = self.create_text_view()
- view = scrolled_window.get_child()
-
- view.modify_font(font_desc)
- view.set_wrap_mode(Gtk.WrapMode.NONE)
- return scrolled_window, buffer
-
- def run(self, argv):
- self.connect('activate', self.on_activate)
- return super(GtkDemoApp, self).run(argv)
-
-
-def main(argv):
- """Entry point for demo manager"""
- app = GtkDemoApp()
- return app.run(argv)
-
-
-if __name__ == '__main__':
- SystemExit(main(sys.argv))
diff --git a/examples/demo/demos/Css/__init__.py b/examples/demo/demos/Css/__init__.py
deleted file mode 100644
index e69de29..0000000
diff --git a/examples/demo/demos/Css/css_accordion.py b/examples/demo/demos/Css/css_accordion.py
deleted file mode 100644
index 2b7cddc..0000000
--- a/examples/demo/demos/Css/css_accordion.py
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2013 Gian Mario Tagliaretti
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "CSS Accordion"
-description = """
-A simple accordion demo written using CSS transitions and multiple backgrounds.
-"""
-
-
-from gi.repository import Gtk, Gio
-
-
-class CSSAccordionApp:
- def __init__(self):
- window = Gtk.Window()
- window.set_title('CSS Accordion')
- window.set_default_size(600, 300)
- window.set_border_width(10)
- window.connect('destroy', Gtk.main_quit)
-
- hbox = Gtk.Box(homogeneous=False, spacing=2,
- orientation=Gtk.Orientation.HORIZONTAL)
- hbox.set_halign(Gtk.Align.CENTER)
- hbox.set_valign(Gtk.Align.CENTER)
- window.add(hbox)
-
- for label in ('This', 'Is', 'A', 'CSS', 'Accordion', ':-)'):
- hbox.add(Gtk.Button(label=label))
-
- bytes = Gio.resources_lookup_data("/css_accordion/css_accordion.css", 0)
-
- provider = Gtk.CssProvider()
- provider.load_from_data(bytes.get_data())
-
- self.apply_css(window, provider)
-
- window.show_all()
-
- def apply_css(self, widget, provider):
- Gtk.StyleContext.add_provider(widget.get_style_context(),
- provider,
- Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
-
- if isinstance(widget, Gtk.Container):
- widget.forall(self.apply_css, provider)
-
-
-def main(demoapp=None):
- CSSAccordionApp()
- Gtk.main()
-
-
-if __name__ == '__main__':
- import os
- base_path = os.path.abspath(os.path.dirname(__file__))
- resource_path = os.path.join(base_path, '../data/demo.gresource')
- resource = Gio.Resource.load(resource_path)
-
- # FIXME: method register() should be without the underscore
- # FIXME: see https://bugzilla.gnome.org/show_bug.cgi?id=684319
- resource._register()
- main()
diff --git a/examples/demo/demos/Css/css_basics.py b/examples/demo/demos/Css/css_basics.py
deleted file mode 100644
index 18c3d12..0000000
--- a/examples/demo/demos/Css/css_basics.py
+++ /dev/null
@@ -1,148 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2013 Gian Mario Tagliaretti
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "CSS Basics"
-description = """
-Gtk themes are written using CSS. Every widget is build of multiple items
-that you can style very similarly to a regular website.
-"""
-
-import os
-from gi.repository import Gtk, Gdk, Pango, Gio, GLib
-
-
-class CSSBasicsApp:
- def __init__(self, demoapp):
- self.demoapp = demoapp
- #: Store the last successful parsing of the css so we can revert
- #: this in case of an error.
- self.last_good_text = ''
- #: Set when we receive a parsing-error callback. This is needed
- #: to handle logic after a parsing-error callback which does not raise
- #: an exception with provider.load_from_data()
- self.last_error_code = 0
-
- self.window = Gtk.Window()
- self.window.set_title('CSS Basics')
- self.window.set_default_size(400, 300)
- self.window.set_border_width(10)
- self.window.connect('destroy', lambda w: Gtk.main_quit())
-
- self.infobar = Gtk.InfoBar()
- self.infolabel = Gtk.Label()
- self.infobar.get_content_area().pack_start(self.infolabel, False, False, 0)
- self.infobar.set_message_type(Gtk.MessageType.WARNING)
-
- scrolled = Gtk.ScrolledWindow()
- box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
- box.pack_start(scrolled, expand=True, fill=True, padding=0)
- box.pack_start(self.infobar, expand=False, fill=True, padding=0)
- self.window.add(box)
-
- provider = Gtk.CssProvider()
-
- buffer = Gtk.TextBuffer()
- buffer.create_tag(tag_name="warning", underline=Pango.Underline.SINGLE)
- buffer.create_tag(tag_name="error", underline=Pango.Underline.ERROR)
- buffer.connect("changed", self.css_text_changed, provider)
-
- provider.connect("parsing-error", self.show_parsing_error, buffer)
-
- textview = Gtk.TextView()
- textview.set_buffer(buffer)
- scrolled.add(textview)
-
- bytes = Gio.resources_lookup_data("/css_basics/css_basics.css", 0)
- buffer.set_text(bytes.get_data().decode('utf-8'))
-
- self.apply_css(self.window, provider)
- self.window.show_all()
- self.infobar.hide()
-
- def apply_css(self, widget, provider):
- Gtk.StyleContext.add_provider(widget.get_style_context(),
- provider,
- Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
-
- if isinstance(widget, Gtk.Container):
- widget.forall(self.apply_css, provider)
-
- def show_parsing_error(self, provider, section, error, buffer):
- start = buffer.get_iter_at_line_index(section.get_start_line(),
- section.get_start_position())
-
- end = buffer.get_iter_at_line_index(section.get_end_line(),
- section.get_end_position())
-
- if error.code == Gtk.CssProviderError.DEPRECATED:
- tag_name = "warning"
- else:
- tag_name = "error"
- self.last_error_code = error.code
-
- self.infolabel.set_text(error.message)
- self.infobar.show_all()
-
- buffer.apply_tag_by_name(tag_name, start, end)
-
- def css_text_changed(self, buffer, provider):
- start = buffer.get_start_iter()
- end = buffer.get_end_iter()
- buffer.remove_all_tags(start, end)
-
- text = buffer.get_text(start, end, False).encode('utf-8')
-
- # Ignore CSS errors as they are shown by highlighting
- try:
- provider.load_from_data(text)
- except GLib.GError as e:
- if e.domain != 'gtk-css-provider-error-quark':
- raise e
-
- # If the parsing-error callback is ever run (even in the case of warnings)
- # load the last good css text that ran without any warnings. Otherwise
- # we may have a discrepancy in "last_good_text" vs the current buffer
- # causing section.get_start_position() to give back an invalid position
- # for the editor buffer.
- if self.last_error_code:
- provider.load_from_data(self.last_good_text)
- self.last_error_code = 0
- else:
- self.last_good_text = text
- self.infobar.hide()
-
- Gtk.StyleContext.reset_widgets(Gdk.Screen.get_default())
-
-
-def main(demoapp=None):
- CSSBasicsApp(demoapp)
- Gtk.main()
-
-
-if __name__ == '__main__':
- base_path = os.path.abspath(os.path.dirname(__file__))
- resource_path = os.path.join(base_path, '../data/demo.gresource')
- resource = Gio.Resource.load(resource_path)
-
- # FIXME: method register() should be without the underscore
- # FIXME: see https://bugzilla.gnome.org/show_bug.cgi?id=684319
- resource._register()
- main()
diff --git a/examples/demo/demos/Css/css_multiplebgs.py b/examples/demo/demos/Css/css_multiplebgs.py
deleted file mode 100644
index 9e1b011..0000000
--- a/examples/demo/demos/Css/css_multiplebgs.py
+++ /dev/null
@@ -1,187 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2013 Gian Mario Tagliaretti
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "CSS Theming/Multiple Backgrounds"
-description = """
-Gtk themes are written using CSS. Every widget is build of multiple items
-that you can style very similarly to a regular website.
-"""
-
-from gi.repository import Gtk, Gdk, Pango, Gio, GLib
-
-
-class CSSMultiplebgsApp:
- def __init__(self, demoapp):
- self.demoapp = demoapp
- #: Store the last successful parsing of the css so we can revert
- #: this in case of an error.
- self.last_good_text = ''
- #: Set when we receive a parsing-error callback. This is needed
- #: to handle logic after a parsing-error callback which does not raise
- #: an exception with provider.load_from_data()
- self.last_error_code = 0
-
- self.window = Gtk.Window()
- self.window.set_title('CSS Multiplebgs')
- self.window.set_default_size(400, 300)
- self.window.set_border_width(10)
- self.window.connect('destroy', lambda w: Gtk.main_quit())
-
- overlay = Gtk.Overlay()
- overlay.add_events(Gdk.EventMask.ENTER_NOTIFY_MASK |
- Gdk.EventMask.LEAVE_NOTIFY_MASK |
- Gdk.EventMask.POINTER_MOTION_MASK)
-
- self.infobar = Gtk.InfoBar()
- self.infolabel = Gtk.Label()
- self.infobar.get_content_area().pack_start(self.infolabel, False, False, 0)
- self.infobar.set_message_type(Gtk.MessageType.WARNING)
-
- box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
- box.pack_start(overlay, expand=True, fill=True, padding=0)
- box.pack_start(self.infobar, expand=False, fill=True, padding=0)
- self.window.add(box)
-
- canvas = Gtk.DrawingArea()
- canvas.set_name("canvas")
- canvas.connect("draw", self.drawing_area_draw)
- overlay.add(canvas)
-
- button = Gtk.Button()
- button.add_events(Gdk.EventMask.ENTER_NOTIFY_MASK |
- Gdk.EventMask.LEAVE_NOTIFY_MASK |
- Gdk.EventMask.POINTER_MOTION_MASK)
- button.set_name("bricks-button")
- button.set_halign(Gtk.Align.CENTER)
- button.set_valign(Gtk.Align.CENTER)
- button.set_size_request(250, 84)
- overlay.add_overlay(button)
-
- paned = Gtk.Paned(orientation=Gtk.Orientation.VERTICAL)
- overlay.add_overlay(paned)
-
- # We need a filler so we get a handle
- box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
- paned.add(box)
-
- buffer = Gtk.TextBuffer()
- buffer.create_tag(tag_name="warning", underline=Pango.Underline.SINGLE)
- buffer.create_tag(tag_name="error", underline=Pango.Underline.ERROR)
-
- provider = Gtk.CssProvider()
-
- buffer.connect("changed", self.css_text_changed, provider)
- provider.connect("parsing-error", self.show_parsing_error, buffer)
-
- textview = Gtk.TextView()
- textview.set_buffer(buffer)
-
- scrolled = Gtk.ScrolledWindow()
- scrolled.add(textview)
- paned.add(scrolled)
-
- bytes = Gio.resources_lookup_data("/css_multiplebgs/css_multiplebgs.css", 0)
- buffer.set_text(bytes.get_data().decode('utf-8'))
-
- self.apply_css(self.window, provider)
- self.window.show_all()
- self.infobar.hide()
-
- def drawing_area_draw(self, widget, cairo_t):
- context = widget.get_style_context()
- Gtk.render_background(context, cairo_t, 0, 0,
- widget.get_allocated_width(),
- widget.get_allocated_height())
-
- Gtk.render_frame(context, cairo_t, 0, 0,
- widget.get_allocated_width(),
- widget.get_allocated_height())
-
- def apply_css(self, widget, provider):
- Gtk.StyleContext.add_provider(widget.get_style_context(),
- provider,
- Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
-
- if isinstance(widget, Gtk.Container):
- widget.forall(self.apply_css, provider)
-
- def show_parsing_error(self, provider, section, error, buffer):
- start = buffer.get_iter_at_line_index(section.get_start_line(),
- section.get_start_position())
-
- end = buffer.get_iter_at_line_index(section.get_end_line(),
- section.get_end_position())
-
- if error.code == Gtk.CssProviderError.DEPRECATED:
- tag_name = "warning"
- else:
- tag_name = "error"
- self.last_error_code = error.code
-
- self.infolabel.set_text(error.message)
- self.infobar.show_all()
-
- buffer.apply_tag_by_name(tag_name, start, end)
-
- def css_text_changed(self, buffer, provider):
- start = buffer.get_start_iter()
- end = buffer.get_end_iter()
- buffer.remove_all_tags(start, end)
-
- text = buffer.get_text(start, end, False).encode('utf-8')
-
- # Ignore CSS errors as they are shown by highlighting
- try:
- provider.load_from_data(text)
- except GLib.GError as e:
- if e.domain != 'gtk-css-provider-error-quark':
- raise e
-
- # If the parsing-error callback is ever run (even in the case of warnings)
- # load the last good css text that ran without any warnings. Otherwise
- # we may have a discrepancy in "last_good_text" vs the current buffer
- # causing section.get_start_position() to give back an invalid position
- # for the editor buffer.
- if self.last_error_code:
- provider.load_from_data(self.last_good_text)
- self.last_error_code = 0
- else:
- self.last_good_text = text
- self.infobar.hide()
-
- Gtk.StyleContext.reset_widgets(Gdk.Screen.get_default())
-
-
-def main(demoapp=None):
- CSSMultiplebgsApp(demoapp)
- Gtk.main()
-
-
-if __name__ == '__main__':
- import os
- base_path = os.path.abspath(os.path.dirname(__file__))
- resource_path = os.path.join(base_path, '../data/demo.gresource')
- resource = Gio.Resource.load(resource_path)
-
- # FIXME: method register() should be without the underscore
- # FIXME: see https://bugzilla.gnome.org/show_bug.cgi?id=684319
- resource._register()
- main()
diff --git a/examples/demo/demos/Entry/__init__.py b/examples/demo/demos/Entry/__init__.py
deleted file mode 100644
index e69de29..0000000
diff --git a/examples/demo/demos/Entry/entry_buffer.py b/examples/demo/demos/Entry/entry_buffer.py
deleted file mode 100644
index f0c04a4..0000000
--- a/examples/demo/demos/Entry/entry_buffer.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "Entry Buffer"
-description = """
-Gtk.EntryBuffer provides the text content in a Gtk.Entry.
-"""
-
-
-from gi.repository import Gtk
-
-
-class EntryBufferApp:
- def __init__(self):
- self.window = Gtk.Dialog(title='Gtk.EntryBuffer')
- self.window.add_buttons(Gtk.STOCK_CLOSE, Gtk.ResponseType.NONE)
- self.window.connect('response', self.destroy)
- self.window.connect('destroy', lambda x: Gtk.main_quit())
- self.window.set_resizable(False)
-
- vbox = Gtk.VBox(homogeneous=False, spacing=0)
- self.window.get_content_area().pack_start(vbox, True, True, 0)
- vbox.set_border_width(5)
-
- label = Gtk.Label()
- label.set_markup('Entries share a buffer. Typing in one is reflected in the other.')
- vbox.pack_start(label, False, False, 0)
-
- # create a buffer
- buffer = Gtk.EntryBuffer()
-
- # create our first entry
- entry = Gtk.Entry(buffer=buffer)
- vbox.pack_start(entry, False, False, 0)
-
- # create the second entry
- entry = Gtk.Entry(buffer=buffer)
- entry.set_visibility(False)
- vbox.pack_start(entry, False, False, 0)
-
- self.window.show_all()
-
- def destroy(self, *args):
- self.window.destroy()
- Gtk.main_quit()
-
-
-def main(demoapp=None):
- EntryBufferApp()
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/Entry/entry_completion.py b/examples/demo/demos/Entry/entry_completion.py
deleted file mode 100644
index 107c45a..0000000
--- a/examples/demo/demos/Entry/entry_completion.py
+++ /dev/null
@@ -1,86 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "Entry Completion"
-description = """
-Gtk.EntryCompletion provides a mechanism for adding support for
-completion in Gtk.Entry.
-"""
-
-
-from gi.repository import Gtk
-
-
-class EntryBufferApp:
- def __init__(self):
- self.window = Gtk.Dialog(title='Gtk.EntryCompletion')
- self.window.add_buttons(Gtk.STOCK_CLOSE, Gtk.ResponseType.NONE)
- self.window.connect('response', self.destroy)
- self.window.connect('destroy', lambda x: Gtk.main_quit())
- self.window.set_resizable(False)
-
- vbox = Gtk.VBox(homogeneous=False, spacing=0)
- self.window.get_content_area().pack_start(vbox, True, True, 0)
- vbox.set_border_width(5)
-
- label = Gtk.Label()
- label.set_markup('Completion demo, try writing total or gnome for example.')
- vbox.pack_start(label, False, False, 0)
-
- # create our entry
- entry = Gtk.Entry()
- vbox.pack_start(entry, False, False, 0)
-
- # create the completion object
- completion = Gtk.EntryCompletion()
-
- # assign the completion to the entry
- entry.set_completion(completion)
-
- # create tree model and use it as the completion model
- completion_model = self.create_completion_model()
- completion.set_model(completion_model)
-
- completion.set_text_column(0)
-
- self.window.show_all()
-
- def create_completion_model(self):
- store = Gtk.ListStore(str)
-
- store.append(['GNOME'])
- store.append(['total'])
- store.append(['totally'])
-
- return store
-
- def destroy(self, *args):
- self.window.destroy()
- Gtk.main_quit()
-
-
-def main(demoapp=None):
- EntryBufferApp()
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/Entry/search_entry.py b/examples/demo/demos/Entry/search_entry.py
deleted file mode 100644
index 793b81a..0000000
--- a/examples/demo/demos/Entry/search_entry.py
+++ /dev/null
@@ -1,254 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "Search Entry"
-description = """GtkEntry allows to display icons and progress information.
-This demo shows how to use these features in a search entry.
-"""
-
-from gi.repository import Gtk, GObject
-
-(PIXBUF_COL,
- TEXT_COL) = range(2)
-
-
-class SearchboxApp:
- def __init__(self, demoapp):
- self.demoapp = demoapp
-
- self.window = Gtk.Dialog(title='Search Entry')
- self.window.add_buttons(Gtk.STOCK_CLOSE, Gtk.ResponseType.NONE)
-
- self.window.connect('response', lambda x, y: self.window.destroy())
- self.window.connect('destroy', Gtk.main_quit)
-
- content_area = self.window.get_content_area()
-
- vbox = Gtk.VBox(spacing=5)
- content_area.pack_start(vbox, True, True, 0)
- vbox.set_border_width(5)
-
- label = Gtk.Label()
- label.set_markup('Search entry demo')
- vbox.pack_start(label, False, False, 0)
-
- hbox = Gtk.HBox(homogeneous=False, spacing=10)
- hbox.set_border_width(0)
- vbox.pack_start(hbox, True, True, 0)
-
- # Create our entry
- entry = Gtk.Entry()
- hbox.pack_start(entry, False, False, 0)
-
- # Create the find and cancel buttons
- notebook = Gtk.Notebook()
- self.notebook = notebook
- notebook.set_show_tabs(False)
- notebook.set_show_border(False)
- hbox.pack_start(notebook, False, False, 0)
-
- find_button = Gtk.Button(label='Find')
- find_button.connect('clicked', self.start_search, entry)
- notebook.append_page(find_button, None)
- find_button.show()
-
- cancel_button = Gtk.Button(label='Cancel')
- cancel_button.connect('clicked', self.stop_search, entry)
- notebook.append_page(cancel_button, None)
- cancel_button.show()
-
- # Set up the search icon
- self.search_by_name(None, entry)
-
- # Set up the clear icon
- entry.set_icon_from_stock(Gtk.EntryIconPosition.SECONDARY,
- Gtk.STOCK_CLEAR)
- self.text_changed_cb(entry, None, find_button)
-
- entry.connect('notify::text', self.text_changed_cb, find_button)
-
- entry.connect('activate', self.activate_cb)
-
- # Create the menu
- menu = self.create_search_menu(entry)
- entry.connect('icon-press', self.icon_press_cb, menu)
-
- # FIXME: this should take None for the detach callback
- # but our callback implementation does not allow
- # it yet, so we pass in a noop callback
- menu.attach_to_widget(entry, self.detach)
-
- # add accessible alternatives for icon functionality
- entry.connect('populate-popup', self.entry_populate_popup)
-
- self.window.show_all()
-
- def detach(self, *args):
- pass
-
- def show_find_button(self):
- self.notebook.set_current_page(0)
-
- def show_cancel_button(self):
- self.notebook.set_current_page(1)
-
- def search_progress(self, entry):
- entry.progress_pulse()
- return True
-
- def search_progress_done(self, entry):
- entry.set_progress_fraction(0.0)
-
- def finish_search(self, button, entry):
- self.show_find_button()
- GObject.source_remove(self.search_progress_id)
- self.search_progress_done(entry)
- self.search_progress_id = 0
-
- return False
-
- def start_search_feedback(self, entry):
- self.search_progress_id = GObject.timeout_add(100,
- self.search_progress,
- entry)
-
- return False
-
- def start_search(self, button, entry):
- self.show_cancel_button()
- self.search_progress_id = GObject.timeout_add_seconds(1,
- self.start_search_feedback,
- entry)
- self.finish_search_id = GObject.timeout_add_seconds(15,
- self.finish_search,
- button)
-
- def stop_search(self, button, entry):
- GObject.source_remove(self.finish_search_id)
- self.finish_search(button, entry)
-
- def clear_entry_swapped(self, widget, entry):
- self.clear_entry(entry)
-
- def clear_entry(self, entry):
- entry.set_text('')
-
- def search_by_name(self, item, entry):
- entry.set_icon_from_stock(Gtk.EntryIconPosition.PRIMARY,
- Gtk.STOCK_FIND)
- entry.set_icon_tooltip_text(Gtk.EntryIconPosition.PRIMARY,
- 'Search by name\n' +
- 'Click here to change the search type')
-
- def search_by_description(self, item, entry):
- entry.set_icon_from_stock(Gtk.EntryIconPosition.PRIMARY,
- Gtk.STOCK_EDIT)
- entry.set_icon_tooltip_text(Gtk.EntryIconPosition.PRIMARY,
- 'Search by description\n' +
- 'Click here to change the search type')
-
- def search_by_file(self, item, entry):
- entry.set_icon_from_stock(Gtk.EntryIconPosition.PRIMARY,
- Gtk.STOCK_OPEN)
- entry.set_icon_tooltip_text(Gtk.EntryIconPosition.PRIMARY,
- 'Search by file name\n' +
- 'Click here to change the search type')
-
- def create_search_menu(self, entry):
- menu = Gtk.Menu()
-
- item = Gtk.ImageMenuItem.new_with_mnemonic('Search by _name')
- image = Gtk.Image.new_from_stock(Gtk.STOCK_FIND, Gtk.IconSize.MENU)
- item.set_image(image)
- item.set_always_show_image(True)
- item.connect('activate', self.search_by_name, entry)
- menu.append(item)
-
- item = Gtk.ImageMenuItem.new_with_mnemonic('Search by _description')
- image = Gtk.Image.new_from_stock(Gtk.STOCK_EDIT, Gtk.IconSize.MENU)
- item.set_image(image)
- item.set_always_show_image(True)
- item.connect('activate', self.search_by_description, entry)
- menu.append(item)
-
- item = Gtk.ImageMenuItem.new_with_mnemonic('Search by _file name')
- image = Gtk.Image.new_from_stock(Gtk.STOCK_OPEN, Gtk.IconSize.MENU)
- item.set_image(image)
- item.set_always_show_image(True)
- item.connect('activate', self.search_by_name, entry)
- menu.append(item)
-
- menu.show_all()
-
- return menu
-
- def icon_press_cb(self, entry, position, event, menu):
- if position == Gtk.EntryIconPosition.PRIMARY:
- menu.popup(None, None, None, None,
- event.button, event.time)
- else:
- self.clear_entry(entry)
-
- def text_changed_cb(self, entry, pspec, button):
- has_text = entry.get_text_length() > 0
- entry.set_icon_sensitive(Gtk.EntryIconPosition.SECONDARY, has_text)
- button.set_sensitive(has_text)
-
- def activate_cb(self, entry, button):
- if self.search_progress_id != 0:
- return
- self.start_search(button, entry)
-
- def search_entry_destroyed(self, widget):
- if self.finish_search_id != 0:
- GObject.source_remove(self.finish_search_id)
- if self.search_progress_id != 0:
- GObject.source_remove(self.search_progress_id)
-
- self.window = None
-
- def entry_populate_popup(self, entry, menu):
- has_text = entry.get_text_length() > 0
-
- item = Gtk.SeparatorMenuItem()
- item.show()
- menu.append(item)
-
- item = Gtk.MenuItem.new_with_mnemonic("C_lear")
- item.show()
- item.connect('activate', self.clear_entry_swapped, entry)
- menu.append(item)
- item.set_sensitive(has_text)
-
- search_menu = self.create_search_menu(entry)
- item = Gtk.MenuItem.new_with_label('Search by')
- item.show()
- item.set_submenu(search_menu)
- menu.append(item)
-
-
-def main(demoapp=None):
- SearchboxApp(demoapp)
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/IconView/__init__.py b/examples/demo/demos/IconView/__init__.py
deleted file mode 100644
index e69de29..0000000
diff --git a/examples/demo/demos/IconView/iconviewbasics.py b/examples/demo/demos/IconView/iconviewbasics.py
deleted file mode 100644
index 8cb71a8..0000000
--- a/examples/demo/demos/IconView/iconviewbasics.py
+++ /dev/null
@@ -1,221 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "Icon View Basics"
-description = """The GtkIconView widget is used to display and manipulate
-icons. It uses a GtkTreeModel for data storage, so the list store example might
-be helpful. We also use the Gio.File API to get the icons for each file type.
-"""
-
-
-import os
-
-from gi.repository import GLib, Gio, GdkPixbuf, Gtk
-
-
-class IconViewApp:
- (COL_PATH,
- COL_DISPLAY_NAME,
- COL_PIXBUF,
- COL_IS_DIRECTORY,
- NUM_COLS) = range(5)
-
- def __init__(self, demoapp):
- self.pixbuf_lookup = {}
-
- self.demoapp = demoapp
-
- self.window = Gtk.Window()
- self.window.set_title('Gtk.IconView demo')
- self.window.set_default_size(650, 400)
- self.window.connect('destroy', Gtk.main_quit)
-
- vbox = Gtk.VBox()
- self.window.add(vbox)
-
- tool_bar = Gtk.Toolbar()
- vbox.pack_start(tool_bar, False, False, 0)
-
- up_button = Gtk.ToolButton(stock_id=Gtk.STOCK_GO_UP)
- up_button.set_is_important(True)
- up_button.set_sensitive(False)
- tool_bar.insert(up_button, -1)
-
- home_button = Gtk.ToolButton(stock_id=Gtk.STOCK_HOME)
- home_button.set_is_important(True)
- tool_bar.insert(home_button, -1)
-
- sw = Gtk.ScrolledWindow()
- sw.set_shadow_type(Gtk.ShadowType.ETCHED_IN)
- sw.set_policy(Gtk.PolicyType.AUTOMATIC,
- Gtk.PolicyType.AUTOMATIC)
-
- vbox.pack_start(sw, True, True, 0)
-
- # create the store and fill it with content
- self.parent_dir = '/'
- store = self.create_store()
- self.fill_store(store)
-
- icon_view = Gtk.IconView(model=store)
- icon_view.set_selection_mode(Gtk.SelectionMode.MULTIPLE)
- sw.add(icon_view)
-
- # connect to the 'clicked' signal of the "Up" tool button
- up_button.connect('clicked', self.up_clicked, store)
-
- # connect to the 'clicked' signal of the "home" tool button
- home_button.connect('clicked', self.home_clicked, store)
-
- self.up_button = up_button
- self.home_button = home_button
-
- # we now set which model columns that correspond to the text
- # and pixbuf of each item
- icon_view.set_text_column(self.COL_DISPLAY_NAME)
- icon_view.set_pixbuf_column(self.COL_PIXBUF)
-
- # connect to the "item-activated" signal
- icon_view.connect('item-activated', self.item_activated, store)
- icon_view.grab_focus()
-
- self.window.show_all()
-
- def sort_func(self, store, a_iter, b_iter, user_data):
- (a_name, a_is_dir) = store.get(a_iter,
- self.COL_DISPLAY_NAME,
- self.COL_IS_DIRECTORY)
-
- (b_name, b_is_dir) = store.get(b_iter,
- self.COL_DISPLAY_NAME,
- self.COL_IS_DIRECTORY)
-
- if a_name is None:
- a_name = ''
-
- if b_name is None:
- b_name = ''
-
- if (not a_is_dir) and b_is_dir:
- return 1
- elif a_is_dir and (not b_is_dir):
- return -1
- elif a_name > b_name:
- return 1
- elif a_name < b_name:
- return -1
- else:
- return 0
-
- def up_clicked(self, item, store):
- self.parent_dir = os.path.split(self.parent_dir)[0]
- self.fill_store(store)
- # de-sensitize the up button if we are at the root
- self.up_button.set_sensitive(self.parent_dir != '/')
-
- def home_clicked(self, item, store):
- self.parent_dir = GLib.get_home_dir()
- self.fill_store(store)
-
- # Sensitize the up button
- self.up_button.set_sensitive(True)
-
- def item_activated(self, icon_view, tree_path, store):
- iter_ = store.get_iter(tree_path)
- (path, is_dir) = store.get(iter_, self.COL_PATH, self.COL_IS_DIRECTORY)
- if not is_dir:
- return
-
- self.parent_dir = path
- self.fill_store(store)
-
- self.up_button.set_sensitive(True)
-
- def create_store(self):
- store = Gtk.ListStore(str, str, GdkPixbuf.Pixbuf, bool)
-
- # set sort column and function
- store.set_default_sort_func(self.sort_func)
- store.set_sort_column_id(-1, Gtk.SortType.ASCENDING)
-
- return store
-
- def file_to_icon_pixbuf(self, path):
- pixbuf = None
-
- # get the theme icon
- f = Gio.file_new_for_path(path)
- info = f.query_info(Gio.FILE_ATTRIBUTE_STANDARD_ICON,
- Gio.FileQueryInfoFlags.NONE,
- None)
- gicon = info.get_icon()
-
- # check to see if it is an image format we support
- for format in GdkPixbuf.Pixbuf.get_formats():
- for mime_type in format.get_mime_types():
- content_type = Gio.content_type_from_mime_type(mime_type)
- if content_type is not None:
- break
-
- format_gicon = Gio.content_type_get_icon(content_type)
- if format_gicon.equal(gicon):
- gicon = f.icon_new()
- break
-
- if gicon in self.pixbuf_lookup:
- return self.pixbuf_lookup[gicon]
-
- if isinstance(gicon, Gio.ThemedIcon):
- names = gicon.get_names()
- icon_theme = Gtk.IconTheme.get_default()
- for name in names:
- try:
- pixbuf = icon_theme.load_icon(name, 64, 0)
- break
- except GLib.GError:
- pass
-
- self.pixbuf_lookup[gicon] = pixbuf
-
- elif isinstance(gicon, Gio.FileIcon):
- icon_file = gicon.get_file()
- path = icon_file.get_path()
- pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(path, 72, 72)
- self.pixbuf_lookup[gicon] = pixbuf
-
- return pixbuf
-
- def fill_store(self, store):
- store.clear()
- for name in os.listdir(self.parent_dir):
- path = os.path.join(self.parent_dir, name)
- is_dir = os.path.isdir(path)
- pixbuf = self.file_to_icon_pixbuf(path)
- store.append((path, name, pixbuf, is_dir))
-
-
-def main(demoapp=None):
- IconViewApp(demoapp)
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/IconView/iconviewedit.py b/examples/demo/demos/IconView/iconviewedit.py
deleted file mode 100644
index 85dfa93..0000000
--- a/examples/demo/demos/IconView/iconviewedit.py
+++ /dev/null
@@ -1,99 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "Editing and Drag-and-Drop"
-description = """The GtkIconView widget supports Editing and Drag-and-Drop.
-This example also demonstrates using the generic GtkCellLayout interface to set
-up cell renderers in an icon view.
-"""
-
-from gi.repository import Gtk, Gdk, GdkPixbuf
-
-
-class IconviewEditApp:
- COL_TEXT = 0
- NUM_COLS = 1
-
- def __init__(self):
- self.window = Gtk.Window()
- self.window.set_title('Editing and Drag-and-Drop')
- self.window.set_border_width(8)
- self.window.connect('destroy', Gtk.main_quit)
-
- store = Gtk.ListStore(str)
- colors = ['Red', 'Green', 'Blue', 'Yellow']
- store.clear()
- for c in colors:
- store.append([c])
-
- icon_view = Gtk.IconView(model=store)
- icon_view.set_selection_mode(Gtk.SelectionMode.SINGLE)
- icon_view.set_item_orientation(Gtk.Orientation.HORIZONTAL)
- icon_view.set_columns(2)
- icon_view.set_reorderable(True)
-
- renderer = Gtk.CellRendererPixbuf()
- icon_view.pack_start(renderer, True)
- icon_view.set_cell_data_func(renderer,
- self.set_cell_color,
- None)
-
- renderer = Gtk.CellRendererText()
- icon_view.pack_start(renderer, True)
- renderer.props.editable = True
- renderer.connect('edited', self.edited, icon_view)
- icon_view.add_attribute(renderer, 'text', self.COL_TEXT)
-
- self.window.add(icon_view)
-
- self.window.show_all()
-
- def set_cell_color(self, cell_layout, cell, tree_model, iter_, icon_view):
-
- # FIXME return single element instead of tuple
- text = tree_model.get(iter_, self.COL_TEXT)[0]
- color = Gdk.color_parse(text)
- pixel = 0
- if color is not None:
- pixel = ((color.red >> 8) << 24 |
- (color.green >> 8) << 16 |
- (color.blue >> 8) << 8)
-
- pixbuf = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB, False, 8, 24, 24)
- pixbuf.fill(pixel)
-
- cell.props.pixbuf = pixbuf
-
- def edited(self, cell, path_string, text, icon_view):
- model = icon_view.get_model()
- path = Gtk.TreePath(path_string)
-
- iter_ = model.get_iter(path)
- model.set_row(iter_, [text])
-
-
-def main(demoapp=None):
- IconviewEditApp()
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/TreeView/__init__.py b/examples/demo/demos/TreeView/__init__.py
deleted file mode 100644
index e69de29..0000000
diff --git a/examples/demo/demos/TreeView/liststore.py b/examples/demo/demos/TreeView/liststore.py
deleted file mode 100644
index 4b3daa1..0000000
--- a/examples/demo/demos/TreeView/liststore.py
+++ /dev/null
@@ -1,212 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "List Store"
-description = """
-The GtkListStore is used to store data in list form, to be used later on by a
-GtkTreeView to display it. This demo builds a simple GtkListStore and displays
-it. See the Stock Browser demo for a more advanced example.
-"""
-
-
-from gi.repository import Gtk, GObject, GLib
-
-
-class Bug:
- def __init__(self, is_fixed, number, severity, description):
- self.is_fixed = is_fixed
- self.number = number
- self.severity = severity
- self.description = description
-
-
-# initial data we use to fill in the store
-data = [Bug(False, 60482, "Normal", "scrollable notebooks and hidden tabs"),
- Bug(False, 60620, "Critical", "gdk_window_clear_area (gdkwindow-win32.c) is not thread-safe"),
- Bug(False, 50214, "Major", "Xft support does not clean up correctly"),
- Bug(True, 52877, "Major", "GtkFileSelection needs a refresh method. "),
- Bug(False, 56070, "Normal", "Can't click button after setting in sensitive"),
- Bug(True, 56355, "Normal", "GtkLabel - Not all changes propagate correctly"),
- Bug(False, 50055, "Normal", "Rework width/height computations for TreeView"),
- Bug(False, 58278, "Normal", "gtk_dialog_set_response_sensitive () doesn't work"),
- Bug(False, 55767, "Normal", "Getters for all setters"),
- Bug(False, 56925, "Normal", "Gtkcalender size"),
- Bug(False, 56221, "Normal", "Selectable label needs right-click copy menu"),
- Bug(True, 50939, "Normal", "Add shift clicking to GtkTextView"),
- Bug(False, 6112, "Enhancement", "netscape-like collapsable toolbars"),
- Bug(False, 1, "Normal", "First bug :=)")]
-
-
-class ListStoreApp:
- (COLUMN_FIXED,
- COLUMN_NUMBER,
- COLUMN_SEVERITY,
- COLUMN_DESCRIPTION,
- COLUMN_PULSE,
- COLUMN_ICON,
- COLUMN_ACTIVE,
- COLUMN_SENSITIVE,
- NUM_COLUMNS) = range(9)
-
- def __init__(self):
- self.window = Gtk.Window()
- self.window.set_title('Gtk.ListStore Demo')
- self.window.connect('destroy', Gtk.main_quit)
-
- vbox = Gtk.VBox(spacing=8)
- self.window.add(vbox)
-
- label = Gtk.Label(label='This is the bug list (note: not based on real data, it would be nice to have a nice ODBC interface to bugzilla or so, though).')
- vbox.pack_start(label, False, False, 0)
-
- sw = Gtk.ScrolledWindow()
- sw.set_shadow_type(Gtk.ShadowType.ETCHED_IN)
- sw.set_policy(Gtk.PolicyType.NEVER,
- Gtk.PolicyType.AUTOMATIC)
- vbox.pack_start(sw, True, True, 0)
-
- self.create_model()
- treeview = Gtk.TreeView(model=self.model)
- treeview.set_rules_hint(True)
- treeview.set_search_column(self.COLUMN_DESCRIPTION)
- sw.add(treeview)
-
- self.add_columns(treeview)
-
- self.window.set_default_size(280, 250)
- self.window.show_all()
-
- self.window.connect('delete-event', self.window_closed)
- self.timeout = GLib.timeout_add(80, self.spinner_timeout)
-
- def window_closed(self, window, event):
- if self.timeout != 0:
- GLib.source_remove(self.timeout)
-
- def spinner_timeout(self):
- if self.model is None:
- return False
-
- iter_ = self.model.get_iter_first()
- pulse = self.model.get(iter_, self.COLUMN_PULSE)[0]
- if pulse == 999999999:
- pulse = 0
- else:
- pulse += 1
-
- self.model.set_value(iter_, self.COLUMN_PULSE, pulse)
- self.model.set_value(iter_, self.COLUMN_ACTIVE, True)
-
- return True
-
- def create_model(self):
- self.model = Gtk.ListStore(bool,
- GObject.TYPE_INT,
- str,
- str,
- GObject.TYPE_INT,
- str,
- bool,
- bool)
-
- col = 0
- for bug in data:
- if col == 1 or col == 3:
- icon_name = 'battery-critical-charging-symbolic'
- else:
- icon_name = ''
- if col == 3:
- is_sensitive = False
- else:
- is_sensitive = True
-
- self.model.append([bug.is_fixed,
- bug.number,
- bug.severity,
- bug.description,
- 0,
- icon_name,
- False,
- is_sensitive])
- col += 1
-
- def add_columns(self, treeview):
- model = treeview.get_model()
-
- # column for is_fixed toggle
- renderer = Gtk.CellRendererToggle()
- renderer.connect('toggled', self.is_fixed_toggled, model)
-
- column = Gtk.TreeViewColumn("Fixed?", renderer,
- active=self.COLUMN_FIXED)
- column.set_fixed_width(50)
- column.set_sizing(Gtk.TreeViewColumnSizing.FIXED)
- treeview.append_column(column)
-
- # column for severities
- renderer = Gtk.CellRendererText()
- column = Gtk.TreeViewColumn("Severity", renderer,
- text=self.COLUMN_SEVERITY)
- column.set_sort_column_id(self.COLUMN_SEVERITY)
- treeview.append_column(column)
-
- # column for description
- renderer = Gtk.CellRendererText()
- column = Gtk.TreeViewColumn("Description", renderer,
- text=self.COLUMN_DESCRIPTION)
- column.set_sort_column_id(self.COLUMN_DESCRIPTION)
- treeview.append_column(column)
-
- # column for spinner
- renderer = Gtk.CellRendererSpinner()
- column = Gtk.TreeViewColumn("Spinning", renderer,
- pulse=self.COLUMN_PULSE,
- active=self.COLUMN_ACTIVE)
- column.set_sort_column_id(self.COLUMN_PULSE)
- treeview.append_column(column)
-
- # column for symbolic icon
- renderer = Gtk.CellRendererPixbuf()
- renderer.props.follow_state = True
- column = Gtk.TreeViewColumn("Symbolic icon", renderer,
- icon_name=self.COLUMN_ICON,
- sensitive=self.COLUMN_SENSITIVE)
- column.set_sort_column_id(self.COLUMN_ICON)
- treeview.append_column(column)
-
- def is_fixed_toggled(self, cell, path_str, model):
- # get toggled iter
- iter_ = model.get_iter(path_str)
- is_fixed = model.get_value(iter_, self.COLUMN_FIXED)
-
- # do something with value
- is_fixed ^= 1
-
- model.set_value(iter_, self.COLUMN_FIXED, is_fixed)
-
-
-def main(demoapp=None):
- ListStoreApp()
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/TreeView/treemodel_filelist.py b/examples/demo/demos/TreeView/treemodel_filelist.py
deleted file mode 100644
index 82e6d95..0000000
--- a/examples/demo/demos/TreeView/treemodel_filelist.py
+++ /dev/null
@@ -1,235 +0,0 @@
-#!/usr/bin/env python
-
-title = "File List (GenericTreeModel)"
-description = """
-This is a file list demo which makes use of the GenericTreeModel python
-implementation of the Gtk.TreeModel interface. This demo shows what methods
-need to be overridden to provide a valid TreeModel to a TreeView.
-"""
-
-import os
-import stat
-import time
-
-import pygtkcompat
-pygtkcompat.enable()
-pygtkcompat.enable_gtk('3.0')
-
-import gtk
-
-
-folderxpm = [
- "17 16 7 1",
- " c #000000",
- ". c #808000",
- "X c yellow",
- "o c #808080",
- "O c #c0c0c0",
- "+ c white",
- "@ c None",
- "@@@@@@@@@@@@@@@@@",
- "@@@@@@@@@@@@@@@@@",
- "@@+XXXX.@@@@@@@@@",
- "@+OOOOOO.@@@@@@@@",
- "@+OXOXOXOXOXOXO. ",
- "@+XOXOXOXOXOXOX. ",
- "@+OXOXOXOXOXOXO. ",
- "@+XOXOXOXOXOXOX. ",
- "@+OXOXOXOXOXOXO. ",
- "@+XOXOXOXOXOXOX. ",
- "@+OXOXOXOXOXOXO. ",
- "@+XOXOXOXOXOXOX. ",
- "@+OOOOOOOOOOOOO. ",
- "@ ",
- "@@@@@@@@@@@@@@@@@",
- "@@@@@@@@@@@@@@@@@"
- ]
-folderpb = gtk.gdk.pixbuf_new_from_xpm_data(folderxpm)
-
-filexpm = [
- "12 12 3 1",
- " c #000000",
- ". c #ffff04",
- "X c #b2c0dc",
- "X XXX",
- "X ...... XXX",
- "X ...... X",
- "X . ... X",
- "X ........ X",
- "X . .... X",
- "X ........ X",
- "X . .. X",
- "X ........ X",
- "X . .. X",
- "X ........ X",
- "X X"
- ]
-filepb = gtk.gdk.pixbuf_new_from_xpm_data(filexpm)
-
-
-class FileListModel(gtk.GenericTreeModel):
- __gtype_name__ = 'DemoFileListModel'
-
- column_types = (gtk.gdk.Pixbuf, str, int, str, str)
- column_names = ['Name', 'Size', 'Mode', 'Last Changed']
-
- def __init__(self, dname=None):
- gtk.GenericTreeModel.__init__(self)
- self._sort_column_id = 0
- self._sort_order = gtk.SORT_ASCENDING
-
- if not dname:
- self.dirname = os.path.expanduser('~')
- else:
- self.dirname = os.path.abspath(dname)
- self.files = ['..'] + [f for f in os.listdir(self.dirname)]
- return
-
- def get_pathname(self, path):
- filename = self.files[path[0]]
- return os.path.join(self.dirname, filename)
-
- def is_folder(self, path):
- filename = self.files[path[0]]
- pathname = os.path.join(self.dirname, filename)
- filestat = os.stat(pathname)
- if stat.S_ISDIR(filestat.st_mode):
- return True
- return False
-
- def get_column_names(self):
- return self.column_names[:]
-
- #
- # GenericTreeModel Implementation
- #
- def on_get_flags(self):
- return 0 # gtk.TREE_MODEL_ITERS_PERSIST
-
- def on_get_n_columns(self):
- return len(self.column_types)
-
- def on_get_column_type(self, n):
- return self.column_types[n]
-
- def on_get_iter(self, path):
- return self.files[path[0]]
-
- def on_get_path(self, rowref):
- return self.files.index(rowref)
-
- def on_get_value(self, rowref, column):
- fname = os.path.join(self.dirname, rowref)
- try:
- filestat = os.stat(fname)
- except OSError:
- return None
- mode = filestat.st_mode
- if column == 0:
- if stat.S_ISDIR(mode):
- return folderpb
- else:
- return filepb
- elif column == 1:
- return rowref
- elif column == 2:
- return filestat.st_size
- elif column == 3:
- return oct(stat.S_IMODE(mode))
- return time.ctime(filestat.st_mtime)
-
- def on_iter_next(self, rowref):
- try:
- i = self.files.index(rowref) + 1
- return self.files[i]
- except IndexError:
- return None
-
- def on_iter_children(self, rowref):
- if rowref:
- return None
- return self.files[0]
-
- def on_iter_has_child(self, rowref):
- return False
-
- def on_iter_n_children(self, rowref):
- if rowref:
- return 0
- return len(self.files)
-
- def on_iter_nth_child(self, rowref, n):
- if rowref:
- return None
- try:
- return self.files[n]
- except IndexError:
- return None
-
- def on_iter_parent(child):
- return None
-
-
-class GenericTreeModelExample:
- def delete_event(self, widget, event, data=None):
- gtk.main_quit()
- return False
-
- def __init__(self):
- # Create a new window
- self.window = gtk.Window(type=gtk.WINDOW_TOPLEVEL)
-
- self.window.set_size_request(300, 200)
-
- self.window.connect("delete_event", self.delete_event)
-
- self.listmodel = FileListModel()
-
- # create the TreeView
- self.treeview = gtk.TreeView()
-
- self.tvcolumns = []
-
- # create the TreeViewColumns to display the data
- for n, name in enumerate(self.listmodel.get_column_names()):
- if n == 0:
- cellpb = gtk.CellRendererPixbuf()
- col = gtk.TreeViewColumn(name, cellpb, pixbuf=0)
- cell = gtk.CellRendererText()
- col.pack_start(cell, False)
- col.add_attribute(cell, 'text', 1)
- else:
- cell = gtk.CellRendererText()
- col = gtk.TreeViewColumn(name, cell, text=n + 1)
- if n == 1:
- cell.set_property('xalign', 1.0)
-
- self.treeview.append_column(col)
-
- self.treeview.connect('row-activated', self.open_file)
-
- self.scrolledwindow = gtk.ScrolledWindow()
- self.scrolledwindow.add(self.treeview)
- self.window.add(self.scrolledwindow)
- self.treeview.set_model(self.listmodel)
- self.window.set_title(self.listmodel.dirname)
- self.window.show_all()
-
- def open_file(self, treeview, path, column):
- model = treeview.get_model()
- if model.is_folder(path):
- pathname = model.get_pathname(path)
- new_model = FileListModel(pathname)
- self.window.set_title(new_model.dirname)
- treeview.set_model(new_model)
- return
-
-
-def main(demoapp=None):
- demo = GenericTreeModelExample()
- demo
- gtk.main()
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/demo/demos/TreeView/treemodel_filetree.py b/examples/demo/demos/TreeView/treemodel_filetree.py
deleted file mode 100644
index eb8e2b9..0000000
--- a/examples/demo/demos/TreeView/treemodel_filetree.py
+++ /dev/null
@@ -1,280 +0,0 @@
-#!/usr/bin/env python
-
-title = "File Tree (GenericTreeModel)"
-description = """
-This is a file list demo which makes use of the GenericTreeModel python
-implementation of the Gtk.TreeModel interface. This demo shows what methods
-need to be overridden to provide a valid TreeModel to a TreeView.
-"""
-
-import os
-import stat
-import time
-from collections import OrderedDict
-
-import pygtkcompat
-pygtkcompat.enable_gtk('3.0')
-
-import gtk
-
-
-folderxpm = [
- "17 16 7 1",
- " c #000000",
- ". c #808000",
- "X c yellow",
- "o c #808080",
- "O c #c0c0c0",
- "+ c white",
- "@ c None",
- "@@@@@@@@@@@@@@@@@",
- "@@@@@@@@@@@@@@@@@",
- "@@+XXXX.@@@@@@@@@",
- "@+OOOOOO.@@@@@@@@",
- "@+OXOXOXOXOXOXO. ",
- "@+XOXOXOXOXOXOX. ",
- "@+OXOXOXOXOXOXO. ",
- "@+XOXOXOXOXOXOX. ",
- "@+OXOXOXOXOXOXO. ",
- "@+XOXOXOXOXOXOX. ",
- "@+OXOXOXOXOXOXO. ",
- "@+XOXOXOXOXOXOX. ",
- "@+OOOOOOOOOOOOO. ",
- "@ ",
- "@@@@@@@@@@@@@@@@@",
- "@@@@@@@@@@@@@@@@@"
- ]
-folderpb = gtk.gdk.pixbuf_new_from_xpm_data(folderxpm)
-
-filexpm = [
- "12 12 3 1",
- " c #000000",
- ". c #ffff04",
- "X c #b2c0dc",
- "X XXX",
- "X ...... XXX",
- "X ...... X",
- "X . ... X",
- "X ........ X",
- "X . .... X",
- "X ........ X",
- "X . .. X",
- "X ........ X",
- "X . .. X",
- "X ........ X",
- "X X"
- ]
-filepb = gtk.gdk.pixbuf_new_from_xpm_data(filexpm)
-
-
-class FileTreeModel(gtk.GenericTreeModel):
- __gtype_name__ = 'DemoFileTreeModel'
-
- column_types = (gtk.gdk.Pixbuf, str, int, str, str)
- column_names = ['Name', 'Size', 'Mode', 'Last Changed']
-
- def __init__(self, dname=None):
- gtk.GenericTreeModel.__init__(self)
- if not dname:
- self.dirname = os.path.expanduser('~')
- else:
- self.dirname = os.path.abspath(dname)
- self.files = self.build_file_dict(self.dirname)
- return
-
- def build_file_dict(self, dirname):
- """
- :Returns:
- A dictionary containing the files in the given dirname keyed by filename.
- If the child filename is a sub-directory, the dict value is a dict.
- Otherwise it will be None.
- """
- d = OrderedDict()
- for fname in os.listdir(dirname):
- try:
- filestat = os.stat(os.path.join(dirname, fname))
- except OSError:
- d[fname] = None
- else:
- d[fname] = OrderedDict() if stat.S_ISDIR(filestat.st_mode) else None
-
- return d
-
- def get_node_from_treepath(self, path):
- """
- :Returns:
- The node stored at the given tree path in local storage.
- """
- # TreePaths are a series of integer indices so just iterate through them
- # and index values by each integer since we are using an OrderedDict
- if path is None:
- path = []
- node = self.files
- for index in path:
- node = list(node.values())[index]
- return node
-
- def get_node_from_filepath(self, filepath):
- """
- :Returns:
- The node stored at the given file path in local storage.
- """
- if not filepath:
- return self.files
- node = self.files
- for key in filepath.split(os.path.sep):
- node = node[key]
- return node
-
- def get_column_names(self):
- return self.column_names[:]
-
- #
- # GenericTreeModel Implementation
- #
-
- def on_get_flags(self):
- return 0
-
- def on_get_n_columns(self):
- return len(self.column_types)
-
- def on_get_column_type(self, n):
- return self.column_types[n]
-
- def on_get_path(self, relpath):
- path = []
- node = self.files
- for key in relpath.split(os.path.sep):
- path.append(list(node.keys()).index(key))
- node = node[key]
- return path
-
- def on_get_value(self, relpath, column):
- fname = os.path.join(self.dirname, relpath)
- try:
- filestat = os.stat(fname)
- except OSError:
- return None
- mode = filestat.st_mode
- if column == 0:
- if stat.S_ISDIR(mode):
- return folderpb
- else:
- return filepb
- elif column == 1:
- return os.path.basename(relpath)
- elif column == 2:
- return filestat.st_size
- elif column == 3:
- return oct(stat.S_IMODE(mode))
- return time.ctime(filestat.st_mtime)
-
- def on_get_iter(self, path):
- filepath = ''
- value = self.files
- for index in path:
- filepath = os.path.join(filepath, list(value.keys())[index])
- value = list(value.values())[index]
- return filepath
-
- def on_iter_next(self, filepath):
- parent_path, child_path = os.path.split(filepath)
- parent = self.get_node_from_filepath(parent_path)
-
- # Index of filepath within its parents child list
- sibling_names = list(parent.keys())
- index = sibling_names.index(child_path)
- try:
- return os.path.join(parent_path, sibling_names[index + 1])
- except IndexError:
- return None
-
- def on_iter_children(self, filepath):
- if filepath:
- children = list(self.get_node_from_filepath(filepath).keys())
- if children:
- return os.path.join(filepath, children[0])
- elif self.files:
- return list(self.files.keys())[0]
-
- return None
-
- def on_iter_has_child(self, filepath):
- return bool(self.get_node_from_filepath(filepath))
-
- def on_iter_n_children(self, filepath):
- return len(self.get_node_from_filepath(filepath))
-
- def on_iter_nth_child(self, filepath, n):
- try:
- child = list(self.get_node_from_filepath(filepath).keys())[n]
- if filepath:
- return os.path.join(filepath, child)
- else:
- return child
- except IndexError:
- return None
-
- def on_iter_parent(self, filepath):
- return os.path.dirname(filepath)
-
- def on_ref_node(self, filepath):
- value = self.get_node_from_filepath(filepath)
- if value is not None:
- value.update(self.build_file_dict(os.path.join(self.dirname, filepath)))
-
- def on_unref_node(self, filepath):
- pass
-
-
-class GenericTreeModelExample:
- def delete_event(self, widget, event, data=None):
- gtk.main_quit()
- return False
-
- def __init__(self):
- # Create a new window
- self.window = gtk.Window(type=gtk.WINDOW_TOPLEVEL)
- self.window.set_size_request(300, 200)
- self.window.connect("delete_event", self.delete_event)
-
- self.listmodel = FileTreeModel()
-
- # create the TreeView
- self.treeview = gtk.TreeView()
-
- # create the TreeViewColumns to display the data
- column_names = self.listmodel.get_column_names()
- self.tvcolumn = [None] * len(column_names)
- cellpb = gtk.CellRendererPixbuf()
- self.tvcolumn[0] = gtk.TreeViewColumn(column_names[0],
- cellpb, pixbuf=0)
- cell = gtk.CellRendererText()
- self.tvcolumn[0].pack_start(cell, False)
- self.tvcolumn[0].add_attribute(cell, 'text', 1)
- self.treeview.append_column(self.tvcolumn[0])
- for n in range(1, len(column_names)):
- cell = gtk.CellRendererText()
- if n == 1:
- cell.set_property('xalign', 1.0)
- self.tvcolumn[n] = gtk.TreeViewColumn(column_names[n],
- cell, text=n + 1)
- self.treeview.append_column(self.tvcolumn[n])
-
- self.scrolledwindow = gtk.ScrolledWindow()
- self.scrolledwindow.add(self.treeview)
- self.window.add(self.scrolledwindow)
- self.treeview.set_model(self.listmodel)
- self.window.set_title(self.listmodel.dirname)
- self.window.show_all()
-
-
-def main(demoapp=None):
- demo = GenericTreeModelExample()
- demo
- gtk.main()
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/demo/demos/TreeView/treemodel_large.py b/examples/demo/demos/TreeView/treemodel_large.py
deleted file mode 100644
index b129521..0000000
--- a/examples/demo/demos/TreeView/treemodel_large.py
+++ /dev/null
@@ -1,143 +0,0 @@
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# pygobject - Python bindings for the GObject library
-# Copyright (C) 2014 Simon Feltman
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, see .
-
-title = "Tree Model with Large Data"
-description = """
-Implementation of the Gtk.TreeModel interface to create a custom model.
-The demo uses a fake data store (it is not backed by a Python list) and is for
-the purpose of showing how to override the TreeModel interfaces virtual methods.
-"""
-
-from gi.repository import GObject
-from gi.repository import GLib
-from gi.repository import Gtk
-
-
-class Model(GObject.Object, Gtk.TreeModel):
- columns_types = (str, str)
- item_count = 100000
- item_data = 'abcdefghijklmnopqrstuvwxyz'
-
- def __init__(self):
- super(Model, self).__init__()
-
- def do_get_flags(self):
- return Gtk.TreeModelFlags.LIST_ONLY
-
- def do_get_n_columns(self):
- return len(self.columns_types)
-
- def do_get_column_type(self, n):
- return self.columns_types[n]
-
- def do_get_iter(self, path):
- # Return False and an empty iter when out of range
- index = path.get_indices()[0]
- if index < 0 or index >= self.item_count:
- return False, None
-
- it = Gtk.TreeIter()
- it.user_data = index
- return True, it
-
- def do_get_path(self, it):
- return Gtk.TreePath([it.user_data])
-
- def do_get_value(self, it, column):
- if column == 0:
- return str(it.user_data)
- elif column == 1:
- return self.item_data
-
- def do_iter_next(self, it):
- # Return False if there is not a next item
- next = it.user_data + 1
- if next >= self.item_count:
- return False
-
- # Set the iters data and return True
- it.user_data = next
- return True
-
- def do_iter_previous(self, it):
- prev = it.user_data - 1
- if prev < 0:
- return False
-
- it.user_data = prev
- return True
-
- def do_iter_children(self, parent):
- # If parent is None return the first item
- if parent is None:
- it = Gtk.TreeIter()
- it.user_data = 0
- return True, it
- return False, None
-
- def do_iter_has_child(self, it):
- return it is None
-
- def do_iter_n_children(self, it):
- # If iter is None, return the number of top level nodes
- if it is None:
- return self.item_count
- return 0
-
- def do_iter_nth_child(self, parent, n):
- if parent is not None or n >= self.item_count:
- return False, None
- elif parent is None:
- # If parent is None, return the nth iter
- it = Gtk.TreeIter()
- it.user_data = n
- return True, it
-
- def do_iter_parent(self, child):
- return False, None
-
-
-def main(demoapp=None):
- model = Model()
- # Use fixed-height-mode to get better model load and display performance.
- view = Gtk.TreeView(fixed_height_mode=True, headers_visible=False)
- column = Gtk.TreeViewColumn()
- column.props.sizing = Gtk.TreeViewColumnSizing.FIXED
-
- renderer1 = Gtk.CellRendererText()
- renderer2 = Gtk.CellRendererText()
- column.pack_start(renderer1, expand=True)
- column.pack_start(renderer2, expand=True)
- column.add_attribute(renderer1, 'text', 0)
- column.add_attribute(renderer2, 'text', 1)
- view.append_column(column)
-
- scrolled = Gtk.ScrolledWindow()
- scrolled.add(view)
-
- window = Gtk.Window(title=title)
- window.set_size_request(480, 640)
- window.add(scrolled)
- window.show_all()
- GLib.timeout_add(10, lambda *args: view.set_model(model))
- return window
-
-
-if __name__ == "__main__":
- window = main()
- window.connect('destroy', Gtk.main_quit)
- Gtk.main()
diff --git a/examples/demo/demos/__init__.py b/examples/demo/demos/__init__.py
deleted file mode 100644
index e69de29..0000000
diff --git a/examples/demo/demos/appwindow.py b/examples/demo/demos/appwindow.py
deleted file mode 100644
index edac467..0000000
--- a/examples/demo/demos/appwindow.py
+++ /dev/null
@@ -1,408 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "Application main window"
-description = """
-Demonstrates a typical application window with menubar, toolbar, statusbar.
-"""
-
-import os
-
-from gi.repository import GdkPixbuf, Gtk
-
-
-infobar = None
-window = None
-messagelabel = None
-_demoapp = None
-
-
-def widget_destroy(widget, button):
- widget.destroy()
-
-
-def activate_action(action, user_data=None):
- global window
-
- name = action.get_name()
- _type = type(action)
- if name == 'DarkTheme':
- value = action.get_active()
- settings = Gtk.Settings.get_default()
- settings.set_property('gtk-application-prefer-dark-theme', value)
- return
-
- dialog = Gtk.MessageDialog(message_type=Gtk.MessageType.INFO,
- buttons=Gtk.ButtonsType.CLOSE,
- text='You activated action: "%s" of type %s' % (name, _type))
-
- # FIXME: this should be done in the constructor
- dialog.set_transient_for(window)
- dialog.connect('response', widget_destroy)
- dialog.show()
-
-
-def activate_radio_action(action, current, user_data=None):
- global infobar
- global messagelabel
-
- name = current.get_name()
- _type = type(current)
- active = current.get_active()
- value = current.get_current_value()
- if active:
- text = 'You activated radio action: "%s" of type %s.\n Current value: %d' % (name, _type, value)
- messagelabel.set_text(text)
- infobar.set_message_type(Gtk.MessageType(value))
- infobar.show()
-
-
-def update_statusbar(buffer, statusbar):
- statusbar.pop(0)
- count = buffer.get_char_count()
-
- iter = buffer.get_iter_at_mark(buffer.get_insert())
- row = iter.get_line()
- col = iter.get_line_offset()
- msg = 'Cursor at row %d column %d - %d chars in document' % (row, col, count)
-
- statusbar.push(0, msg)
-
-
-def mark_set_callback(buffer, new_location, mark, data):
- update_statusbar(buffer, data)
-
-
-def about_cb(widget, user_data=None):
- global window
-
- authors = ['John (J5) Palmieri',
- 'Tomeu Vizoso',
- 'and many more...']
-
- documentors = ['David Malcolm',
- 'Zack Goldberg',
- 'and many more...']
-
- license = """
-This library is free software; you can redistribute it and/or
-modify it under the terms of the GNU Library General Public License as
-published by the Free Software Foundation; either version 2 of the
-License, or (at your option) any later version.
-
-This library is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-Library General Public License for more details.
-
-You should have received a copy of the GNU Library General Public
-License along with the Gnome Library; see the file COPYING.LIB. If not,
-write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.
-"""
- dirname = os.path.abspath(os.path.dirname(__file__))
- filename = os.path.join(dirname, 'data', 'gtk-logo-rgb.gif')
- pixbuf = GdkPixbuf.Pixbuf.new_from_file(filename)
- transparent = pixbuf.add_alpha(True, 0xff, 0xff, 0xff)
-
- about = Gtk.AboutDialog(parent=window,
- program_name='GTK Code Demos',
- version='0.1',
- copyright='(C) 2010 The PyGI Team',
- license=license,
- website='http://live.gnome.org/PyGI',
- comments='Program to demonstrate PyGI functions.',
- authors=authors,
- documenters=documentors,
- logo=transparent,
- title='About GTK Code Demos')
-
- about.connect('response', widget_destroy)
- about.show()
-
-
-action_entries = (
- ("FileMenu", None, "_File"), # name, stock id, label
- ("OpenMenu", None, "_Open"), # name, stock id, label
- ("PreferencesMenu", None, "_Preferences"), # name, stock id, label
- ("ColorMenu", None, "_Color"), # name, stock id, label
- ("ShapeMenu", None, "_Shape"), # name, stock id, label
- ("HelpMenu", None, "_Help"), # name, stock id, label
- ("New", Gtk.STOCK_NEW, # name, stock id
- "_New", "N", # label, accelerator
- "Create a new file", # tooltip
- activate_action),
- ("File1", None, # name, stock id
- "File1", None, # label, accelerator
- "Open first file", # tooltip
- activate_action),
- ("Save", Gtk.STOCK_SAVE, # name, stock id
- "_Save", "S", # label, accelerator
- "Save current file", # tooltip
- activate_action),
- ("SaveAs", Gtk.STOCK_SAVE, # name, stock id
- "Save _As...", None, # label, accelerator
- "Save to a file", # tooltip
- activate_action),
- ("Quit", Gtk.STOCK_QUIT, # name, stock id
- "_Quit", "Q", # label, accelerator
- "Quit", # tooltip
- activate_action),
- ("About", None, # name, stock id
- "_About", "A", # label, accelerator
- "About", # tooltip
- about_cb),
- ("Logo", "demo-gtk-logo", # name, stock id
- None, None, # label, accelerator
- "GTK", # tooltip
- activate_action),
-)
-
-toggle_action_entries = (
- ("Bold", Gtk.STOCK_BOLD, # name, stock id
- "_Bold", "B", # label, accelerator
- "Bold", # tooltip
- activate_action,
- True), # is_active
- ("DarkTheme", None, # name, stock id
- "_Prefer Dark Theme", None, # label, accelerator
- "Prefer Dark Theme", # tooltip
- activate_action,
- False), # is_active
-)
-
-(COLOR_RED,
- COLOR_GREEN,
- COLOR_BLUE) = range(3)
-
-color_action_entries = (
- ("Red", None, # name, stock id
- "_Red", "R", # label, accelerator
- "Blood", COLOR_RED), # tooltip, value
- ("Green", None, # name, stock id
- "_Green", "G", # label, accelerator
- "Grass", COLOR_GREEN), # tooltip, value
- ("Blue", None, # name, stock id
- "_Blue", "B", # label, accelerator
- "Sky", COLOR_BLUE), # tooltip, value
-)
-
-(SHAPE_SQUARE,
- SHAPE_RECTANGLE,
- SHAPE_OVAL) = range(3)
-
-shape_action_entries = (
- ("Square", None, # name, stock id
- "_Square", "S", # label, accelerator
- "Square", SHAPE_SQUARE), # tooltip, value
- ("Rectangle", None, # name, stock id
- "_Rectangle", "R", # label, accelerator
- "Rectangle", SHAPE_RECTANGLE), # tooltip, value
- ("Oval", None, # name, stock id
- "_Oval", "O", # label, accelerator
- "Egg", SHAPE_OVAL), # tooltip, value
-)
-
-ui_info = """
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-"""
-
-
-def _quit(*args):
- Gtk.main_quit()
-
-
-def register_stock_icons():
- """
- This function registers our custom toolbar icons, so they can be themed.
- It's totally optional to do this, you could just manually insert icons
- and have them not be themeable, especially if you never expect people
- to theme your app.
- """
- '''
- item = Gtk.StockItem()
- item.stock_id = 'demo-gtk-logo'
- item.label = '_GTK!'
- item.modifier = 0
- item.keyval = 0
- item.translation_domain = None
-
- Gtk.stock_add(item, 1)
- '''
- global _demoapp
-
- factory = Gtk.IconFactory()
- factory.add_default()
-
- if _demoapp is None:
- filename = os.path.join('data', 'gtk-logo-rgb.gif')
- else:
- filename = _demoapp.find_file('gtk-logo-rgb.gif')
-
- pixbuf = GdkPixbuf.Pixbuf.new_from_file(filename)
- transparent = pixbuf.add_alpha(True, 0xff, 0xff, 0xff)
- icon_set = Gtk.IconSet.new_from_pixbuf(transparent)
-
- factory.add('demo-gtk-logo', icon_set)
-
-
-class ToolMenuAction(Gtk.Action):
- __gtype_name__ = "GtkToolMenuAction"
-
- def do_create_tool_item(self):
- return Gtk.MenuToolButton()
-
-
-def main(demoapp=None):
- global infobar
- global window
- global messagelabel
- global _demoapp
-
- _demoapp = demoapp
-
- register_stock_icons()
-
- window = Gtk.Window()
- window.set_title('Application Window')
- window.set_icon_name('gtk-open')
- window.connect_after('destroy', _quit)
- table = Gtk.Table(n_rows=1,
- n_columns=5,
- homogeneous=False)
- window.add(table)
-
- action_group = Gtk.ActionGroup(name='AppWindowActions')
- open_action = ToolMenuAction(name='Open',
- stock_id=Gtk.STOCK_OPEN,
- label='_Open',
- tooltip='Open a file')
-
- action_group.add_action(open_action)
- action_group.add_actions(action_entries)
- action_group.add_toggle_actions(toggle_action_entries)
- action_group.add_radio_actions(color_action_entries,
- COLOR_RED,
- activate_radio_action)
- action_group.add_radio_actions(shape_action_entries,
- SHAPE_SQUARE,
- activate_radio_action)
-
- merge = Gtk.UIManager()
- merge.insert_action_group(action_group, 0)
- window.add_accel_group(merge.get_accel_group())
-
- merge.add_ui_from_string(ui_info)
-
- bar = merge.get_widget('/MenuBar')
- bar.show()
- table.attach(bar, 0, 1, 0, 1,
- Gtk.AttachOptions.EXPAND | Gtk.AttachOptions.FILL,
- 0, 0, 0)
-
- bar = merge.get_widget('/ToolBar')
- bar.show()
- table.attach(bar, 0, 1, 1, 2,
- Gtk.AttachOptions.EXPAND | Gtk.AttachOptions.FILL,
- 0, 0, 0)
-
- infobar = Gtk.InfoBar()
- infobar.set_no_show_all(True)
- messagelabel = Gtk.Label()
- messagelabel.show()
- infobar.get_content_area().pack_start(messagelabel, True, True, 0)
- infobar.add_button(Gtk.STOCK_OK, Gtk.ResponseType.OK)
- infobar.connect('response', lambda a, b: Gtk.Widget.hide(a))
-
- table.attach(infobar, 0, 1, 2, 3,
- Gtk.AttachOptions.EXPAND | Gtk.AttachOptions.FILL,
- 0, 0, 0)
-
- sw = Gtk.ScrolledWindow(hadjustment=None,
- vadjustment=None)
- sw.set_shadow_type(Gtk.ShadowType.IN)
- table.attach(sw, 0, 1, 3, 4,
- Gtk.AttachOptions.EXPAND | Gtk.AttachOptions.FILL,
- Gtk.AttachOptions.EXPAND | Gtk.AttachOptions.FILL,
- 0, 0)
-
- contents = Gtk.TextView()
- contents.grab_focus()
- sw.add(contents)
-
- # Create statusbar
- statusbar = Gtk.Statusbar()
- table.attach(statusbar, 0, 1, 4, 5,
- Gtk.AttachOptions.EXPAND | Gtk.AttachOptions.FILL,
- 0, 0, 0)
-
- # show text widget info in the statusbar
- buffer = contents.get_buffer()
- buffer.connect('changed', update_statusbar, statusbar)
- buffer.connect('mark_set', mark_set_callback, statusbar)
-
- update_statusbar(buffer, statusbar)
-
- window.set_default_size(200, 200)
- window.show_all()
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/assistant.py b/examples/demo/demos/assistant.py
deleted file mode 100644
index 9e729e9..0000000
--- a/examples/demo/demos/assistant.py
+++ /dev/null
@@ -1,135 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "Assistant"
-description = """
-Demonstrates a sample multistep assistant. Assistants are used to divide
-an operation into several simpler sequential steps, and to guide the user
-through these steps.
-"""
-
-
-from gi.repository import Gtk
-
-
-class AssistantApp:
- def __init__(self):
- self.assistant = Gtk.Assistant()
- self.assistant.set_default_size(-1, 300)
-
- self.create_page1()
- self.create_page2()
- self.create_page3()
-
- self.assistant.connect('cancel', self.on_close_cancel)
- self.assistant.connect('close', self.on_close_cancel)
- self.assistant.connect('apply', self.on_apply)
- self.assistant.connect('prepare', self.on_prepare)
-
- self.assistant.show()
-
- def on_close_cancel(self, assistant):
- assistant.destroy()
- Gtk.main_quit()
-
- def on_apply(self, assistant):
- # apply changes here; this is a fictional example so just do
- # nothing here
- pass
-
- def on_prepare(self, assistant, page):
- current_page = assistant.get_current_page()
- n_pages = assistant.get_n_pages()
- title = 'Sample assistant (%d of %d)' % (current_page + 1, n_pages)
- assistant.set_title(title)
-
- def on_entry_changed(self, widget):
- page_number = self.assistant.get_current_page()
- current_page = self.assistant.get_nth_page(page_number)
- text = widget.get_text()
-
- if text:
- self.assistant.set_page_complete(current_page, True)
- else:
- self.assistant.set_page_complete(current_page, False)
-
- def create_page1(self):
- box = Gtk.HBox(homogeneous=False,
- spacing=12)
- box.set_border_width(12)
- label = Gtk.Label(label='You must fill out this entry to continue:')
- box.pack_start(label, False, False, 0)
-
- entry = Gtk.Entry()
- box.pack_start(entry, True, True, 0)
- entry.connect('changed', self.on_entry_changed)
-
- box.show_all()
- self.assistant.append_page(box)
- self.assistant.set_page_title(box, 'Page 1')
- self.assistant.set_page_type(box, Gtk.AssistantPageType.INTRO)
-
- pixbuf = self.assistant.render_icon(Gtk.STOCK_DIALOG_INFO,
- Gtk.IconSize.DIALOG,
- None)
-
- self.assistant.set_page_header_image(box, pixbuf)
-
- def create_page2(self):
- box = Gtk.VBox(homogeneous=False,
- spacing=12)
- box.set_border_width(12)
-
- checkbutton = Gtk.CheckButton(label='This is optional data, you may continue even if you do not check this')
- box.pack_start(checkbutton, False, False, 0)
-
- box.show_all()
-
- self.assistant.append_page(box)
- self.assistant.set_page_complete(box, True)
- self.assistant.set_page_title(box, 'Page 2')
-
- pixbuf = self.assistant.render_icon(Gtk.STOCK_DIALOG_INFO,
- Gtk.IconSize.DIALOG,
- None)
- self.assistant.set_page_header_image(box, pixbuf)
-
- def create_page3(self):
- label = Gtk.Label(label='This is a confirmation page, press "Apply" to apply changes')
- label.show()
- self.assistant.append_page(label)
- self.assistant.set_page_complete(label, True)
- self.assistant.set_page_title(label, 'Confirmation')
- self.assistant.set_page_type(label, Gtk.AssistantPageType.CONFIRM)
-
- pixbuf = self.assistant.render_icon(Gtk.STOCK_DIALOG_INFO,
- Gtk.IconSize.DIALOG,
- None)
- self.assistant.set_page_header_image(label, pixbuf)
-
-
-def main(demoapp=None):
- AssistantApp()
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/builder.py b/examples/demo/demos/builder.py
deleted file mode 100644
index 47e09a4..0000000
--- a/examples/demo/demos/builder.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "Builder"
-description = """
-Demonstrates an interface loaded from a XML description.
-"""
-
-
-import os
-
-from gi.repository import Gtk
-
-
-class BuilderApp:
- def __init__(self, demoapp):
- self.demoapp = demoapp
-
- self.builder = Gtk.Builder()
- if demoapp is None:
- filename = os.path.join('data', 'demo.ui')
- else:
- filename = demoapp.find_file('demo.ui')
-
- self.builder.add_from_file(filename)
- self.builder.connect_signals(self)
-
- window = self.builder.get_object('window1')
- window.connect('destroy', lambda x: Gtk.main_quit())
- window.show_all()
-
- def about_activate(self, action):
- about_dlg = self.builder.get_object('aboutdialog1')
- about_dlg.run()
- about_dlg.hide()
-
- def quit_activate(self, action):
- Gtk.main_quit()
-
-
-def main(demoapp=None):
- BuilderApp(demoapp)
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/button_box.py b/examples/demo/demos/button_box.py
deleted file mode 100644
index be94984..0000000
--- a/examples/demo/demos/button_box.py
+++ /dev/null
@@ -1,122 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "Button Boxes"
-description = """
-The Button Box widgets are used to arrange buttons with padding.
-"""
-
-
-from gi.repository import Gtk
-
-
-class ButtonBoxApp:
- def __init__(self):
- window = Gtk.Window()
- window.set_title('Button Boxes')
- window.connect('destroy', lambda x: Gtk.main_quit())
- window.set_border_width(10)
-
- main_vbox = Gtk.VBox(homogeneous=False, spacing=0)
- window.add(main_vbox)
-
- frame_horz = Gtk.Frame(label='Horizontal Button Boxes')
- main_vbox.pack_start(frame_horz, True, True, 10)
-
- vbox = Gtk.VBox(homogeneous=False, spacing=0)
- vbox.set_border_width(10)
- frame_horz.add(vbox)
-
- vbox.pack_start(
- self.create_bbox(True, 'Spread', 40, Gtk.ButtonBoxStyle.SPREAD),
- True, True, 0)
-
- vbox.pack_start(
- self.create_bbox(True, 'Edge', 40, Gtk.ButtonBoxStyle.EDGE),
- True, True, 5)
-
- vbox.pack_start(
- self.create_bbox(True, 'Start', 40, Gtk.ButtonBoxStyle.START),
- True, True, 5)
-
- vbox.pack_start(
- self.create_bbox(True, 'End', 40, Gtk.ButtonBoxStyle.END),
- True, True, 5)
-
- frame_vert = Gtk.Frame(label='Vertical Button Boxes')
- main_vbox.pack_start(frame_vert, True, True, 10)
-
- hbox = Gtk.HBox(homogeneous=False, spacing=0)
- hbox.set_border_width(10)
- frame_vert.add(hbox)
-
- hbox.pack_start(
- self.create_bbox(False, 'Spread', 30, Gtk.ButtonBoxStyle.SPREAD),
- True, True, 0)
-
- hbox.pack_start(
- self.create_bbox(False, 'Edge', 30, Gtk.ButtonBoxStyle.EDGE),
- True, True, 5)
-
- hbox.pack_start(
- self.create_bbox(False, 'Start', 30, Gtk.ButtonBoxStyle.START),
- True, True, 5)
-
- hbox.pack_start(
- self.create_bbox(False, 'End', 30, Gtk.ButtonBoxStyle.END),
- True, True, 5)
-
- window.show_all()
-
- def create_bbox(self, is_horizontal, title, spacing, layout):
- frame = Gtk.Frame(label=title)
-
- if is_horizontal:
- bbox = Gtk.HButtonBox()
- else:
- bbox = Gtk.VButtonBox()
-
- bbox.set_border_width(5)
- frame.add(bbox)
-
- bbox.set_layout(layout)
- bbox.set_spacing(spacing)
-
- # FIXME: GtkButton consturctor should take a stock_id
- button = Gtk.Button.new_from_stock(Gtk.STOCK_OK)
- bbox.add(button)
-
- button = Gtk.Button.new_from_stock(Gtk.STOCK_CANCEL)
- bbox.add(button)
-
- button = Gtk.Button.new_from_stock(Gtk.STOCK_HELP)
- bbox.add(button)
-
- return frame
-
-
-def main(demoapp=None):
- ButtonBoxApp()
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/clipboard.py b/examples/demo/demos/clipboard.py
deleted file mode 100644
index 5a88828..0000000
--- a/examples/demo/demos/clipboard.py
+++ /dev/null
@@ -1,228 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "Clipboard"
-description = """
-GtkClipboard is used for clipboard handling. This demo shows how to
-copy and paste text to and from the clipboard.
-
-It also shows how to transfer images via the clipboard or via
-drag-and-drop, and how to make clipboard contents persist after
-the application exits. Clipboard persistence requires a clipboard
-manager to run.
-"""
-
-
-from gi.repository import Gtk, Gdk
-
-
-class ClipboardApp:
- def __init__(self):
- self.window = Gtk.Window()
- self.window.set_title('Clipboard demo')
- self.window.connect('destroy', lambda w: Gtk.main_quit())
-
- vbox = Gtk.VBox(homogeneous=False, spacing=0)
- vbox.set_border_width(8)
- self.window.add(vbox)
-
- label = Gtk.Label(label='"Copy" will copy the text\nin the entry to the clipboard')
- vbox.pack_start(label, False, False, 0)
-
- hbox = Gtk.HBox(homogeneous=False, spacing=4)
- hbox.set_border_width(8)
- vbox.pack_start(hbox, False, False, 0)
-
- # create first entry
- entry = Gtk.Entry()
- hbox.pack_start(entry, True, True, 0)
-
- # create button
- button = Gtk.Button.new_from_stock(Gtk.STOCK_COPY)
- hbox.pack_start(button, False, False, 0)
- button.connect('clicked', self.copy_button_clicked, entry)
-
- label = Gtk.Label(label='"Paste" will paste the text from the clipboard to the entry')
- vbox.pack_start(label, False, False, 0)
-
- hbox = Gtk.HBox(homogeneous=False, spacing=4)
- hbox.set_border_width(8)
- vbox.pack_start(hbox, False, False, 0)
-
- # create secondary entry
- entry = Gtk.Entry()
- hbox.pack_start(entry, True, True, 0)
- # create button
- button = Gtk.Button.new_from_stock(Gtk.STOCK_PASTE)
- hbox.pack_start(button, False, False, 0)
- button.connect('clicked', self.paste_button_clicked, entry)
-
- label = Gtk.Label(label='Images can be transferred via the clipboard, too')
- vbox.pack_start(label, False, False, 0)
-
- hbox = Gtk.HBox(homogeneous=False, spacing=4)
- hbox.set_border_width(8)
- vbox.pack_start(hbox, False, False, 0)
-
- # create the first image
- image = Gtk.Image(stock=Gtk.STOCK_DIALOG_WARNING,
- icon_size=Gtk.IconSize.BUTTON)
-
- ebox = Gtk.EventBox()
- ebox.add(image)
- hbox.add(ebox)
-
- # make ebox a drag source
- ebox.drag_source_set(Gdk.ModifierType.BUTTON1_MASK,
- None, Gdk.DragAction.COPY)
- ebox.drag_source_add_image_targets()
- ebox.connect('drag-begin', self.drag_begin, image)
- ebox.connect('drag-data-get', self.drag_data_get, image)
-
- # accept drops on ebox
- ebox.drag_dest_set(Gtk.DestDefaults.ALL,
- None, Gdk.DragAction.COPY)
- ebox.drag_dest_add_image_targets()
- ebox.connect('drag-data-received', self.drag_data_received, image)
-
- # context menu on ebox
- ebox.connect('button-press-event', self.button_press, image)
-
- # create the second image
- image = Gtk.Image(stock=Gtk.STOCK_STOP,
- icon_size=Gtk.IconSize.BUTTON)
-
- ebox = Gtk.EventBox()
- ebox.add(image)
- hbox.add(ebox)
-
- # make ebox a drag source
- ebox.drag_source_set(Gdk.ModifierType.BUTTON1_MASK,
- None, Gdk.DragAction.COPY)
- ebox.drag_source_add_image_targets()
- ebox.connect('drag-begin', self.drag_begin, image)
- ebox.connect('drag-data-get', self.drag_data_get, image)
-
- # accept drops on ebox
- ebox.drag_dest_set(Gtk.DestDefaults.ALL,
- None, Gdk.DragAction.COPY)
- ebox.drag_dest_add_image_targets()
- ebox.connect('drag-data-received', self.drag_data_received, image)
-
- # context menu on ebox
- ebox.connect('button-press-event', self.button_press, image)
-
- # tell the clipboard manager to make data persistent
- # FIXME: Allow sending strings a Atoms and convert in PyGI
- atom = Gdk.atom_intern('CLIPBOARD', True)
- clipboard = Gtk.Clipboard.get(atom)
- clipboard.set_can_store(None)
-
- self.window.show_all()
-
- def copy_button_clicked(self, button, entry):
- # get the default clipboard
- atom = Gdk.atom_intern('CLIPBOARD', True)
- clipboard = entry.get_clipboard(atom)
-
- # set the clipboard's text
- # FIXME: don't require passing length argument
- clipboard.set_text(entry.get_text(), -1)
-
- def paste_received(self, clipboard, text, entry):
- if text is not None:
- entry.set_text(text)
-
- def paste_button_clicked(self, button, entry):
- # get the default clipboard
- atom = Gdk.atom_intern('CLIPBOARD', True)
- clipboard = entry.get_clipboard(atom)
-
- # set the clipboard's text
- clipboard.request_text(self.paste_received, entry)
-
- def get_image_pixbuf(self, image):
- # FIXME: We should hide storage types in an override
- storage_type = image.get_storage_type()
- if storage_type == Gtk.ImageType.PIXBUF:
- return image.get_pixbuf()
- elif storage_type == Gtk.ImageType.STOCK:
- (stock_id, size) = image.get_stock()
- return image.render_icon(stock_id, size, None)
-
- return None
-
- def drag_begin(self, widget, context, data):
- pixbuf = self.get_image_pixbuf(data)
- Gtk.drag_set_icon_pixbuf(context, pixbuf, -2, -2)
-
- def drag_data_get(self, widget, context, selection_data, info, time, data):
- pixbuf = self.get_image_pixbuf(data)
- selection_data.set_pixbuf(pixbuf)
-
- def drag_data_received(self, widget, context, x, y, selection_data, info, time, data):
- if selection_data.get_length() > 0:
- pixbuf = selection_data.get_pixbuf()
- data.set_from_pixbuf(pixbuf)
-
- def copy_image(self, item, data):
- # get the default clipboard
- atom = Gdk.atom_intern('CLIPBOARD', True)
- clipboard = Gtk.Clipboard.get(atom)
- pixbuf = self.get_image_pixbuf(data)
-
- clipboard.set_image(pixbuf)
-
- def paste_image(self, item, data):
- # get the default clipboard
- atom = Gdk.atom_intern('CLIPBOARD', True)
- clipboard = Gtk.Clipboard.get(atom)
- pixbuf = clipboard.wait_for_image()
-
- if pixbuf is not None:
- data.set_from_pixbuf(pixbuf)
-
- def button_press(self, widget, event, data):
- if event.button != 3:
- return False
-
- self.menu = Gtk.Menu()
-
- item = Gtk.ImageMenuItem.new_from_stock(Gtk.STOCK_COPY, None)
- item.connect('activate', self.copy_image, data)
- item.show()
- self.menu.append(item)
-
- item = Gtk.ImageMenuItem.new_from_stock(Gtk.STOCK_PASTE, None)
- item.connect('activate', self.paste_image, data)
- item.show()
- self.menu.append(item)
-
- self.menu.popup(None, None, None, None, event.button, event.time)
-
-
-def main(demoapp=None):
- ClipboardApp()
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/colorselector.py b/examples/demo/demos/colorselector.py
deleted file mode 100644
index d05ca52..0000000
--- a/examples/demo/demos/colorselector.py
+++ /dev/null
@@ -1,112 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "Color Selector"
-description = """
- GtkColorSelection lets the user choose a color. GtkColorSelectionDialog is
- a prebuilt dialog containing a GtkColorSelection.
- """
-
-
-from gi.repository import Gtk, Gdk
-
-
-class ColorSelectorApp:
- def __init__(self):
- # FIXME: we should allow Gdk.Color to be allocated without parameters
- # Also color doesn't seem to work
- self.color = Gdk.RGBA()
- self.color.red = 0
- self.color.blue = 1
- self.color.green = 0
- self.color.alpha = 1
-
- self.window = Gtk.Window()
- self.window.set_title('Color Selection')
- self.window.set_border_width(8)
- self.window.connect('destroy', lambda w: Gtk.main_quit())
-
- vbox = Gtk.VBox(homogeneous=False,
- spacing=8)
- vbox.set_border_width(8)
- self.window.add(vbox)
-
- # create color swatch area
- frame = Gtk.Frame()
- frame.set_shadow_type(Gtk.ShadowType.IN)
- vbox.pack_start(frame, True, True, 0)
-
- self.da = Gtk.DrawingArea()
- self.da.connect('draw', self.draw_cb)
-
- # set a minimum size
- self.da.set_size_request(200, 200)
- # set the color
- self.da.override_background_color(0, self.color)
- frame.add(self.da)
-
- alignment = Gtk.Alignment(xalign=1.0,
- yalign=0.5,
- xscale=0.0,
- yscale=0.0)
-
- button = Gtk.Button(label='_Change the above color',
- use_underline=True)
- alignment.add(button)
- vbox.pack_start(alignment, False, False, 0)
-
- button.connect('clicked', self.change_color_cb)
-
- self.window.show_all()
-
- def draw_cb(self, widget, cairo_ctx):
- style = widget.get_style_context()
- bg_color = style.get_background_color(0)
- Gdk.cairo_set_source_rgba(cairo_ctx, bg_color)
- cairo_ctx.paint()
-
- return True
-
- def change_color_cb(self, button):
- dialog = Gtk.ColorSelectionDialog(title='Changing color')
- dialog.set_transient_for(self.window)
-
- colorsel = dialog.get_color_selection()
- colorsel.set_previous_rgba(self.color)
- colorsel.set_current_rgba(self.color)
- colorsel.set_has_palette(True)
-
- response = dialog.run()
-
- if response == Gtk.ResponseType.OK:
- self.color = colorsel.get_current_rgba()
- self.da.override_background_color(0, self.color)
-
- dialog.destroy()
-
-
-def main(demoapp=None):
- ColorSelectorApp()
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/combobox.py b/examples/demo/demos/combobox.py
deleted file mode 100644
index 1215f16..0000000
--- a/examples/demo/demos/combobox.py
+++ /dev/null
@@ -1,319 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "Combo boxes"
-description = """
-The ComboBox widget allows to select one option out of a list.
-The ComboBoxEntry additionally allows the user to enter a value
-that is not in the list of options.
-
-How the options are displayed is controlled by cell renderers.
- """
-
-
-from gi.repository import Gtk, Gdk, GdkPixbuf, GLib, GObject
-
-
-(PIXBUF_COL,
- TEXT_COL) = range(2)
-
-
-class MaskEntry(Gtk.Entry):
- __gtype_name__ = 'MaskEntry'
-
- def __init__(self, mask=None):
- self.mask = mask
- super(MaskEntry, self).__init__()
-
- self.connect('changed', self.changed_cb)
-
- self.error_color = Gdk.RGBA()
- self.error_color.red = 1.0
- self.error_color.green = 0.9
- self.error_color_blue = 0.9
- self.error_color.alpha = 1.0
-
- # workaround since override_color doesn't accept None yet
- style_ctx = self.get_style_context()
- self.normal_color = style_ctx.get_color(0)
-
- def set_background(self):
- if self.mask:
- if not GLib.regex_match_simple(self.mask,
- self.get_text(), 0, 0):
- self.override_color(0, self.error_color)
- return
-
- self.override_color(0, self.normal_color)
-
- def changed_cb(self, entry):
- self.set_background()
-
-
-class ComboboxApp:
- def __init__(self, demoapp):
- self.demoapp = demoapp
-
- self.window = Gtk.Window()
- self.window.set_title('Combo boxes')
- self.window.set_border_width(10)
- self.window.connect('destroy', lambda w: Gtk.main_quit())
-
- vbox = Gtk.VBox(homogeneous=False, spacing=2)
- self.window.add(vbox)
-
- frame = Gtk.Frame(label='Some stock icons')
- vbox.pack_start(frame, False, False, 0)
-
- box = Gtk.VBox(homogeneous=False, spacing=0)
- box.set_border_width(5)
- frame.add(box)
-
- model = self.create_stock_icon_store()
- combo = Gtk.ComboBox(model=model)
- box.add(combo)
-
- renderer = Gtk.CellRendererPixbuf()
- combo.pack_start(renderer, False)
-
- # FIXME: override set_attributes
- combo.add_attribute(renderer, 'pixbuf', PIXBUF_COL)
- combo.set_cell_data_func(renderer, self.set_sensitive, None)
-
- renderer = Gtk.CellRendererText()
- combo.pack_start(renderer, True)
- combo.add_attribute(renderer, 'text', TEXT_COL)
- combo.set_cell_data_func(renderer, self.set_sensitive, None)
-
- combo.set_row_separator_func(self.is_separator, None)
- combo.set_active(0)
-
- # a combobox demonstrating trees
- frame = Gtk.Frame(label='Where are we ?')
- vbox.pack_start(frame, False, False, 0)
-
- box = Gtk.VBox(homogeneous=False, spacing=0)
- box.set_border_width(5)
- frame.add(box)
-
- model = self.create_capital_store()
- combo = Gtk.ComboBox(model=model)
- box.add(combo)
-
- renderer = Gtk.CellRendererText()
- combo.pack_start(renderer, True)
- combo.add_attribute(renderer, 'text', 0)
- combo.set_cell_data_func(renderer, self.is_capital_sensistive, None)
-
- # FIXME: make new_from_indices work
- # make constructor take list or string of indices
- path = Gtk.TreePath.new_from_string('0:8')
- treeiter = model.get_iter(path)
- combo.set_active_iter(treeiter)
-
- # A GtkComboBoxEntry with validation.
-
- frame = Gtk.Frame(label='Editable')
- vbox.pack_start(frame, False, False, 0)
-
- box = Gtk.VBox(homogeneous=False, spacing=0)
- box.set_border_width(5)
- frame.add(box)
-
- combo = Gtk.ComboBoxText.new_with_entry()
- self.fill_combo_entry(combo)
- box.add(combo)
-
- entry = MaskEntry(mask='^([0-9]*|One|Two|2\302\275|Three)$')
-
- Gtk.Container.remove(combo, combo.get_child())
- combo.add(entry)
-
- # A combobox with string IDs
-
- frame = Gtk.Frame(label='String IDs')
- vbox.pack_start(frame, False, False, 0)
-
- box = Gtk.VBox(homogeneous=False, spacing=0)
- box.set_border_width(5)
- frame.add(box)
-
- # FIXME: model is not setup when constructing Gtk.ComboBoxText()
- # so we call new() - Gtk should fix this to setup the model
- # in __init__, not in the constructor
- combo = Gtk.ComboBoxText.new()
- combo.append('never', 'Not visible')
- combo.append('when-active', 'Visible when active')
- combo.append('always', 'Always visible')
- box.add(combo)
-
- entry = Gtk.Entry()
-
- combo.bind_property('active-id',
- entry, 'text',
- GObject.BindingFlags.BIDIRECTIONAL)
-
- box.add(entry)
- self.window.show_all()
-
- def strip_underscore(self, s):
- return s.replace('_', '')
-
- def create_stock_icon_store(self):
- stock_id = (Gtk.STOCK_DIALOG_WARNING,
- Gtk.STOCK_STOP,
- Gtk.STOCK_NEW,
- Gtk.STOCK_CLEAR,
- None,
- Gtk.STOCK_OPEN)
-
- cellview = Gtk.CellView()
- store = Gtk.ListStore(GdkPixbuf.Pixbuf, str)
-
- for id in stock_id:
- if id is not None:
- pixbuf = cellview.render_icon(id, Gtk.IconSize.BUTTON, None)
- item = Gtk.stock_lookup(id)
- label = self.strip_underscore(item.label)
- store.append((pixbuf, label))
- else:
- store.append((None, 'separator'))
-
- return store
-
- def set_sensitive(self, cell_layout, cell, tree_model, treeiter, data):
- """
- A GtkCellLayoutDataFunc that demonstrates how one can control
- sensitivity of rows. This particular function does nothing
- useful and just makes the second row insensitive.
- """
-
- path = tree_model.get_path(treeiter)
- indices = path.get_indices()
-
- sensitive = not (indices[0] == 1)
-
- cell.set_property('sensitive', sensitive)
-
- def is_separator(self, model, treeiter, data):
- """
- A GtkTreeViewRowSeparatorFunc that demonstrates how rows can be
- rendered as separators. This particular function does nothing
- useful and just turns the fourth row into a separator.
- """
-
- path = model.get_path(treeiter)
-
- indices = path.get_indices()
- result = (indices[0] == 4)
-
- return result
-
- def create_capital_store(self):
- capitals = (
- {'group': 'A - B', 'capital': None},
- {'group': None, 'capital': 'Albany'},
- {'group': None, 'capital': 'Annapolis'},
- {'group': None, 'capital': 'Atlanta'},
- {'group': None, 'capital': 'Augusta'},
- {'group': None, 'capital': 'Austin'},
- {'group': None, 'capital': 'Baton Rouge'},
- {'group': None, 'capital': 'Bismarck'},
- {'group': None, 'capital': 'Boise'},
- {'group': None, 'capital': 'Boston'},
- {'group': 'C - D', 'capital': None},
- {'group': None, 'capital': 'Carson City'},
- {'group': None, 'capital': 'Charleston'},
- {'group': None, 'capital': 'Cheyeene'},
- {'group': None, 'capital': 'Columbia'},
- {'group': None, 'capital': 'Columbus'},
- {'group': None, 'capital': 'Concord'},
- {'group': None, 'capital': 'Denver'},
- {'group': None, 'capital': 'Des Moines'},
- {'group': None, 'capital': 'Dover'},
- {'group': 'E - J', 'capital': None},
- {'group': None, 'capital': 'Frankfort'},
- {'group': None, 'capital': 'Harrisburg'},
- {'group': None, 'capital': 'Hartford'},
- {'group': None, 'capital': 'Helena'},
- {'group': None, 'capital': 'Honolulu'},
- {'group': None, 'capital': 'Indianapolis'},
- {'group': None, 'capital': 'Jackson'},
- {'group': None, 'capital': 'Jefferson City'},
- {'group': None, 'capital': 'Juneau'},
- {'group': 'K - O', 'capital': None},
- {'group': None, 'capital': 'Lansing'},
- {'group': None, 'capital': 'Lincon'},
- {'group': None, 'capital': 'Little Rock'},
- {'group': None, 'capital': 'Madison'},
- {'group': None, 'capital': 'Montgomery'},
- {'group': None, 'capital': 'Montpelier'},
- {'group': None, 'capital': 'Nashville'},
- {'group': None, 'capital': 'Oklahoma City'},
- {'group': None, 'capital': 'Olympia'},
- {'group': 'P - S', 'capital': None},
- {'group': None, 'capital': 'Phoenix'},
- {'group': None, 'capital': 'Pierre'},
- {'group': None, 'capital': 'Providence'},
- {'group': None, 'capital': 'Raleigh'},
- {'group': None, 'capital': 'Richmond'},
- {'group': None, 'capital': 'Sacramento'},
- {'group': None, 'capital': 'Salem'},
- {'group': None, 'capital': 'Salt Lake City'},
- {'group': None, 'capital': 'Santa Fe'},
- {'group': None, 'capital': 'Springfield'},
- {'group': None, 'capital': 'St. Paul'},
- {'group': 'T - Z', 'capital': None},
- {'group': None, 'capital': 'Tallahassee'},
- {'group': None, 'capital': 'Topeka'},
- {'group': None, 'capital': 'Trenton'}
- )
-
- parent = None
-
- store = Gtk.TreeStore(str)
-
- for item in capitals:
- if item['group']:
- parent = store.append(None, (item['group'],))
- elif item['capital']:
- store.append(parent, (item['capital'],))
-
- return store
-
- def is_capital_sensistive(self, cell_layout, cell, tree_model, treeiter, data):
- sensitive = not tree_model.iter_has_child(treeiter)
- cell.set_property('sensitive', sensitive)
-
- def fill_combo_entry(self, entry):
- entry.append_text('One')
- entry.append_text('Two')
- entry.append_text('2\302\275')
- entry.append_text('Three')
-
-
-def main(demoapp=None):
- ComboboxApp(demoapp)
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/data/alphatest.png b/examples/demo/demos/data/alphatest.png
deleted file mode 100644
index eb5885f..0000000
Binary files a/examples/demo/demos/data/alphatest.png and /dev/null differ
diff --git a/examples/demo/demos/data/apple-red.png b/examples/demo/demos/data/apple-red.png
deleted file mode 100644
index b0a24e9..0000000
Binary files a/examples/demo/demos/data/apple-red.png and /dev/null differ
diff --git a/examples/demo/demos/data/background.jpg b/examples/demo/demos/data/background.jpg
deleted file mode 100644
index 86c006a..0000000
Binary files a/examples/demo/demos/data/background.jpg and /dev/null differ
diff --git a/examples/demo/demos/data/brick.png b/examples/demo/demos/data/brick.png
deleted file mode 100644
index d413cd2..0000000
Binary files a/examples/demo/demos/data/brick.png and /dev/null differ
diff --git a/examples/demo/demos/data/brick2.png b/examples/demo/demos/data/brick2.png
deleted file mode 100644
index cfcd079..0000000
Binary files a/examples/demo/demos/data/brick2.png and /dev/null differ
diff --git a/examples/demo/demos/data/css_accordion.css b/examples/demo/demos/data/css_accordion.css
deleted file mode 100644
index a243427..0000000
--- a/examples/demo/demos/data/css_accordion.css
+++ /dev/null
@@ -1,52 +0,0 @@
-@import url("resource://css_accordion/reset.css");
-
-* {
- transition-property: color, background-color, border-color, background-image, padding, border-width;
- transition-duration: 1s;
-
- font: Sans 20px;
-}
-
-GtkWindow {
- background: linear-gradient(153deg, #151515, #151515 5px, transparent 5px) 0 0,
- linear-gradient(333deg, #151515, #151515 5px, transparent 5px) 10px 5px,
- linear-gradient(153deg, #222, #222 5px, transparent 5px) 0 5px,
- linear-gradient(333deg, #222, #222 5px, transparent 5px) 10px 10px,
- linear-gradient(90deg, #1b1b1b, #1b1b1b 10px, transparent 10px),
- linear-gradient(#1d1d1d, #1d1d1d 25%, #1a1a1a 25%, #1a1a1a 50%, transparent 50%, transparent 75%, #242424 75%, #242424);
- background-color: #131313;
- background-size: 20px 20px;
-}
-
-.button {
- color: black;
- background-color: #bbb;
- border-style: solid;
- border-width: 2px 0 2px 2px;
- border-color: #333;
-
- padding: 12px 4px;
-}
-
-.button:first-child {
- border-radius: 5px 0 0 5px;
-}
-
-.button:last-child {
- border-radius: 0 5px 5px 0;
- border-width: 2px;
-}
-
-.button:hover {
- padding: 12px 48px;
- background-color: #4870bc;
-}
-
-.button *:hover {
- color: white;
-}
-
-.button:hover:active,
-.button:active {
- background-color: #993401;
-}
diff --git a/examples/demo/demos/data/css_basics.css b/examples/demo/demos/data/css_basics.css
deleted file mode 100644
index 62dba7a..0000000
--- a/examples/demo/demos/data/css_basics.css
+++ /dev/null
@@ -1,22 +0,0 @@
-/* You can edit the text in this window to change the
- * appearance of this Window.
- * Be careful, if you screw it up, nothing might be visible
- * anymore. :)
- */
-
-/* This CSS resets all properties to their defaults values
- * and overrides all user settings and the theme in use */
-@import url("resource://css_basics/reset.css");
-
-/* Set a very futuristic style by default */
-* {
- color: green;
- font-family: Monospace;
- border: 1px solid;
-}
-
-/* Make sure selections are visible */
-:selected {
- background-color: darkGreen;
- color: black;
-}
diff --git a/examples/demo/demos/data/css_multiplebgs.css b/examples/demo/demos/data/css_multiplebgs.css
deleted file mode 100644
index eb9d4d6..0000000
--- a/examples/demo/demos/data/css_multiplebgs.css
+++ /dev/null
@@ -1,136 +0,0 @@
-/* You can edit the text in this window to change the
- * appearance of this Window.
- * Be careful, if you screw it up, nothing might be visible
- * anymore. :)
- */
-
-/* This CSS resets all properties to their defaults values
- * and overrides all user settings and the theme in use */
-@import url("resource://css_multiplebgs/reset.css");
-@import url("resource://css_multiplebgs/cssview.css");
-
-#canvas {
- transition-property: background-color, background-image;
- transition-duration: 0.5s;
-
- background-color: #4870bc;
-}
-
-/* The gradients below are adapted versions of Lea Verou's CSS3 patterns,
- * licensed under the MIT license:
- * Copyright (c) 2011 Lea Verou, http://lea.verou.me/
- *
- * See https://github.com/LeaVerou/CSS3-Patterns-Gallery
- */
-
-/**********
- * Bricks *
- **********/
-/*
-@define-color brick_hi #d42;
-@define-color brick_lo #b42;
-@define-color brick_hi_backdrop #888;
-@define-color brick_lo_backdrop #999;
-
-#canvas {
- background-color: #999;
- background-image: linear-gradient(205deg, @brick_lo, @brick_lo 23px, transparent 23px),
- linear-gradient(25deg, @brick_hi, @brick_hi 23px, transparent 23px),
- linear-gradient(205deg, @brick_lo, @brick_lo 23px, transparent 23px),
- linear-gradient(25deg, @brick_hi, @brick_hi 23px, transparent 23px);
- background-size: 58px 58px;
- background-position: 0px 6px, 4px 31px, 29px 35px, 34px 2px;
-}
-
-#canvas:backdrop {
- background-color: #444;
- background-image: linear-gradient(205deg, @brick_lo_backdrop, @brick_lo_backdrop 23px, transparent 23px),
- linear-gradient(25deg, @brick_hi_backdrop, @brick_hi_backdrop 23px, transparent 23px),
- linear-gradient(205deg, @brick_lo_backdrop, @brick_lo_backdrop 23px, transparent 23px),
- linear-gradient(25deg, @brick_hi_backdrop, @brick_hi_backdrop 23px, transparent 23px);
- background-size: 58px 58px;
- background-position: 0px 6px, 4px 31px, 29px 35px, 34px 2px;
-}
-*/
-
-/*
-#bricks-button {
- background-color: #eef;
- background-image: -gtk-scaled(url('resource://css_multiplebgs/brick.png'),url('resource://css_multiplebgs/brick2.png'));
- background-repeat: no-repeat;
- background-position: center;
-}
-
-*/
-/**********
- * Tartan *
- **********/
-/*
-@define-color tartan_bg #662e2c;
-@define-color tartan_bg_backdrop #333;
-
-#canvas {
- background-color: @tartan_bg;
- background-image: repeating-linear-gradient(transparent, transparent 50px, rgba(0,0,0,.4) 50px,
- rgba(0,0,0,.4) 53px, transparent 53px, transparent 63px,
- rgba(0,0,0,.4) 63px, rgba(0,0,0,.4) 66px, transparent 66px,
- transparent 116px, rgba(0,0,0,.5) 116px, rgba(0,0,0,.5) 166px,
- rgba(255,255,255,.2) 166px, rgba(255,255,255,.2) 169px, rgba(0,0,0,.5) 169px,
- rgba(0,0,0,.5) 179px, rgba(255,255,255,.2) 179px, rgba(255,255,255,.2) 182px,
- rgba(0,0,0,.5) 182px, rgba(0,0,0,.5) 232px, transparent 232px),
- repeating-linear-gradient(90deg, transparent, transparent 50px, rgba(0,0,0,.4) 50px, rgba(0,0,0,.4) 53px,
- transparent 53px, transparent 63px, rgba(0,0,0,.4) 63px, rgba(0,0,0,.4) 66px,
- transparent 66px, transparent 116px, rgba(0,0,0,.5) 116px, rgba(0,0,0,.5) 166px,
- rgba(255,255,255,.2) 166px, rgba(255,255,255,.2) 169px, rgba(0,0,0,.5) 169px,
- rgba(0,0,0,.5) 179px, rgba(255,255,255,.2) 179px, rgba(255,255,255,.2) 182px,
- rgba(0,0,0,.5) 182px, rgba(0,0,0,.5) 232px, transparent 232px),
- repeating-linear-gradient(-55deg, transparent, transparent 1px, rgba(0,0,0,.2) 1px, rgba(0,0,0,.2) 4px,
- transparent 4px, transparent 19px, rgba(0,0,0,.2) 19px,
- rgba(0,0,0,.2) 24px, transparent 24px, transparent 51px, rgba(0,0,0,.2) 51px,
- rgba(0,0,0,.2) 54px, transparent 54px, transparent 74px);
-}
-
-#canvas:backdrop {
- background-color: @tartan_bg_backdrop;
-}
-*/
-
-/***********
- * Stripes *
- ***********/
-
-/*
-@define-color base_bg #4870bc;
-@define-color backdrop_bg #555;
-
-#canvas {
- background-color: @base_bg;
- background-image: linear-gradient(to left, transparent, rgba(255,255,255,.07) 50%, transparent 50%),
- linear-gradient(to left, transparent, rgba(255,255,255,.13) 50%, transparent 50%),
- linear-gradient(to left, transparent, transparent 50%, rgba(255,255,255,.17) 50%),
- linear-gradient(to left, transparent, transparent 50%, rgba(255,255,255,.19) 50%);
- background-size: 29px, 59px, 73px, 109px;
-}
-
-#canvas:backdrop {
- background-color: @backdrop_bg;
-}
-*/
-
-/***************
- * Lined Paper *
- ***************/
-/*
-#canvas {
- background-color: #fff;
- background-image: linear-gradient(90deg, transparent 79px, alpha(#f98195, 0.40) 79px, #f98195 80px, alpha(#f98195, 0.40) 81px, transparent 81px),
- linear-gradient(alpha(#77c5cf, 0.60), alpha(#77c5cf, 0.60) 1px, transparent 1px);
- background-size: 100% 36px;
-}
-
-#canvas:backdrop {
- background-color: #f1f2f4;
- background-image: linear-gradient(90deg, transparent 79px, alpha(#999, 0.40) 79px, #999 80px, alpha(#999, 0.40) 81px, transparent 81px),
- linear-gradient(alpha(#bbb, 0.60), alpha(#bbb, 0.60) 1px, transparent 1px);
-}
-*/
diff --git a/examples/demo/demos/data/cssview.css b/examples/demo/demos/data/cssview.css
deleted file mode 100644
index 5060c39..0000000
--- a/examples/demo/demos/data/cssview.css
+++ /dev/null
@@ -1,41 +0,0 @@
-/* Make the text editor has a nice style */
-.view {
- color: #2e3436;
- font: Monospace;
- background-color: alpha(white, 0.30);
-}
-
-.view:selected {
- color: white;
- background-color: #4a90d9;
-}
-
-.scrollbar.trough,
-.scrollbars-junction {
- background-color: alpha(white, 0.80);
-}
-
-.scrollbar.slider {
- border-width: 3px;
- border-style: solid;
- border-radius: 10px;
- border-color: transparent;
- background-clip: padding-box;
- background-color: #999;
-}
-
-.scrollbar.slider:prelight {
- background-color: #555;
-}
-
-.pane-separator {
- background-color: alpha(white, 0.80);
- background-image: linear-gradient(transparent, transparent 1px, #999 1px, #999 4px, transparent 4px);
- background-size: 40px auto;
- background-repeat: no-repeat;
- background-position: center;
-}
-
-.pane-separator:prelight {
- background-image: linear-gradient(transparent, transparent 1px, #555 1px, #555 4px, transparent 4px);
-}
diff --git a/examples/demo/demos/data/demo.gresource b/examples/demo/demos/data/demo.gresource
deleted file mode 100644
index e19d822..0000000
Binary files a/examples/demo/demos/data/demo.gresource and /dev/null differ
diff --git a/examples/demo/demos/data/demo.gresource.xml b/examples/demo/demos/data/demo.gresource.xml
deleted file mode 100644
index 866769f..0000000
--- a/examples/demo/demos/data/demo.gresource.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-
-
-
- css_accordion.css
- reset.css
-
-
- css_basics.css
- reset.css
-
-
- css_multiplebgs.css
- brick.png
- brick2.png
- cssview.css
- reset.css
-
-
diff --git a/examples/demo/demos/data/demo.ui b/examples/demo/demos/data/demo.ui
deleted file mode 100644
index 57dd232..0000000
--- a/examples/demo/demos/data/demo.ui
+++ /dev/null
@@ -1,258 +0,0 @@
-
-
-
-
-
- GtkBuilder demo
-
-
-
-
-
- 250
- 440
- GtkBuilder demo
-
-
- True
-
-
- True
-
-
- The menubar
-
-
-
-
- False
-
-
-
-
- True
-
-
- The toolbar
-
-
-
-
- False
- 1
-
-
-
-
- automatic
- in
- True
- automatic
-
-
- True
- liststore1
- 3
-
-
- Name list
-
- A list of person with name, surname and age columns
-
-
-
-
-
- Name
-
-
-
- 0
-
-
-
-
-
-
- Surname
-
-
-
- 1
-
-
-
-
-
-
- Age
-
-
-
- 2
-
-
-
-
-
-
-
-
-
-
-
- 2
-
-
-
-
- True
-
-
- False
- 3
-
-
-
-
-
-
diff --git a/examples/demo/demos/data/floppybuddy.gif b/examples/demo/demos/data/floppybuddy.gif
deleted file mode 100644
index ac986c8..0000000
Binary files a/examples/demo/demos/data/floppybuddy.gif and /dev/null differ
diff --git a/examples/demo/demos/data/gnome-applets.png b/examples/demo/demos/data/gnome-applets.png
deleted file mode 100644
index 8d3549e..0000000
Binary files a/examples/demo/demos/data/gnome-applets.png and /dev/null differ
diff --git a/examples/demo/demos/data/gnome-calendar.png b/examples/demo/demos/data/gnome-calendar.png
deleted file mode 100644
index 889f329..0000000
Binary files a/examples/demo/demos/data/gnome-calendar.png and /dev/null differ
diff --git a/examples/demo/demos/data/gnome-foot.png b/examples/demo/demos/data/gnome-foot.png
deleted file mode 100644
index 0476658..0000000
Binary files a/examples/demo/demos/data/gnome-foot.png and /dev/null differ
diff --git a/examples/demo/demos/data/gnome-fs-directory.png b/examples/demo/demos/data/gnome-fs-directory.png
deleted file mode 100644
index 05921a6..0000000
Binary files a/examples/demo/demos/data/gnome-fs-directory.png and /dev/null differ
diff --git a/examples/demo/demos/data/gnome-fs-regular.png b/examples/demo/demos/data/gnome-fs-regular.png
deleted file mode 100644
index 0f5019c..0000000
Binary files a/examples/demo/demos/data/gnome-fs-regular.png and /dev/null differ
diff --git a/examples/demo/demos/data/gnome-gimp.png b/examples/demo/demos/data/gnome-gimp.png
deleted file mode 100644
index f6bbc6d..0000000
Binary files a/examples/demo/demos/data/gnome-gimp.png and /dev/null differ
diff --git a/examples/demo/demos/data/gnome-gmush.png b/examples/demo/demos/data/gnome-gmush.png
deleted file mode 100644
index 0a4b0d0..0000000
Binary files a/examples/demo/demos/data/gnome-gmush.png and /dev/null differ
diff --git a/examples/demo/demos/data/gnome-gsame.png b/examples/demo/demos/data/gnome-gsame.png
deleted file mode 100644
index 01c0611..0000000
Binary files a/examples/demo/demos/data/gnome-gsame.png and /dev/null differ
diff --git a/examples/demo/demos/data/gnu-keys.png b/examples/demo/demos/data/gnu-keys.png
deleted file mode 100644
index 58a3377..0000000
Binary files a/examples/demo/demos/data/gnu-keys.png and /dev/null differ
diff --git a/examples/demo/demos/data/gtk-logo-rgb.gif b/examples/demo/demos/data/gtk-logo-rgb.gif
deleted file mode 100644
index 63c622b..0000000
Binary files a/examples/demo/demos/data/gtk-logo-rgb.gif and /dev/null differ
diff --git a/examples/demo/demos/data/reset.css b/examples/demo/demos/data/reset.css
deleted file mode 100644
index 1c27a8e..0000000
--- a/examples/demo/demos/data/reset.css
+++ /dev/null
@@ -1,68 +0,0 @@
-/* @import this colorsheet to get the default values for every property.
- * This is useful when writing special CSS tests that should not be
- * inluenced by themes - not even the default ones.
- * Keep in mind that the output will be very ugly and not look like
- * anything GTK.
- * Also, when adding new style properties, please add them here.
- */
-
-* {
- color: inherit;
- font-size: inherit;
- background-color: initial;
- font-family: inherit;
- font-style: inherit;
- font-variant: inherit;
- font-weight: inherit;
- text-shadow: inherit;
- icon-shadow: inherit;
- box-shadow: initial;
- margin-top: initial;
- margin-left: initial;
- margin-bottom: initial;
- margin-right: initial;
- padding-top: initial;
- padding-left: initial;
- padding-bottom: initial;
- padding-right: initial;
- border-top-style: initial;
- border-top-width: initial;
- border-left-style: initial;
- border-left-width: initial;
- border-bottom-style: initial;
- border-bottom-width: initial;
- border-right-style: initial;
- border-right-width: initial;
- border-top-left-radius: initial;
- border-top-right-radius: initial;
- border-bottom-right-radius: initial;
- border-bottom-left-radius: initial;
- outline-style: initial;
- outline-width: initial;
- outline-offset: initial;
- background-clip: initial;
- background-origin: initial;
- background-size: initial;
- background-position: initial;
- border-top-color: initial;
- border-right-color: initial;
- border-bottom-color: initial;
- border-left-color: initial;
- outline-color: initial;
- background-repeat: initial;
- background-image: initial;
- border-image-source: initial;
- border-image-repeat: initial;
- border-image-slice: initial;
- border-image-width: initial;
- transition-property: initial;
- transition-duration: initial;
- transition-timing-function: initial;
- transition-delay: initial;
- engine: initial;
- gtk-key-bindings: initial;
-
- -GtkWidget-focus-line-width: 0;
- -GtkWidget-focus-padding: 0;
- -GtkNotebook-initial-gap: 0;
-}
diff --git a/examples/demo/demos/dialogs.py b/examples/demo/demos/dialogs.py
deleted file mode 100644
index 47d6822..0000000
--- a/examples/demo/demos/dialogs.py
+++ /dev/null
@@ -1,156 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "Dialog and Message Boxes"
-description = """
-Dialog widgets are used to pop up a transient window for user feedback.
-"""
-
-from gi.repository import Gtk
-
-
-class DialogsApp:
- def __init__(self):
- self.dialog_counter = 1
-
- self.window = Gtk.Window(title="Dialogs")
- self.window.set_border_width(8)
- self.window.connect('destroy', Gtk.main_quit)
-
- frame = Gtk.Frame(label="Dialogs")
- self.window.add(frame)
-
- vbox = Gtk.VBox(spacing=8)
- vbox.set_border_width(8)
- frame.add(vbox)
-
- # Standard message dialog
- hbox = Gtk.HBox(spacing=8)
- vbox.pack_start(hbox, False, False, 0)
- button = Gtk.Button.new_with_mnemonic("_Message Dialog")
-
- button.connect('clicked',
- self._message_dialog_clicked)
- hbox.pack_start(button, False, False, 0)
-
- vbox.pack_start(Gtk.HSeparator(),
- False, False, 0)
-
- # Interactive dialog
- hbox = Gtk.HBox(spacing=8)
- vbox.pack_start(hbox, False, False, 0)
- vbox2 = Gtk.VBox(spacing=0)
- button = Gtk.Button.new_with_mnemonic("_Interactive Dialog")
-
- button.connect('clicked',
- self._interactive_dialog_clicked)
- hbox.pack_start(vbox2, False, False, 0)
- vbox2.pack_start(button, False, False, 0)
-
- table = Gtk.Table(n_rows=2, n_columns=2, homogeneous=False)
- table.set_row_spacings(4)
- table.set_col_spacings(4)
- hbox.pack_start(table, False, False, 0)
-
- label = Gtk.Label.new_with_mnemonic("_Entry 1")
- table.attach_defaults(label, 0, 1, 0, 1)
-
- self.entry1 = Gtk.Entry()
- table.attach_defaults(self.entry1, 1, 2, 0, 1)
- label.set_mnemonic_widget(self.entry1)
-
- label = Gtk.Label.new_with_mnemonic("E_ntry 2")
-
- table.attach_defaults(label, 0, 1, 1, 2)
-
- self.entry2 = Gtk.Entry()
- table.attach_defaults(self.entry2, 1, 2, 1, 2)
- label.set_mnemonic_widget(self.entry2)
-
- self.window.show_all()
-
- def _interactive_dialog_clicked(self, button):
- dialog = Gtk.Dialog(title='Interactive Dialog',
- transient_for=self.window,
- modal=True,
- destroy_with_parent=True)
- dialog.add_buttons(Gtk.STOCK_OK, Gtk.ResponseType.OK,
- "_Non-stock Button", Gtk.ResponseType.CANCEL)
-
- content_area = dialog.get_content_area()
- hbox = Gtk.HBox(spacing=8)
- hbox.set_border_width(8)
- content_area.pack_start(hbox, False, False, 0)
-
- stock = Gtk.Image(stock=Gtk.STOCK_DIALOG_QUESTION,
- icon_size=Gtk.IconSize.DIALOG)
-
- hbox.pack_start(stock, False, False, 0)
-
- table = Gtk.Table(n_rows=2, n_columns=2, homogeneous=False)
- table.set_row_spacings(4)
- table.set_col_spacings(4)
- hbox.pack_start(table, True, True, 0)
- label = Gtk.Label.new_with_mnemonic("_Entry 1")
- table.attach_defaults(label, 0, 1, 0, 1)
- local_entry1 = Gtk.Entry()
- local_entry1.set_text(self.entry1.get_text())
- table.attach_defaults(local_entry1, 1, 2, 0, 1)
- label.set_mnemonic_widget(local_entry1)
-
- label = Gtk.Label.new_with_mnemonic("E_ntry 2")
- table.attach_defaults(label, 0, 1, 1, 2)
-
- local_entry2 = Gtk.Entry()
- local_entry2.set_text(self.entry2.get_text())
- table.attach_defaults(local_entry2, 1, 2, 1, 2)
- label.set_mnemonic_widget(local_entry2)
-
- hbox.show_all()
-
- response = dialog.run()
- if response == Gtk.ResponseType.OK:
- self.entry1.set_text(local_entry1.get_text())
- self.entry2.set_text(local_entry2.get_text())
-
- dialog.destroy()
-
- def _message_dialog_clicked(self, button):
- dialog = Gtk.MessageDialog(transient_for=self.window,
- modal=True,
- destroy_with_parent=True,
- message_type=Gtk.MessageType.INFO,
- buttons=Gtk.ButtonsType.OK,
- text="This message box has been popped up the following\nnumber of times:")
- dialog.format_secondary_text('%d' % self.dialog_counter)
- dialog.run()
-
- self.dialog_counter += 1
- dialog.destroy()
-
-
-def main(demoapp=None):
- DialogsApp()
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/drawingarea.py b/examples/demo/demos/drawingarea.py
deleted file mode 100644
index b04c41d..0000000
--- a/examples/demo/demos/drawingarea.py
+++ /dev/null
@@ -1,207 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "Drawing Area"
-description = """
-GtkDrawingArea is a blank area where you can draw custom displays
-of various kinds.
-
-This demo has two drawing areas. The checkerboard area shows
-how you can just draw something; all you have to do is write
-a signal handler for expose_event, as shown here.
-
-The "scribble" area is a bit more advanced, and shows how to handle
-events such as button presses and mouse motion. Click the mouse
-and drag in the scribble area to draw squiggles. Resize the window
-to clear the area.
-"""
-
-
-import cairo
-
-from gi.repository import Gtk, Gdk
-
-
-class DrawingAreaApp:
- def __init__(self):
- self.sureface = None
-
- window = Gtk.Window()
- window.set_title(title)
- window.connect('destroy', lambda x: Gtk.main_quit())
- window.set_border_width(8)
-
- vbox = Gtk.VBox(homogeneous=False, spacing=8)
- window.add(vbox)
-
- # create checkerboard area
- label = Gtk.Label()
- label.set_markup('Checkerboard pattern')
- vbox.pack_start(label, False, False, 0)
-
- frame = Gtk.Frame()
- frame.set_shadow_type(Gtk.ShadowType.IN)
- vbox.pack_start(frame, True, True, 0)
-
- da = Gtk.DrawingArea()
- da.set_size_request(100, 100)
- frame.add(da)
- da.connect('draw', self.checkerboard_draw_event)
-
- # create scribble area
- label = Gtk.Label()
- label.set_markup('Scribble area')
- vbox.pack_start(label, False, False, 0)
-
- frame = Gtk.Frame()
- frame.set_shadow_type(Gtk.ShadowType.IN)
- vbox.pack_start(frame, True, True, 0)
-
- da = Gtk.DrawingArea()
- da.set_size_request(100, 100)
- frame.add(da)
- da.connect('draw', self.scribble_draw_event)
- da.connect('configure-event', self.scribble_configure_event)
-
- # event signals
- da.connect('motion-notify-event', self.scribble_motion_notify_event)
- da.connect('button-press-event', self.scribble_button_press_event)
-
- # Ask to receive events the drawing area doesn't normally
- # subscribe to
- da.set_events(da.get_events() |
- Gdk.EventMask.LEAVE_NOTIFY_MASK |
- Gdk.EventMask.BUTTON_PRESS_MASK |
- Gdk.EventMask.POINTER_MOTION_MASK |
- Gdk.EventMask.POINTER_MOTION_HINT_MASK)
-
- window.show_all()
-
- def checkerboard_draw_event(self, da, cairo_ctx):
-
- # At the start of a draw handler, a clip region has been set on
- # the Cairo context, and the contents have been cleared to the
- # widget's background color. The docs for
- # gdk_window_begin_paint_region() give more details on how this
- # works.
- check_size = 10
- spacing = 2
-
- xcount = 0
- i = spacing
- width = da.get_allocated_width()
- height = da.get_allocated_height()
-
- while i < width:
- j = spacing
- ycount = xcount % 2 # start with even/odd depending on row
- while j < height:
- if ycount % 2:
- cairo_ctx.set_source_rgb(0.45777, 0, 0.45777)
- else:
- cairo_ctx.set_source_rgb(1, 1, 1)
- # If we're outside the clip this will do nothing.
- cairo_ctx.rectangle(i, j,
- check_size,
- check_size)
- cairo_ctx.fill()
-
- j += check_size + spacing
- ycount += 1
-
- i += check_size + spacing
- xcount += 1
-
- return True
-
- def scribble_draw_event(self, da, cairo_ctx):
-
- cairo_ctx.set_source_surface(self.surface, 0, 0)
- cairo_ctx.paint()
-
- return False
-
- def draw_brush(self, widget, x, y):
- update_rect = Gdk.Rectangle()
- update_rect.x = x - 3
- update_rect.y = y - 3
- update_rect.width = 6
- update_rect.height = 6
-
- # paint to the surface where we store our state
- cairo_ctx = cairo.Context(self.surface)
-
- Gdk.cairo_rectangle(cairo_ctx, update_rect)
- cairo_ctx.fill()
-
- widget.get_window().invalidate_rect(update_rect, False)
-
- def scribble_configure_event(self, da, event):
-
- allocation = da.get_allocation()
- self.surface = da.get_window().create_similar_surface(cairo.CONTENT_COLOR,
- allocation.width,
- allocation.height)
-
- cairo_ctx = cairo.Context(self.surface)
- cairo_ctx.set_source_rgb(1, 1, 1)
- cairo_ctx.paint()
-
- return True
-
- def scribble_motion_notify_event(self, da, event):
- if self.surface is None: # paranoia check, in case we haven't gotten a configure event
- return False
-
- # This call is very important; it requests the next motion event.
- # If you don't call gdk_window_get_pointer() you'll only get
- # a single motion event. The reason is that we specified
- # GDK_POINTER_MOTION_HINT_MASK to gtk_widget_set_events().
- # If we hadn't specified that, we could just use event->x, event->y
- # as the pointer location. But we'd also get deluged in events.
- # By requesting the next event as we handle the current one,
- # we avoid getting a huge number of events faster than we
- # can cope.
-
- (window, x, y, state) = event.window.get_pointer()
-
- if state & Gdk.ModifierType.BUTTON1_MASK:
- self.draw_brush(da, x, y)
-
- return True
-
- def scribble_button_press_event(self, da, event):
- if self.surface is None: # paranoia check, in case we haven't gotten a configure event
- return False
-
- if event.button == 1:
- self.draw_brush(da, event.x, event.y)
-
- return True
-
-
-def main(demoapp=None):
- DrawingAreaApp()
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/expander.py b/examples/demo/demos/expander.py
deleted file mode 100644
index 0ec149e..0000000
--- a/examples/demo/demos/expander.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "Expander"
-description = """
-GtkExpander allows to provide additional content that is initially hidden.
-This is also known as "disclosure triangle".
-"""
-
-from gi.repository import Gtk
-
-
-class ExpanderApp:
- def __init__(self):
- self.window = Gtk.Dialog(title="GtkExpander")
- self.window.add_buttons(Gtk.STOCK_CLOSE, Gtk.ResponseType.NONE)
- self.window.set_resizable(False)
- self.window.connect('response', lambda window, x: window.destroy())
- self.window.connect('destroy', Gtk.main_quit)
-
- content_area = self.window.get_content_area()
- vbox = Gtk.VBox(spacing=5)
- content_area.pack_start(vbox, True, True, 0)
- vbox.set_border_width(5)
-
- label = Gtk.Label(label='Expander demo. Click on the triangle for details.')
- vbox.pack_start(label, True, True, 0)
-
- expander = Gtk.Expander(label='Details')
- vbox.pack_start(expander, False, False, 0)
-
- label = Gtk.Label(label='Details can be shown or hidden')
- expander.add(label)
-
- self.window.show_all()
-
-
-def main(demoapp=None):
- ExpanderApp()
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/flowbox.py b/examples/demo/demos/flowbox.py
deleted file mode 100755
index 0485b7c..0000000
--- a/examples/demo/demos/flowbox.py
+++ /dev/null
@@ -1,752 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2014 Gian Mario Tagliaretti
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "FlowBox"
-description = """
-A FlowBox allows flexible and responsive grids which reflow as needed and
-support sorting and filtering. The children of a GtkFlowBox are regular widgets.
-"""
-
-from gi.repository import Gtk, Gdk
-
-
-class FlowBoxApp:
- def __init__(self):
- window = Gtk.Window()
- window.connect('destroy', lambda x: Gtk.main_quit())
- window.set_border_width(10)
- window.set_default_size(600, 400)
-
- header = Gtk.HeaderBar(title="Flow Box")
- header.set_subtitle("Sample FlowBox app")
- header.props.show_close_button = True
-
- window.set_titlebar(header)
-
- scrolled = Gtk.ScrolledWindow()
- scrolled.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
-
- flowbox = Gtk.FlowBox()
- flowbox.set_valign(Gtk.Align.START)
- flowbox.set_max_children_per_line(30)
- flowbox.set_selection_mode(Gtk.SelectionMode.NONE)
-
- self.create_flowbox(flowbox)
-
- scrolled.add(flowbox)
-
- window.add(scrolled)
- window.show_all()
-
- def color_swatch_new(self, str_color):
- rgba = Gdk.RGBA()
- rgba.parse(str_color)
-
- text_rgba = Gdk.RGBA() # default is white
- if max(rgba.red, rgba.green, rgba.blue) > 0.6:
- text_rgba.parse('black')
-
- label = Gtk.Label(label=str_color)
- label.override_background_color(0, rgba)
- label.override_color(0, text_rgba)
- return label
-
- def create_flowbox(self, flowbox):
- colors = [
- 'AliceBlue',
- 'AntiqueWhite',
- 'AntiqueWhite1',
- 'AntiqueWhite2',
- 'AntiqueWhite3',
- 'AntiqueWhite4',
- 'aqua',
- 'aquamarine',
- 'aquamarine1',
- 'aquamarine2',
- 'aquamarine3',
- 'aquamarine4',
- 'azure',
- 'azure1',
- 'azure2',
- 'azure3',
- 'azure4',
- 'beige',
- 'bisque',
- 'bisque1',
- 'bisque2',
- 'bisque3',
- 'bisque4',
- 'black',
- 'BlanchedAlmond',
- 'blue',
- 'blue1',
- 'blue2',
- 'blue3',
- 'blue4',
- 'BlueViolet',
- 'brown',
- 'brown1',
- 'brown2',
- 'brown3',
- 'brown4',
- 'burlywood',
- 'burlywood1',
- 'burlywood2',
- 'burlywood3',
- 'burlywood4',
- 'CadetBlue',
- 'CadetBlue1',
- 'CadetBlue2',
- 'CadetBlue3',
- 'CadetBlue4',
- 'chartreuse',
- 'chartreuse1',
- 'chartreuse2',
- 'chartreuse3',
- 'chartreuse4',
- 'chocolate',
- 'chocolate1',
- 'chocolate2',
- 'chocolate3',
- 'chocolate4',
- 'coral',
- 'coral1',
- 'coral2',
- 'coral3',
- 'coral4',
- 'CornflowerBlue',
- 'cornsilk',
- 'cornsilk1',
- 'cornsilk2',
- 'cornsilk3',
- 'cornsilk4',
- 'crimson',
- 'cyan',
- 'cyan1',
- 'cyan2',
- 'cyan3',
- 'cyan4',
- 'DarkBlue',
- 'DarkCyan',
- 'DarkGoldenrod',
- 'DarkGoldenrod1',
- 'DarkGoldenrod2',
- 'DarkGoldenrod3',
- 'DarkGoldenrod4',
- 'DarkGray',
- 'DarkGreen',
- 'DarkGrey',
- 'DarkKhaki',
- 'DarkMagenta',
- 'DarkOliveGreen',
- 'DarkOliveGreen1',
- 'DarkOliveGreen2',
- 'DarkOliveGreen3',
- 'DarkOliveGreen4',
- 'DarkOrange',
- 'DarkOrange1',
- 'DarkOrange2',
- 'DarkOrange3',
- 'DarkOrange4',
- 'DarkOrchid',
- 'DarkOrchid1',
- 'DarkOrchid2',
- 'DarkOrchid3',
- 'DarkOrchid4',
- 'DarkRed',
- 'DarkSalmon',
- 'DarkSeaGreen',
- 'DarkSeaGreen1',
- 'DarkSeaGreen2',
- 'DarkSeaGreen3',
- 'DarkSeaGreen4',
- 'DarkSlateBlue',
- 'DarkSlateGray',
- 'DarkSlateGray1',
- 'DarkSlateGray2',
- 'DarkSlateGray3',
- 'DarkSlateGray4',
- 'DarkSlateGrey',
- 'DarkTurquoise',
- 'DarkViolet',
- 'DeepPink',
- 'DeepPink1',
- 'DeepPink2',
- 'DeepPink3',
- 'DeepPink4',
- 'DeepSkyBlue',
- 'DeepSkyBlue1',
- 'DeepSkyBlue2',
- 'DeepSkyBlue3',
- 'DeepSkyBlue4',
- 'DimGray',
- 'DimGrey',
- 'DodgerBlue',
- 'DodgerBlue1',
- 'DodgerBlue2',
- 'DodgerBlue3',
- 'DodgerBlue4',
- 'firebrick',
- 'firebrick1',
- 'firebrick2',
- 'firebrick3',
- 'firebrick4',
- 'FloralWhite',
- 'ForestGreen',
- 'fuchsia',
- 'gainsboro',
- 'GhostWhite',
- 'gold',
- 'gold1',
- 'gold2',
- 'gold3',
- 'gold4',
- 'goldenrod',
- 'goldenrod1',
- 'goldenrod2',
- 'goldenrod3',
- 'goldenrod4',
- 'gray',
- 'gray0',
- 'gray1',
- 'gray2',
- 'gray3',
- 'gray4',
- 'gray5',
- 'gray6',
- 'gray7',
- 'gray8',
- 'gray9',
- 'gray10',
- 'gray11',
- 'gray12',
- 'gray13',
- 'gray14',
- 'gray15',
- 'gray16',
- 'gray17',
- 'gray18',
- 'gray19',
- 'gray20',
- 'gray21',
- 'gray22',
- 'gray23',
- 'gray24',
- 'gray25',
- 'gray26',
- 'gray27',
- 'gray28',
- 'gray29',
- 'gray30',
- 'gray31',
- 'gray32',
- 'gray33',
- 'gray34',
- 'gray35',
- 'gray36',
- 'gray37',
- 'gray38',
- 'gray39',
- 'gray40',
- 'gray41',
- 'gray42',
- 'gray43',
- 'gray44',
- 'gray45',
- 'gray46',
- 'gray47',
- 'gray48',
- 'gray49',
- 'gray50',
- 'gray51',
- 'gray52',
- 'gray53',
- 'gray54',
- 'gray55',
- 'gray56',
- 'gray57',
- 'gray58',
- 'gray59',
- 'gray60',
- 'gray61',
- 'gray62',
- 'gray63',
- 'gray64',
- 'gray65',
- 'gray66',
- 'gray67',
- 'gray68',
- 'gray69',
- 'gray70',
- 'gray71',
- 'gray72',
- 'gray73',
- 'gray74',
- 'gray75',
- 'gray76',
- 'gray77',
- 'gray78',
- 'gray79',
- 'gray80',
- 'gray81',
- 'gray82',
- 'gray83',
- 'gray84',
- 'gray85',
- 'gray86',
- 'gray87',
- 'gray88',
- 'gray89',
- 'gray90',
- 'gray91',
- 'gray92',
- 'gray93',
- 'gray94',
- 'gray95',
- 'gray96',
- 'gray97',
- 'gray98',
- 'gray99',
- 'gray100',
- 'green',
- 'green1',
- 'green2',
- 'green3',
- 'green4',
- 'GreenYellow',
- 'grey',
- 'grey0',
- 'grey1',
- 'grey2',
- 'grey3',
- 'grey4',
- 'grey5',
- 'grey6',
- 'grey7',
- 'grey8',
- 'grey9',
- 'grey10',
- 'grey11',
- 'grey12',
- 'grey13',
- 'grey14',
- 'grey15',
- 'grey16',
- 'grey17',
- 'grey18',
- 'grey19',
- 'grey20',
- 'grey21',
- 'grey22',
- 'grey23',
- 'grey24',
- 'grey25',
- 'grey26',
- 'grey27',
- 'grey28',
- 'grey29',
- 'grey30',
- 'grey31',
- 'grey32',
- 'grey33',
- 'grey34',
- 'grey35',
- 'grey36',
- 'grey37',
- 'grey38',
- 'grey39',
- 'grey40',
- 'grey41',
- 'grey42',
- 'grey43',
- 'grey44',
- 'grey45',
- 'grey46',
- 'grey47',
- 'grey48',
- 'grey49',
- 'grey50',
- 'grey51',
- 'grey52',
- 'grey53',
- 'grey54',
- 'grey55',
- 'grey56',
- 'grey57',
- 'grey58',
- 'grey59',
- 'grey60',
- 'grey61',
- 'grey62',
- 'grey63',
- 'grey64',
- 'grey65',
- 'grey66',
- 'grey67',
- 'grey68',
- 'grey69',
- 'grey70',
- 'grey71',
- 'grey72',
- 'grey73',
- 'grey74',
- 'grey75',
- 'grey76',
- 'grey77',
- 'grey78',
- 'grey79',
- 'grey80',
- 'grey81',
- 'grey82',
- 'grey83',
- 'grey84',
- 'grey85',
- 'grey86',
- 'grey87',
- 'grey88',
- 'grey89',
- 'grey90',
- 'grey91',
- 'grey92',
- 'grey93',
- 'grey94',
- 'grey95',
- 'grey96',
- 'grey97',
- 'grey98',
- 'grey99',
- 'grey100',
- 'honeydew',
- 'honeydew1',
- 'honeydew2',
- 'honeydew3',
- 'honeydew4',
- 'HotPink',
- 'HotPink1',
- 'HotPink2',
- 'HotPink3',
- 'HotPink4',
- 'IndianRed',
- 'IndianRed1',
- 'IndianRed2',
- 'IndianRed3',
- 'IndianRed4',
- 'indigo',
- 'ivory',
- 'ivory1',
- 'ivory2',
- 'ivory3',
- 'ivory4',
- 'khaki',
- 'khaki1',
- 'khaki2',
- 'khaki3',
- 'khaki4',
- 'lavender',
- 'LavenderBlush',
- 'LavenderBlush1',
- 'LavenderBlush2',
- 'LavenderBlush3',
- 'LavenderBlush4',
- 'LawnGreen',
- 'LemonChiffon',
- 'LemonChiffon1',
- 'LemonChiffon2',
- 'LemonChiffon3',
- 'LemonChiffon4',
- 'LightBlue',
- 'LightBlue1',
- 'LightBlue2',
- 'LightBlue3',
- 'LightBlue4',
- 'LightCoral',
- 'LightCyan',
- 'LightCyan1',
- 'LightCyan2',
- 'LightCyan3',
- 'LightCyan4',
- 'LightGoldenrod',
- 'LightGoldenrod1',
- 'LightGoldenrod2',
- 'LightGoldenrod3',
- 'LightGoldenrod4',
- 'LightGoldenrodYellow',
- 'LightGray',
- 'LightGreen',
- 'LightGrey',
- 'LightPink',
- 'LightPink1',
- 'LightPink2',
- 'LightPink3',
- 'LightPink4',
- 'LightSalmon',
- 'LightSalmon1',
- 'LightSalmon2',
- 'LightSalmon3',
- 'LightSalmon4',
- 'LightSeaGreen',
- 'LightSkyBlue',
- 'LightSkyBlue1',
- 'LightSkyBlue2',
- 'LightSkyBlue3',
- 'LightSkyBlue4',
- 'LightSlateBlue',
- 'LightSlateGray',
- 'LightSlateGrey',
- 'LightSteelBlue',
- 'LightSteelBlue1',
- 'LightSteelBlue2',
- 'LightSteelBlue3',
- 'LightSteelBlue4',
- 'LightYellow',
- 'LightYellow1',
- 'LightYellow2',
- 'LightYellow3',
- 'LightYellow4',
- 'lime',
- 'LimeGreen',
- 'linen',
- 'magenta',
- 'magenta1',
- 'magenta2',
- 'magenta3',
- 'magenta4',
- 'maroon',
- 'maroon1',
- 'maroon2',
- 'maroon3',
- 'maroon4',
- 'MediumAquamarine',
- 'MediumBlue',
- 'MediumOrchid',
- 'MediumOrchid1',
- 'MediumOrchid2',
- 'MediumOrchid3',
- 'MediumOrchid4',
- 'MediumPurple',
- 'MediumPurple1',
- 'MediumPurple2',
- 'MediumPurple3',
- 'MediumPurple4',
- 'MediumSeaGreen',
- 'MediumSlateBlue',
- 'MediumSpringGreen',
- 'MediumTurquoise',
- 'MediumVioletRed',
- 'MidnightBlue',
- 'MintCream',
- 'MistyRose',
- 'MistyRose1',
- 'MistyRose2',
- 'MistyRose3',
- 'MistyRose4',
- 'moccasin',
- 'NavajoWhite',
- 'NavajoWhite1',
- 'NavajoWhite2',
- 'NavajoWhite3',
- 'NavajoWhite4',
- 'navy',
- 'NavyBlue',
- 'OldLace',
- 'olive',
- 'OliveDrab',
- 'OliveDrab1',
- 'OliveDrab2',
- 'OliveDrab3',
- 'OliveDrab4',
- 'orange',
- 'orange1',
- 'orange2',
- 'orange3',
- 'orange4',
- 'OrangeRed',
- 'OrangeRed1',
- 'OrangeRed2',
- 'OrangeRed3',
- 'OrangeRed4',
- 'orchid',
- 'orchid1',
- 'orchid2',
- 'orchid3',
- 'orchid4',
- 'PaleGoldenrod',
- 'PaleGreen',
- 'PaleGreen1',
- 'PaleGreen2',
- 'PaleGreen3',
- 'PaleGreen4',
- 'PaleTurquoise',
- 'PaleTurquoise1',
- 'PaleTurquoise2',
- 'PaleTurquoise3',
- 'PaleTurquoise4',
- 'PaleVioletRed',
- 'PaleVioletRed1',
- 'PaleVioletRed2',
- 'PaleVioletRed3',
- 'PaleVioletRed4',
- 'PapayaWhip',
- 'PeachPuff',
- 'PeachPuff1',
- 'PeachPuff2',
- 'PeachPuff3',
- 'PeachPuff4',
- 'peru',
- 'pink',
- 'pink1',
- 'pink2',
- 'pink3',
- 'pink4',
- 'plum',
- 'plum1',
- 'plum2',
- 'plum3',
- 'plum4',
- 'PowderBlue',
- 'purple',
- 'purple1',
- 'purple2',
- 'purple3',
- 'purple4',
- 'red',
- 'red1',
- 'red2',
- 'red3',
- 'red4',
- 'RosyBrown',
- 'RosyBrown1',
- 'RosyBrown2',
- 'RosyBrown3',
- 'RosyBrown4',
- 'RoyalBlue',
- 'RoyalBlue1',
- 'RoyalBlue2',
- 'RoyalBlue3',
- 'RoyalBlue4',
- 'SaddleBrown',
- 'salmon',
- 'salmon1',
- 'salmon2',
- 'salmon3',
- 'salmon4',
- 'SandyBrown',
- 'SeaGreen',
- 'SeaGreen1',
- 'SeaGreen2',
- 'SeaGreen3',
- 'SeaGreen4',
- 'seashell',
- 'seashell1',
- 'seashell2',
- 'seashell3',
- 'seashell4',
- 'sienna',
- 'sienna1',
- 'sienna2',
- 'sienna3',
- 'sienna4',
- 'silver',
- 'SkyBlue',
- 'SkyBlue1',
- 'SkyBlue2',
- 'SkyBlue3',
- 'SkyBlue4',
- 'SlateBlue',
- 'SlateBlue1',
- 'SlateBlue2',
- 'SlateBlue3',
- 'SlateBlue4',
- 'SlateGray',
- 'SlateGray1',
- 'SlateGray2',
- 'SlateGray3',
- 'SlateGray4',
- 'SlateGrey',
- 'snow',
- 'snow1',
- 'snow2',
- 'snow3',
- 'snow4',
- 'SpringGreen',
- 'SpringGreen1',
- 'SpringGreen2',
- 'SpringGreen3',
- 'SpringGreen4',
- 'SteelBlue',
- 'SteelBlue1',
- 'SteelBlue2',
- 'SteelBlue3',
- 'SteelBlue4',
- 'tan',
- 'tan1',
- 'tan2',
- 'tan3',
- 'tan4',
- 'teal',
- 'thistle',
- 'thistle1',
- 'thistle2',
- 'thistle3',
- 'thistle4',
- 'tomato',
- 'tomato1',
- 'tomato2',
- 'tomato3',
- 'tomato4',
- 'turquoise',
- 'turquoise1',
- 'turquoise2',
- 'turquoise3',
- 'turquoise4',
- 'violet',
- 'VioletRed',
- 'VioletRed1',
- 'VioletRed2',
- 'VioletRed3',
- 'VioletRed4',
- 'wheat',
- 'wheat1',
- 'wheat2',
- 'wheat3',
- 'wheat4',
- 'white',
- 'WhiteSmoke',
- 'yellow',
- 'yellow1',
- 'yellow2',
- 'yellow3',
- 'yellow4',
- 'YellowGreen',
- ]
-
- for color in colors:
- button = self.color_swatch_new(color)
- flowbox.add(button)
-
-
-def main(demoapp=None):
- FlowBoxApp()
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/images.py b/examples/demo/demos/images.py
deleted file mode 100644
index 80c99af..0000000
--- a/examples/demo/demos/images.py
+++ /dev/null
@@ -1,305 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "Images"
-description = """GtkImage is used to display an image; the image can be in a
-number of formats. Typically, you load an image into a GdkPixbuf, then display
-the pixbuf. This demo code shows some of the more obscure cases, in the simple
-case a call to gtk_image_new_from_file() is all you need.
-"""
-
-import os
-from os import path
-
-from gi.repository import Gtk, Gdk, GdkPixbuf, GLib, Gio, GObject
-
-
-class ImagesApp:
- def __init__(self):
- self.pixbuf_loader = None
- self.image_stream = None
-
- self.window = Gtk.Window(title="Images")
- self.window.connect('destroy', self.cleanup_cb)
- self.window.set_border_width(8)
-
- vbox = Gtk.VBox(spacing=8)
- vbox.set_border_width(8)
- self.window.add(vbox)
-
- label = Gtk.Label()
- label.set_markup('Image loaded from file')
- vbox.pack_start(label, False, False, 0)
-
- frame = Gtk.Frame()
- frame.set_shadow_type(Gtk.ShadowType.IN)
-
- # The alignment keeps the frame from growing when users resize
- # the window
- align = Gtk.Alignment(xalign=0.5,
- yalign=0.5,
- xscale=0,
- yscale=0)
- align.add(frame)
- vbox.pack_start(align, False, False, 0)
-
- self.base_path = os.path.abspath(os.path.dirname(__file__))
- self.base_path = os.path.join(self.base_path, 'data')
- filename = os.path.join(self.base_path, 'gtk-logo-rgb.gif')
- pixbuf = GdkPixbuf.Pixbuf.new_from_file(filename)
- transparent = pixbuf.add_alpha(True, 0xff, 0xff, 0xff)
- image = Gtk.Image.new_from_pixbuf(transparent)
- frame.add(image)
-
- # Animation
-
- label = Gtk.Label()
- label.set_markup('Animation loaded from file')
- vbox.pack_start(label, False, False, 0)
-
- frame = Gtk.Frame()
- frame.set_shadow_type(Gtk.ShadowType.IN)
-
- # The alignment keeps the frame from growing when users resize
- # the window
- align = Gtk.Alignment(xalign=0.5,
- yalign=0.5,
- xscale=0,
- yscale=0)
- align.add(frame)
- vbox.pack_start(align, False, False, 0)
-
- img_path = path.join(self.base_path, 'floppybuddy.gif')
- image = Gtk.Image.new_from_file(img_path)
- frame.add(image)
-
- # Symbolic icon
-
- label = Gtk.Label()
- label.set_markup('Symbolic themed icon')
- vbox.pack_start(label, False, False, 0)
-
- frame = Gtk.Frame()
- frame.set_shadow_type(Gtk.ShadowType.IN)
-
- # The alignment keeps the frame from growing when users resize
- # the window
- align = Gtk.Alignment(xalign=0.5,
- yalign=0.5,
- xscale=0,
- yscale=0)
- align.add(frame)
- vbox.pack_start(align, False, False, 0)
-
- gicon = Gio.ThemedIcon.new_with_default_fallbacks('battery-caution-charging-symbolic')
- image = Gtk.Image.new_from_gicon(gicon, Gtk.IconSize.DIALOG)
- frame.add(image)
-
- # progressive
-
- label = Gtk.Label()
- label.set_markup('Progressive image loading')
- vbox.pack_start(label, False, False, 0)
-
- frame = Gtk.Frame()
- frame.set_shadow_type(Gtk.ShadowType.IN)
-
- # The alignment keeps the frame from growing when users resize
- # the window
- align = Gtk.Alignment(xalign=0.5,
- yalign=0.5,
- xscale=0,
- yscale=0)
- align.add(frame)
- vbox.pack_start(align, False, False, 0)
-
- image = Gtk.Image.new_from_pixbuf(None)
- frame.add(image)
-
- self.start_progressive_loading(image)
-
- # Sensistivity control
- button = Gtk.ToggleButton.new_with_mnemonic('_Insensitive')
- button.connect('toggled', self.toggle_sensitivity_cb, vbox)
- vbox.pack_start(button, False, False, 0)
-
- self.window.show_all()
-
- def toggle_sensitivity_cb(self, button, container):
- widget_list = container.get_children()
- for w in widget_list:
- if w != button:
- w.set_sensitive(not button.get_active())
-
- return True
-
- def progressive_timeout(self, image):
- # This shows off fully-paranoid error handling, so looks scary.
- # You could factor out the error handling code into a nice separate
- # function to make things nicer.
-
- if self.image_stream:
- try:
- buf = self.image_stream.read(256)
- except IOError as e:
- dialog = Gtk.MessageDialog(self.window,
- Gtk.DialogFlags.DESTROY_WITH_PARENT,
- Gtk.MessageType.ERROR,
- Gtk.ButtonsType.CLOSE,
- "Failure reading image file 'alphatest.png': %s" % (str(e), ))
-
- self.image_stream.close()
- self.image_stream = None
- self.load_timeout = 0
-
- dialog.show()
- dialog.connect('response', lambda x, y: dialog.destroy())
-
- return False # uninstall the timeout
-
- try:
- self.pixbuf_loader.write(buf)
-
- except GObject.GError as e:
- dialog = Gtk.MessageDialog(self.window,
- Gtk.DialogFlags.DESTROY_WITH_PARENT,
- Gtk.MessageType.ERROR,
- Gtk.ButtonsType.CLOSE,
- e.message)
-
- self.image_stream.close()
- self.image_stream = None
- self.load_timeout = 0
-
- dialog.show()
- dialog.connect('response', lambda x, y: dialog.destroy())
-
- return False # uninstall the timeout
-
- if len(buf) < 256: # eof
- self.image_stream.close()
- self.image_stream = None
-
- # Errors can happen on close, e.g. if the image
- # file was truncated we'll know on close that
- # it was incomplete.
- try:
- self.pixbuf_loader.close()
- except GObject.GError as e:
- dialog = Gtk.MessageDialog(self.window,
- Gtk.DialogFlags.DESTROY_WITH_PARENT,
- Gtk.MessageType.ERROR,
- Gtk.ButtonsType.CLOSE,
- 'Failed to load image: %s' % e.message)
-
- self.load_timeout = 0
-
- dialog.show()
- dialog.connect('response', lambda x, y: dialog.destroy())
-
- return False # uninstall the timeout
- else:
- img_path = path.join(self.base_path, 'alphatest.png')
- try:
- self.image_stream = open(img_path, 'rb')
- except IOError as e:
- dialog = Gtk.MessageDialog(self.window,
- Gtk.DialogFlags.DESTROY_WITH_PARENT,
- Gtk.MessageType.ERROR,
- Gtk.ButtonsType.CLOSE,
- str(e))
- self.load_timeout = 0
- dialog.show()
- dialog.connect('response', lambda x, y: dialog.destroy())
-
- return False # uninstall the timeout
-
- if self.pixbuf_loader:
- try:
- self.pixbuf_loader.close()
- except GObject.GError:
- pass
- self.pixbuf_loader = None
-
- self.pixbuf_loader = GdkPixbuf.PixbufLoader()
-
- self.pixbuf_loader.connect('area-prepared',
- self.progressive_prepared_callback,
- image)
-
- self.pixbuf_loader.connect('area-updated',
- self.progressive_updated_callback,
- image)
- # leave timeout installed
- return True
-
- def progressive_prepared_callback(self, loader, image):
- pixbuf = loader.get_pixbuf()
- # Avoid displaying random memory contents, since the pixbuf
- # isn't filled in yet.
- pixbuf.fill(0xaaaaaaff)
- image.set_from_pixbuf(pixbuf)
-
- def progressive_updated_callback(self, loader, x, y, width, height, image):
- # We know the pixbuf inside the GtkImage has changed, but the image
- # itself doesn't know this; so queue a redraw. If we wanted to be
- # really efficient, we could use a drawing area or something
- # instead of a GtkImage, so we could control the exact position of
- # the pixbuf on the display, then we could queue a draw for only
- # the updated area of the image.
- image.queue_draw()
-
- def start_progressive_loading(self, image):
- # This is obviously totally contrived (we slow down loading
- # on purpose to show how incremental loading works).
- # The real purpose of incremental loading is the case where
- # you are reading data from a slow source such as the network.
- # The timeout simply simulates a slow data source by inserting
- # pauses in the reading process.
-
- self.load_timeout = Gdk.threads_add_timeout(150,
- GLib.PRIORITY_DEFAULT_IDLE,
- self.progressive_timeout,
- image)
-
- def cleanup_cb(self, widget):
- if self.load_timeout:
- GLib.source_remove(self.load_timeout)
-
- if self.pixbuf_loader:
- try:
- self.pixbuf_loader.close()
- except GObject.GError:
- pass
-
- if self.image_stream:
- self.image_stream.close()
-
- Gtk.main_quit()
-
-
-def main(demoapp=None):
- ImagesApp()
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/infobars.py b/examples/demo/demos/infobars.py
deleted file mode 100644
index b8a1dc7..0000000
--- a/examples/demo/demos/infobars.py
+++ /dev/null
@@ -1,103 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "Info Bars"
-description = """
-Info bar widgets are used to report important messages to the user.
-"""
-
-from gi.repository import Gtk
-
-
-class InfobarApp:
- def __init__(self):
- self.window = Gtk.Window()
- self.window.set_title('Info Bars')
- self.window.set_border_width(8)
- self.window.connect('destroy', Gtk.main_quit)
-
- vbox = Gtk.VBox(spacing=0)
- self.window.add(vbox)
-
- bar = Gtk.InfoBar()
- vbox.pack_start(bar, False, False, 0)
- bar.set_message_type(Gtk.MessageType.INFO)
- label = Gtk.Label(label='This is an info bar with message type Gtk.MessageType.INFO')
- bar.get_content_area().pack_start(label, False, False, 0)
-
- bar = Gtk.InfoBar()
- vbox.pack_start(bar, False, False, 0)
- bar.set_message_type(Gtk.MessageType.WARNING)
- label = Gtk.Label(label='This is an info bar with message type Gtk.MessageType.WARNING')
- bar.get_content_area().pack_start(label, False, False, 0)
-
- bar = Gtk.InfoBar()
- bar.add_button(Gtk.STOCK_OK, Gtk.ResponseType.OK)
- bar.connect('response', self.on_bar_response)
- vbox.pack_start(bar, False, False, 0)
- bar.set_message_type(Gtk.MessageType.QUESTION)
- label = Gtk.Label(label='This is an info bar with message type Gtk.MessageType.QUESTION')
- bar.get_content_area().pack_start(label, False, False, 0)
-
- bar = Gtk.InfoBar()
- vbox.pack_start(bar, False, False, 0)
- bar.set_message_type(Gtk.MessageType.ERROR)
- label = Gtk.Label(label='This is an info bar with message type Gtk.MessageType.ERROR')
- bar.get_content_area().pack_start(label, False, False, 0)
-
- bar = Gtk.InfoBar()
- vbox.pack_start(bar, False, False, 0)
- bar.set_message_type(Gtk.MessageType.OTHER)
- label = Gtk.Label(label='This is an info bar with message type Gtk.MessageType.OTHER')
- bar.get_content_area().pack_start(label, False, False, 0)
-
- frame = Gtk.Frame(label="Info bars")
- vbox.pack_start(frame, False, False, 8)
-
- vbox2 = Gtk.VBox(spacing=8)
- vbox2.set_border_width(8)
- frame.add(vbox2)
-
- # Standard message dialog
- label = Gtk.Label(label='An example of different info bars')
- vbox2.pack_start(label, False, False, 0)
-
- self.window.show_all()
-
- def on_bar_response(self, info_bar, response_id):
- dialog = Gtk.MessageDialog(transient_for=self.window,
- modal=True,
- destroy_with_parent=True,
- message_type=Gtk.MessageType.INFO,
- buttons=Gtk.ButtonsType.OK,
- text='You clicked on an info bar')
- dialog.format_secondary_text('Your response has id %d' % response_id)
- dialog.run()
- dialog.destroy()
-
-
-def main(demoapp=None):
- InfobarApp()
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/links.py b/examples/demo/demos/links.py
deleted file mode 100644
index c6d331d..0000000
--- a/examples/demo/demos/links.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "Links"
-description = """
-GtkLabel can show hyperlinks. The default action is to call gtk_show_uri() on
-their URI, but it is possible to override this with a custom handler.
-"""
-
-from gi.repository import Gtk
-
-
-class LinksApp:
- def __init__(self):
- self.window = Gtk.Window()
- self.window.set_title('Links')
- self.window.set_border_width(12)
- self.window.connect('destroy', Gtk.main_quit)
-
- label = Gtk.Label(label="""Some text may be marked up
-as hyperlinks, which can be clicked
-or activated via keynav""")
-
- label.set_use_markup(True)
- label.connect("activate-link", self.activate_link)
- self.window.add(label)
- label.show()
-
- self.window.show()
-
- def activate_link(self, label, uri):
- if uri == 'keynav':
- parent = label.get_toplevel()
- markup = """The term keynav is a shorthand for
-keyboard navigation and refers to the process of using
-a program (exclusively) via keyboard input."""
- dialog = Gtk.MessageDialog(transient_for=parent,
- destroy_with_parent=True,
- message_type=Gtk.MessageType.INFO,
- buttons=Gtk.ButtonsType.OK,
- text=markup,
- use_markup=True)
- dialog.present()
- dialog.connect('response', self.response_cb)
-
- return True
-
- def response_cb(self, dialog, response_id):
- dialog.destroy()
-
-
-def main(demoapp=None):
- LinksApp()
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/menus.py b/examples/demo/demos/menus.py
deleted file mode 100644
index 7cf2e57..0000000
--- a/examples/demo/demos/menus.py
+++ /dev/null
@@ -1,134 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "Menus"
-description = """There are several widgets involved in displaying menus. The
-GtkMenuBar widget is a menu bar, which normally appears horizontally at the top
-of an application, but can also be layed out vertically. The GtkMenu widget is
-the actual menu that pops up. Both GtkMenuBar and GtkMenu are subclasses of
-GtkMenuShell; a GtkMenuShell contains menu items (GtkMenuItem). Each menu item
-contains text and/or images and can be selected by the user. There are several
-kinds of menu item, including plain GtkMenuItem, GtkCheckMenuItem which can be
-checked/unchecked, GtkRadioMenuItem which is a check menu item that's in a
-mutually exclusive group, GtkSeparatorMenuItem which is a separator bar,
-GtkTearoffMenuItem which allows a GtkMenu to be torn off, and GtkImageMenuItem
-which can place a GtkImage or other widget next to the menu text. A GtkMenuItem
-can have a submenu, which is simply a GtkMenu to pop up when the menu item is
-selected. Typically, all menu items in a menu bar have submenus. GtkUIManager
-provides a higher-level interface for creating menu bars and menus; while you
-can construct menus manually, most people don't do that. There's a separate demo
-for GtkUIManager.
-"""
-
-from gi.repository import Gtk
-
-
-class MenusApp:
- def __init__(self):
- self.window = Gtk.Window()
- self.window.set_title('Menus')
- self.window.connect('destroy', Gtk.main_quit)
-
- accel_group = Gtk.AccelGroup()
- self.window.add_accel_group(accel_group)
- self.window.set_border_width(0)
-
- box = Gtk.HBox()
- self.window.add(box)
-
- box1 = Gtk.VBox()
- box.add(box1)
-
- menubar = Gtk.MenuBar()
- box1.pack_start(menubar, False, True, 0)
-
- menuitem = Gtk.MenuItem(label='test\nline2')
- menuitem.set_submenu(self.create_menu(3, True))
- menubar.append(menuitem)
-
- menuitem = Gtk.MenuItem(label='foo')
- menuitem.set_submenu(self.create_menu(4, True))
- menuitem.set_right_justified(True)
- menubar.append(menuitem)
-
- box2 = Gtk.VBox(spacing=10)
- box2.set_border_width(10)
- box1.pack_start(box2, False, True, 0)
-
- button = Gtk.Button(label='Flip')
- button.connect('clicked', self.change_orientation, menubar)
- box2.pack_start(button, True, True, 0)
-
- button = Gtk.Button(label='Close')
- button.connect('clicked', lambda x: self.window.destroy())
- box2.pack_start(button, True, True, 0)
- button.set_can_default(True)
-
- self.window.show_all()
-
- def create_menu(self, depth, tearoff):
- if depth < 1:
- return None
-
- menu = Gtk.Menu()
-
- if tearoff:
- menuitem = Gtk.TearoffMenuItem()
- menu.append(menuitem)
-
- i = 0
- j = 1
- while i < 5:
- label = 'item %2d - %d' % (depth, j)
- # we should be adding this to a group but the group API
- # isn't bindable - we need something more like the
- # Gtk.RadioAction API
- menuitem = Gtk.RadioMenuItem(label=label)
- menu.append(menuitem)
-
- if i == 3:
- menuitem.set_sensitive(False)
-
- menuitem.set_submenu(self.create_menu(depth - 1, True))
-
- i += 1
- j += 1
-
- return menu
-
- def change_orientation(self, button, menubar):
- parent = menubar.get_parent()
- orientation = parent.get_orientation()
- parent.set_orientation(1 - orientation)
-
- if orientation == Gtk.Orientation.VERTICAL:
- menubar.props.pack_direction = Gtk.PackDirection.TTB
- else:
- menubar.props.pack_direction = Gtk.PackDirection.LTR
-
-
-def main(demoapp=None):
- MenusApp()
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/pickers.py b/examples/demo/demos/pickers.py
deleted file mode 100644
index d8a9c75..0000000
--- a/examples/demo/demos/pickers.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "Pickers"
-description = """These widgets are mainly intended for use in preference
-dialogs. They allow to select colors, fonts, files and directories.
-"""
-
-from gi.repository import Gtk
-
-
-class PickersApp:
- def __init__(self):
- self.window = Gtk.Window(title='Pickers')
- self.window.connect('destroy', Gtk.main_quit)
- self.window.set_border_width(10)
-
- table = Gtk.Table(n_rows=4, n_columns=2, homogeneous=False)
- table.set_col_spacing(0, 10)
- table.set_row_spacings(3)
- self.window.add(table)
- table.set_border_width(10)
-
- label = Gtk.Label(label='Color:')
- label.set_alignment(0.0, 0.5)
- picker = Gtk.ColorButton()
- table.attach_defaults(label, 0, 1, 0, 1)
- table.attach_defaults(picker, 1, 2, 0, 1)
-
- label = Gtk.Label(label='Font:')
- label.set_alignment(0.0, 0.5)
- picker = Gtk.FontButton()
- table.attach_defaults(label, 0, 1, 1, 2)
- table.attach_defaults(picker, 1, 2, 1, 2)
-
- label = Gtk.Label(label='File:')
- label.set_alignment(0.0, 0.5)
- picker = Gtk.FileChooserButton.new('Pick a File',
- Gtk.FileChooserAction.OPEN)
- table.attach_defaults(label, 0, 1, 2, 3)
- table.attach_defaults(picker, 1, 2, 2, 3)
-
- label = Gtk.Label(label='Folder:')
- label.set_alignment(0.0, 0.5)
- picker = Gtk.FileChooserButton.new('Pick a Folder',
- Gtk.FileChooserAction.SELECT_FOLDER)
- table.attach_defaults(label, 0, 1, 3, 4)
- table.attach_defaults(picker, 1, 2, 3, 4)
-
- self.window.show_all()
-
-
-def main(demoapp=None):
- PickersApp()
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/pixbuf.py b/examples/demo/demos/pixbuf.py
deleted file mode 100644
index c213584..0000000
--- a/examples/demo/demos/pixbuf.py
+++ /dev/null
@@ -1,184 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "Pixbufs"
-description = """A GdkPixbuf represents an image, normally in RGB or RGBA
-format. Pixbufs are normally used to load files from disk and perform image
-scaling. It also shows off how to use GtkDrawingArea to do a simple animation.
-Look at the Image demo for additional pixbuf usage examples.
-"""
-
-from gi.repository import Gtk, Gdk, GdkPixbuf, GLib
-import os
-import math
-
-
-class PixbufApp:
- FRAME_DELAY = 50
- BACKGROUND_NAME = "background.jpg"
- CYCLE_LEN = 60
-
- def __init__(self):
- self.background_width = 0
- self.background_height = 0
- self.background_pixbuf = None
- self.frame = None
- self.frame_num = 0
- self.pixbufs = []
- self.image_names = [
- "apple-red.png",
- "gnome-applets.png",
- "gnome-calendar.png",
- "gnome-foot.png",
- "gnome-gmush.png",
- "gnome-gimp.png",
- "gnome-gsame.png",
- "gnu-keys.png"
- ]
-
- self.window = Gtk.Window(title="Pixbufs")
- self.window.set_resizable(False)
- self.window.connect('destroy', self.cleanup_cb)
-
- try:
- self.load_pixbufs()
- except GLib.Error as e:
- dialog = Gtk.MessageDialog(None,
- 0,
- Gtk.MessageType.ERROR,
- Gtk.ButtonsType.CLOSE,
- e.message)
-
- dialog.run()
- dialog.destroy()
- Gtk.main_quit()
-
- self.window.set_size_request(self.background_width,
- self.background_height)
- self.frame = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB,
- False,
- 8,
- self.background_width,
- self.background_height)
- self.da = Gtk.DrawingArea()
- self.da.connect('draw', self.draw_cb)
- self.window.add(self.da)
- self.timeout_id = GLib.timeout_add(self.FRAME_DELAY, self.timeout_cb)
- self.window.show_all()
-
- def load_pixbufs(self):
- base_path = os.path.abspath(os.path.dirname(__file__))
- base_path = os.path.join(base_path, 'data')
- img_path = os.path.join(base_path, self.BACKGROUND_NAME)
- self.background_pixbuf = GdkPixbuf.Pixbuf.new_from_file(img_path)
- self.background_height = self.background_pixbuf.get_height()
- self.background_width = self.background_pixbuf.get_width()
-
- for img_name in self.image_names:
- img_path = os.path.join(base_path, img_name)
- self.pixbufs.append(GdkPixbuf.Pixbuf.new_from_file(img_path))
-
- def draw_cb(self, da, cairo_ctx):
- Gdk.cairo_set_source_pixbuf(cairo_ctx, self.frame, 0, 0)
- cairo_ctx.paint()
-
- return True
-
- def timeout_cb(self):
- self.background_pixbuf.copy_area(0, 0,
- self.background_width,
- self.background_height,
- self.frame,
- 0, 0)
-
- f = float(self.frame_num % self.CYCLE_LEN) / self.CYCLE_LEN
-
- xmid = self.background_width / 2.0
- ymid = self.background_height / 2.0
- radius = min(xmid, ymid) / 2.0
-
- r1 = Gdk.Rectangle()
- r2 = Gdk.Rectangle()
-
- i = 0
- for pb in self.pixbufs:
- i += 1
- ang = 2.0 * math.pi * i / len(self.pixbufs) - f * 2.0 * math.pi
-
- iw = pb.get_width()
- ih = pb.get_height()
-
- r = radius + (radius / 3.0) * math.sin(f * 2.0 * math.pi)
-
- xpos = math.floor(xmid + r * math.cos(ang) - iw / 2.0 + 0.5)
- ypos = math.floor(ymid + r * math.sin(ang) - ih / 2.0 + 0.5)
-
- if i & 1:
- k = math.sin(f * 2.0 * math.pi)
- else:
- k = math.cos(f * 2.0 * math.pi)
-
- k = 2.0 * k * k
- k = max(0.25, k)
-
- r1.x = xpos
- r1.y = ypos
- r1.width = iw * k
- r1.height = ih * k
-
- r2.x = 0
- r2.y = 0
- r2.width = self.background_width
- r2.height = self.background_height
-
- success, dest = Gdk.rectangle_intersect(r1, r2)
- if success:
- alpha = 0
- if i & 1:
- alpha = max(127, math.fabs(255 * math.sin(f * 2.0 * math.pi)))
- else:
- alpha = max(127, math.fabs(255 * math.cos(f * 2.0 * math.pi)))
-
- pb.composite(self.frame,
- dest.x, dest.y,
- dest.width, dest.height,
- xpos, ypos,
- k, k,
- GdkPixbuf.InterpType.NEAREST,
- alpha)
-
- self.da.queue_draw()
-
- self.frame_num += 1
- return True
-
- def cleanup_cb(self, widget):
- GLib.source_remove(self.timeout_id)
- Gtk.main_quit()
-
-
-def main(demoapp=None):
- PixbufApp()
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/printing.py b/examples/demo/demos/printing.py
deleted file mode 100644
index a87bd6f..0000000
--- a/examples/demo/demos/printing.py
+++ /dev/null
@@ -1,180 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "Printing"
-description = """
-GtkPrintOperation offers a simple API to support printing in a cross-platform way.
-"""
-
-from gi.repository import Gtk, GLib, Pango, PangoCairo
-import math
-import os
-
-
-class PrintingApp:
- HEADER_HEIGHT = 10 * 72 / 25.4
- HEADER_GAP = 3 * 72 / 25.4
-
- def __init__(self):
- self.operation = Gtk.PrintOperation()
- print_data = {'filename': os.path.abspath(__file__),
- 'font_size': 12.0,
- 'lines_per_page': 0,
- 'lines': None,
- 'num_lines': 0,
- 'num_pages': 0
- }
-
- self.operation.connect('begin-print', self.begin_print, print_data)
- self.operation.connect('draw-page', self.draw_page, print_data)
- self.operation.connect('end-print', self.end_print, print_data)
-
- self.operation.set_use_full_page(False)
- self.operation.set_unit(Gtk.Unit.POINTS)
- self.operation.set_embed_page_setup(True)
-
- settings = Gtk.PrintSettings()
-
- dir = GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_DOCUMENTS)
- if dir is None:
- dir = GLib.get_home_dir()
- if settings.get(Gtk.PRINT_SETTINGS_OUTPUT_FILE_FORMAT) == 'ps':
- ext = '.ps'
- elif settings.get(Gtk.PRINT_SETTINGS_OUTPUT_FILE_FORMAT) == 'svg':
- ext = '.svg'
- else:
- ext = '.pdf'
-
- uri = "file://%s/gtk-demo%s" % (dir, ext)
- settings.set(Gtk.PRINT_SETTINGS_OUTPUT_URI, uri)
- self.operation.set_print_settings(settings)
-
- def run(self, parent=None):
- result = self.operation.run(Gtk.PrintOperationAction.PRINT_DIALOG, parent)
-
- if result == Gtk.PrintOperationResult.ERROR:
- message = self.operation.get_error()
-
- dialog = Gtk.MessageDialog(parent,
- 0,
- Gtk.MessageType.ERROR,
- Gtk.ButtonsType.CLOSE,
- message)
-
- dialog.run()
- dialog.destroy()
-
- Gtk.main_quit()
-
- def begin_print(self, operation, print_ctx, print_data):
- height = print_ctx.get_height() - self.HEADER_HEIGHT - self.HEADER_GAP
- print_data['lines_per_page'] = \
- math.floor(height / print_data['font_size'])
-
- file_path = print_data['filename']
- if not os.path.isfile(file_path):
- file_path = os.path.join('demos', file_path)
- if not os.path.isfile(file_path):
- raise Exception("file not found: %s" % (file_path, ))
-
- # in reality you should most likely not read the entire
- # file into a buffer
- source_file = open(file_path, 'r')
- s = source_file.read()
- print_data['lines'] = s.split('\n')
-
- print_data['num_lines'] = len(print_data['lines'])
- print_data['num_pages'] = \
- (print_data['num_lines'] - 1) / print_data['lines_per_page'] + 1
-
- operation.set_n_pages(print_data['num_pages'])
-
- def draw_page(self, operation, print_ctx, page_num, print_data):
- cr = print_ctx.get_cairo_context()
- width = print_ctx.get_width()
-
- cr.rectangle(0, 0, width, self.HEADER_HEIGHT)
- cr.set_source_rgb(0.8, 0.8, 0.8)
- cr.fill_preserve()
-
- cr.set_source_rgb(0, 0, 0)
- cr.set_line_width(1)
- cr.stroke()
-
- layout = print_ctx.create_pango_layout()
- desc = Pango.FontDescription('sans 14')
- layout.set_font_description(desc)
-
- layout.set_text(print_data['filename'], -1)
- (text_width, text_height) = layout.get_pixel_size()
-
- if text_width > width:
- layout.set_width(width)
- layout.set_ellipsize(Pango.EllipsizeMode.START)
- (text_width, text_height) = layout.get_pixel_size()
-
- cr.move_to((width - text_width) / 2,
- (self.HEADER_HEIGHT - text_height) / 2)
- PangoCairo.show_layout(cr, layout)
-
- page_str = "%d/%d" % (page_num + 1, print_data['num_pages'])
- layout.set_text(page_str, -1)
-
- layout.set_width(-1)
- (text_width, text_height) = layout.get_pixel_size()
- cr.move_to(width - text_width - 4,
- (self.HEADER_HEIGHT - text_height) / 2)
- PangoCairo.show_layout(cr, layout)
-
- layout = print_ctx.create_pango_layout()
-
- desc = Pango.FontDescription('monospace')
- desc.set_size(print_data['font_size'] * Pango.SCALE)
- layout.set_font_description(desc)
-
- cr.move_to(0, self.HEADER_HEIGHT + self.HEADER_GAP)
- lines_pp = int(print_data['lines_per_page'])
- num_lines = print_data['num_lines']
- data_lines = print_data['lines']
- font_size = print_data['font_size']
- line = page_num * lines_pp
-
- for i in range(lines_pp):
- if line >= num_lines:
- break
-
- layout.set_text(data_lines[line], -1)
- PangoCairo.show_layout(cr, layout)
- cr.rel_move_to(0, font_size)
- line += 1
-
- def end_print(self, operation, print_ctx, print_data):
- pass
-
-
-def main(demoapp=None):
- app = PrintingApp()
- GLib.idle_add(app.run, demoapp.window)
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/rotatedtext.py b/examples/demo/demos/rotatedtext.py
deleted file mode 100644
index 4dac189..0000000
--- a/examples/demo/demos/rotatedtext.py
+++ /dev/null
@@ -1,191 +0,0 @@
-#!/usr/bin/env python
-# -*- Mode: Python; py-indent-offset: 4 -*-
-# vim: tabstop=4 shiftwidth=4 expandtab
-#
-# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-# USA
-
-title = "Rotated Text"
-description = """This demo shows how to use PangoCairo to draw rotated and
-transformed text. The right pane shows a rotated GtkLabel widget. In both
-cases, a custom PangoCairo shape renderer is installed to draw a red heard using
-cairo drawing operations instead of the Unicode heart character.
-"""
-
-from gi.repository import Gtk, Pango, PangoCairo, Gdk
-import cairo
-import math
-
-
-UTF8_TEXT = u"I ♥ GTK"
-HEART = u"♥"
-BYTES_TEXT = UTF8_TEXT.encode("utf-8")
-BYTES_HEART = HEART.encode("utf-8")
-
-
-class RotatedTextApp:
- RADIUS = 150
- N_WORDS = 5
- FONT = "Serif 18"
-
- def __init__(self):
-
- white = Gdk.RGBA()
- white.red = 1.0
- white.green = 1.0
- white.blue = 1.0
- white.alpha = 1.0
-
- self.window = Gtk.Window(title="Rotated Text")
- self.window.set_default_size(4 * self.RADIUS, 2 * self.RADIUS)
- self.window.connect('destroy', Gtk.main_quit)
-
- box = Gtk.HBox()
- box.set_homogeneous(True)
- self.window.add(box)
-
- # add a drawing area
- da = Gtk.DrawingArea()
- box.add(da)
-
- # override the background color from the theme
- da.override_background_color(0, white)
-
- da.connect('draw', self.rotated_text_draw)
-
- label = Gtk.Label(label=UTF8_TEXT)
- box.add(label)
- label.set_angle(45)
-
- # Setup some fancy stuff on the label
- layout = label.get_layout()
-
- PangoCairo.context_set_shape_renderer(layout.get_context(),
- self.fancy_shape_renderer,
- None)
- attrs = self.create_fancy_attr_list_for_layout(layout)
- label.set_attributes(attrs)
-
- self.window.show_all()
-
- def fancy_shape_renderer(self, cairo_ctx, attr, do_path):
- x, y = cairo_ctx.get_current_point()
- cairo_ctx.translate(x, y)
-
- cairo_ctx.scale(float(attr.inc_rect.width) / Pango.SCALE,
- float(attr.inc_rect.height) / Pango.SCALE)
-
- if int(attr.data) == 0x2665: # U+2665 BLACK HEART SUIT
- cairo_ctx.move_to(0.5, 0.0)
- cairo_ctx.line_to(0.9, -0.4)
- cairo_ctx.curve_to(1.1, -0.8, 0.5, -0.9, 0.5, -0.5)
- cairo_ctx.curve_to(0.5, -0.9, -0.1, -0.8, 0.1, -0.4)
- cairo_ctx.close_path()
-
- if not do_path:
- cairo_ctx.set_source_rgb(1.0, 0.0, 0.0)
- cairo_ctx.fill()
-
- def create_fancy_attr_list_for_layout(self, layout):
- pango_ctx = layout.get_context()
- metrics = pango_ctx.get_metrics(layout.get_font_description(),
- None)
- ascent = metrics.get_ascent()
-
- logical_rect = Pango.Rectangle()
- logical_rect.x = 0
- logical_rect.width = ascent
- logical_rect.y = -ascent
- logical_rect.height = ascent
-
- # Set fancy shape attributes for all hearts
- attrs = Pango.AttrList()
-
- # FIXME: attr_shape_new_with_data isn't introspectable
- '''
- ink_rect = logical_rect
- p = BYTES_TEXT.find(BYTES_HEART)
- while (p != -1):
- attr = Pango.attr_shape_new_with_data(ink_rect,
- logical_rect,
- ord(HEART),
- None)
- attr.start_index = p
- attr.end_index = p + len(BYTES_HEART)
- p = UTF8_TEXT.find(HEART, attr.end_index)
-
- attrs.insert(attr)
- '''
- return attrs
-
- def rotated_text_draw(self, da, cairo_ctx):
- # Create a cairo context and set up a transformation matrix so that the user
- # space coordinates for the centered square where we draw are [-RADIUS, RADIUS],
- # [-RADIUS, RADIUS].
- # We first center, then change the scale.
- width = da.get_allocated_width()
- height = da.get_allocated_height()
- device_radius = min(width, height) / 2.0
- cairo_ctx.translate(
- device_radius + (width - 2 * device_radius) / 2,
- device_radius + (height - 2 * device_radius) / 2)
- cairo_ctx.scale(device_radius / self.RADIUS,
- device_radius / self.RADIUS)
-
- # Create a subtle gradient source and use it.
- pattern = cairo.LinearGradient(-self.RADIUS, -self.RADIUS, self.RADIUS, self.RADIUS)
- pattern.add_color_stop_rgb(0.0, 0.5, 0.0, 0.0)
- pattern.add_color_stop_rgb(1.0, 0.0, 0.0, 0.5)
- cairo_ctx.set_source(pattern)
-
- # Create a PangoContext and set up our shape renderer
- context = da.create_pango_context()
- PangoCairo.context_set_shape_renderer(context,
- self.fancy_shape_renderer,
- None)
-
- # Create a PangoLayout, set the text, font, and attributes */
- layout = Pango.Layout(context=context)
- layout.set_text(UTF8_TEXT, -1)
- desc = Pango.FontDescription(self.FONT)
- layout.set_font_description(desc)
-
- attrs = self.create_fancy_attr_list_for_layout(layout)
- layout.set_attributes(attrs)
-
- # Draw the layout N_WORDS times in a circle */
- for i in range(self.N_WORDS):
- # Inform Pango to re-layout the text with the new transformation matrix
- PangoCairo.update_layout(cairo_ctx, layout)
-
- width, height = layout.get_pixel_size()
- cairo_ctx.move_to(-width / 2, -self.RADIUS * 0.9)
- PangoCairo.show_layout(cairo_ctx, layout)
-
- # Rotate for the next turn
- cairo_ctx.rotate(math.pi * 2 / self.N_WORDS)
-
- return False
-
-
-def main(demoapp=None):
- RotatedTextApp()
- Gtk.main()
-
-
-if __name__ == '__main__':
- main()
diff --git a/examples/demo/demos/test.py b/examples/demo/demos/test.py
deleted file mode 100644
index 4bd7684..0000000
--- a/examples/demo/demos/test.py
+++ /dev/null
@@ -1,16 +0,0 @@
-title = "Test Demo"
-description = "Dude this is a test"
-
-
-from gi.repository import Gtk
-
-
-def _quit(*args):
- Gtk.main_quit()
-
-
-def main(demoapp=None):
- window = Gtk.Window()
- window.connect_after('destroy', _quit)
- window.show_all()
- Gtk.main()
diff --git a/examples/option.py b/examples/option.py
deleted file mode 100644
index 73860f5..0000000
--- a/examples/option.py
+++ /dev/null
@@ -1,28 +0,0 @@
-#!/usr/bin/env python
-
-from gi.repository import GLib
-
-group = GLib.option.OptionGroup(
- "example", "OptionGroup Example", "Shows all example options",
- option_list=[GLib.option.make_option("--example",
- action="store_true",
- dest="example",
- help="An example option."),
- ])
-
-parser = GLib.option.OptionParser(
- "NAMES ...", description="A simple gobject.option example.",
- option_list=[GLib.option.make_option("--file", "-f",
- type="filename",
- action="store",
- dest="file",
- help="A filename option"),
- # ...
- ])
-
-parser.add_option_group(group)
-
-parser.parse_args()
-
-print("group: example " + str(group.values.example))
-print("parser: file " + str(parser.values.file))
diff --git a/examples/properties.py b/examples/properties.py
deleted file mode 100644
index 257e80a..0000000
--- a/examples/properties.py
+++ /dev/null
@@ -1,33 +0,0 @@
-from gi.repository import GObject
-
-
-class MyObject(GObject.GObject):
-
- foo = GObject.Property(type=str, default='bar')
- boolprop = GObject.Property(type=bool, default=False)
-
- def __init__(self):
- GObject.GObject.__init__(self)
-
- @GObject.Property
- def readonly(self):
- return 'readonly'
-
-
-GObject.type_register(MyObject)
-
-print("MyObject properties: ", list(MyObject.props))
-
-obj = MyObject()
-
-print("obj.foo ==", obj.foo)
-
-obj.foo = 'spam'
-print("obj.foo = spam")
-
-print("obj.foo == ", obj.foo)
-
-print("obj.boolprop == ", obj.boolprop)
-
-print(obj.readonly)
-obj.readonly = 'does-not-work'
diff --git a/examples/signal.py b/examples/signal.py
deleted file mode 100644
index 69c1d62..0000000
--- a/examples/signal.py
+++ /dev/null
@@ -1,42 +0,0 @@
-from __future__ import print_function
-
-from gi.repository import GObject
-
-
-class C(GObject.GObject):
- @GObject.Signal(arg_types=(int,))
- def my_signal(self, arg):
- """Decorator style signal which uses the method name as signal name and
- the method as the closure.
-
- Note that with python3 annotations can be used for argument types as follows:
- @GObject.Signal
- def my_signal(self, arg:int):
- pass
- """
- print("C: class closure for `my_signal' called with argument", arg)
-
- @GObject.Signal
- def noarg_signal(self):
- """Decoration of a signal using all defaults and no arguments."""
- print("C: class closure for `noarg_signal' called")
-
-
-class D(C):
- def do_my_signal(self, arg):
- print("D: class closure for `my_signal' called. Chaining up to C")
- C.my_signal(self, arg)
-
-
-def my_signal_handler(obj, arg, *extra):
- print("handler for `my_signal' called with argument", arg, "and extra args", extra)
-
-
-inst = C()
-inst2 = D()
-
-inst.connect("my_signal", my_signal_handler, 1, 2, 3)
-inst.connect("noarg_signal", my_signal_handler, 1, 2, 3)
-inst.emit("my_signal", 42)
-inst.emit("noarg_signal")
-inst2.emit("my_signal", 42)
diff --git a/gi/_option.py b/gi/_option.py
index 947b11d..b7d6566 100644
--- a/gi/_option.py
+++ b/gi/_option.py
@@ -94,7 +94,7 @@ class Option(optparse.Option):
def __init__(self, *args, **kwargs):
warnings.warn(
- "gi.repository.GLib.option.Option is depecated, use gi.repository.GLib.OptionEntry instead",
+ "gi.repository.GLib.option.Option is deprecated, use gi.repository.GLib.OptionEntry instead",
PyGIDeprecationWarning
)
optparse.Option.__init__(self, *args, **kwargs)
@@ -175,7 +175,7 @@ def __init__(self, name, description, help_description="",
option_list=None, defaults=None,
translation_domain=None):
warnings.warn(
- "gi.repository.GLib.option.OptionGroup is depecated, use gi.repository.GLib.OptionContext instead",
+ "gi.repository.GLib.option.OptionGroup is deprecated, use gi.repository.GLib.OptionContext instead",
PyGIDeprecationWarning
)
optparse.OptionContainer.__init__(self, Option, 'error', description)
@@ -270,7 +270,7 @@ class OptionParser(optparse.OptionParser):
def __init__(self, *args, **kwargs):
warnings.warn(
- "gi.repository.GLib.option.OptionParser is depecated, use gi.repository.GLib.OptionContext instead",
+ "gi.repository.GLib.option.OptionParser is deprecated, use gi.repository.GLib.OptionContext instead",
PyGIDeprecationWarning
)
if 'option_class' not in kwargs:
diff --git a/gi/_ossighelper.py b/gi/_ossighelper.py
index fba24e6..543bbe1 100644
--- a/gi/_ossighelper.py
+++ b/gi/_ossighelper.py
@@ -18,6 +18,7 @@
import os
import socket
import signal
+import asyncio
import threading
from contextlib import closing, contextmanager
@@ -127,6 +128,7 @@ def signal_notify(source, condition):
PyOS_getsig = _gi.pyos_getsig
+PyOS_setsig = _gi.pyos_setsig
# We save the signal pointer so we can detect if glib has changed the
# signal handler behind Python's back (GLib.unix_signal_add)
@@ -237,3 +239,37 @@ def sigint_handler(sig_num, frame):
signal.default_int_handler(signal.SIGINT, None)
else:
_callback_stack.pop()
+
+
+class DummyEventLoop():
+ @classmethod
+ @contextmanager
+ def paused(cls):
+ yield
+
+ @classmethod
+ @contextmanager
+ def running(cls, quit_func):
+ with wakeup_on_signal():
+ yield
+
+
+def get_event_loop(ctx):
+ """Return the correct GLibEventLoop or a dummy that just registers the
+ signal wakeup mechanism."""
+
+ # Try to use the running loop. If there is none, get the policy and
+ # try getting one in the hope that this will give us an event loop for the
+ # correct context.
+ loop = asyncio._get_running_loop()
+ if loop is None:
+ try:
+ loop = asyncio.get_event_loop_policy().get_event_loop_for_context(ctx)
+ except:
+ pass
+
+ if loop and hasattr(loop, '_context'):
+ if ctx is not None and hash(loop._context) == hash(ctx):
+ return loop
+
+ return DummyEventLoop
diff --git a/gi/events.py b/gi/events.py
new file mode 100644
index 0000000..94789e3
--- /dev/null
+++ b/gi/events.py
@@ -0,0 +1,650 @@
+# -*- Mode: Python; py-indent-offset: 4 -*-
+# pygobject - Python bindings for the GObject library
+# Copyright (C) 2021 Benjamin Berg
+#
+# gi/asyncio.py: GObject asyncio integration
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, see .
+
+__all__ = ['GLibEventLoopPolicy', 'GLibEventLoop']
+
+import sys
+import asyncio
+from asyncio import coroutines
+import signal
+import threading
+import selectors
+import weakref
+import warnings
+from contextlib import contextmanager
+from . import _ossighelper
+
+from gi.repository import GLib
+
+try:
+ g_main_loop_run = super(GLib.MainLoop, GLib.MainLoop).run
+except AttributeError:
+ g_main_loop_run = GLib.MainLoop.run
+
+
+class _GLibEventLoopMixin:
+ """
+ Base functionally required for both proactor and selector.
+
+ The proactor/selector is always available through _selector, and we assume
+ it has the following extra functionality that we provide:
+ * _source: the GSource subclass
+ * _dispatching: boolean whether it is dispatching currently
+ * attach/detach: add/remove the GSource from the main context
+
+ In principle, we simply override run_forever to call into GLib, with the
+ assumption that a GSource is registered which will then call back into
+ the python mainloop _run_once handler when needed. This in turn calls
+ self._selector.select(), which means we just need to make sure to return
+ our already prepared events at that point.
+ """
+
+ def __init__(self, main_context):
+ # A mainloop in case we want to run our context
+ assert main_context is not None
+ self._context = main_context
+ self._main_loop = GLib.MainLoop.new(self._context, False)
+ self._quit_funcs = []
+
+ @contextmanager
+ def paused(self):
+ """This context manager ensures the EventLoop is *not* being iterated.
+
+ It purely exist to handle the case where python code iterates the main
+ context more gracefully."""
+ # Nothing to do if we are not running or dispatched by ourselves
+ if not self.is_running() or self._selector._source._dispatching:
+ yield
+ return
+
+ try:
+ self._selector.detach()
+ yield
+ finally:
+ self._selector.attach()
+
+ @contextmanager
+ def running(self, quit_func):
+ """This context manager ensures the EventLoop is marked as running
+ while other API is iterating its main context.
+ The passed quit function is used to stop all recursion levels when
+ stop() is called.
+ """
+ assert self._context.acquire()
+
+ self._quit_funcs.append(quit_func)
+ # Nested main context iteration (by using glib API)
+ if self.is_running():
+ try:
+ yield
+ finally:
+ self._context.release()
+ self._quit_funcs.pop()
+ # Stop recursively
+ if self._stopping:
+ self._quit_funcs[-1]()
+ return
+
+ # Outermost nesting
+ self._check_closed()
+ self._set_coroutine_origin_tracking(self._debug)
+ self._thread_id = threading.get_ident()
+
+ old_agen_hooks = sys.get_asyncgen_hooks()
+ sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
+ finalizer=self._asyncgen_finalizer_hook)
+ try:
+ asyncio._set_running_loop(self)
+ assert not self._selector._source._dispatching
+ self._selector.attach()
+ yield
+ finally:
+ self._selector.detach()
+ self._context.release()
+ self._thread_id = None
+ asyncio._set_running_loop(None)
+ try:
+ self._set_coroutine_origin_tracking(False)
+ except AttributeError:
+ pass
+ sys.set_asyncgen_hooks(*old_agen_hooks)
+
+ self._quit_funcs.pop()
+ assert len(self._quit_funcs) == 0
+ self._stopping = False
+
+ def time(self):
+ return GLib.get_monotonic_time() / 1000000
+
+ def _get_timeout_ms(self):
+ if not self.is_running():
+ warnings.warn('GLibEventLoop is iterated without being marked as running. Missing override or invalid use of existing API!', RuntimeWarning)
+ if self._stopping is True:
+ warnings.warn('GLibEventLoop is not stopping properly. Missing override or invalid use of existing API!', RuntimeWarning)
+ if self._ready:
+ return 0
+
+ if self._scheduled:
+ # The time is floor'ed here.
+ # Python dispatches everything ready within the next _clock_resolution.
+ timeout = int((self._scheduled[0]._when - self.time()) * 1000)
+ return timeout if timeout >= 0 else 0
+
+ return -1
+
+ def stop(self):
+ # Simply quit the mainloop
+ self._stopping = True
+ if self._quit_funcs:
+ self._quit_funcs[-1]()
+
+ def __repr__(self):
+ return (
+ f'<{self.__class__.__name__} running={self.is_running()} '
+ f'closed={self.is_closed()} debug={self.get_debug()} '
+ f'ctx=0x{hash(self._context):X} loop=0x{hash(self._main_loop):X}>'
+ )
+
+
+class _GLibEventLoopRunMixin:
+ # This class exists so we don't need to copy the ProactorEventLoop.run_forever,
+ # instead, we change the MRO using a metaclass, so that super() sees this class
+ # when called in ProactorEventLoop.run_forever.
+
+ def run_forever(self):
+ # NOTE: self._check_running was only added in 3.8 (with a typo in 3.7)
+ if self.is_running():
+ raise RuntimeError('This event loop is already running')
+
+ with _ossighelper.register_sigint_fallback(self._main_loop.quit):
+ with self.running(self._main_loop.quit):
+ g_main_loop_run(self._main_loop)
+
+
+class _SourceBase(GLib.Source):
+ """Common Source functionality for both unix and win32"""
+ def __init__(self, selector):
+ super().__init__()
+
+ self._dispatching = False
+
+ # It is *not* safe to run the *python* part of the mainloop recursively.
+ # This error must be caught further up in the chain, otherwise the
+ # mainloop will be blocking without an obvious reason.
+ self.set_can_recurse(False)
+ self.set_name('python asyncio integration')
+
+ self._selector = selector
+ # NOTE: Avoid loop -> selector -> source -> loop reference cycle,
+ # we need the source to be destroyed *after* the selector. Otherwise
+ # we need a flag to deal with FDs being unregistered after __del__ has
+ # been called on the source.
+ self._loop = weakref.ref(selector._loop)
+
+ self._ready = []
+
+ def dispatch(self, callback, args):
+ # Now, wag the dog by its tail
+ self._dispatching = True
+ try:
+ self._loop()._run_once()
+ finally:
+ self._dispatching = False
+
+ return GLib.SOURCE_CONTINUE
+
+ def _get_ready(self):
+ if not self._dispatching:
+ raise RuntimeError("gi.asyncio.Selector.select only works while it is dispatching!")
+
+ ready = self._ready
+ self._ready = []
+ return ready
+
+
+class _SelectorMixin:
+ """A Mixin for common functionality of the Selector and Proactor."""
+
+ def __init__(self, context, loop):
+ super().__init__()
+
+ self._context = context
+ self._loop = loop
+ self._fd_to_key = {}
+
+ self._source = _Source(self)
+
+ def close(self):
+ if self._source:
+ self._source.destroy()
+ self._source = None
+ super().close()
+
+ def select(self, timeout=None):
+ return self._source._get_ready()
+
+ def _real_select(self, timeout=None):
+ return super().select(timeout)
+
+
+if sys.platform != 'win32':
+ class GLibEventLoop(_GLibEventLoopMixin, _GLibEventLoopRunMixin, asyncio.SelectorEventLoop):
+ """An asyncio event loop that runs the python mainloop inside GLib.
+
+ Based on the asyncio.SelectorEventLoop"""
+
+ _GLIB_SIGNALS = {signal.SIGHUP, signal.SIGINT, signal.SIGTERM, signal.SIGUSR1, signal.SIGUSR2, signal.SIGWINCH}
+
+ # This is based on the selector event loop, but never actually runs select()
+ # in the strict sense.
+ # We use the selector to register all FDs with the main context using our
+ # own GSource. For python timeouts/idle equivalent, we directly query them
+ # from the context by providing the _get_timeout_ms function that the
+ # GSource uses. This in turn accesses _ready and _scheduled to calculate
+ # the timeout and whether python can dispatch anything non-FD based yet.
+ #
+ # The Selector select() method simply returns the information we already
+ # collected.
+ #
+ # The rest is done by the mixin which overrides run_forever to simply
+ # iterate the main context.
+ def __init__(self, main_context):
+ _GLibEventLoopMixin.__init__(self, main_context)
+
+ # _UnixSelectorEventLoop uses _signal_handlers, we could do the same,
+ # with the difference that close() would clean up the handlers for us.
+ self.__signal_handlers = {}
+
+ selector = _Selector(self._context, self)
+ asyncio.SelectorEventLoop.__init__(self, selector)
+
+ # Used by run_once to not busy loop if the timeout is floor'ed to zero
+ self._clock_resolution = 1e-3
+
+ def add_signal_handler(self, sig, callback, *args):
+ """Add a handler for UNIX signal"""
+
+ if (coroutines.iscoroutine(callback) or
+ coroutines.iscoroutinefunction(callback)):
+ raise TypeError("coroutines cannot be used "
+ "with add_signal_handler()")
+ self._check_closed()
+
+ # Can be useful while testing failures
+ # assert sig != signal.SIGALRM
+
+ if sig not in self._GLIB_SIGNALS:
+ return super().add_signal_handler(sig, callback, *args)
+
+ # Pure python demands that there is only one signal handler
+ source, _, _ = self.__signal_handlers.get(sig, (None, None, None))
+ if source:
+ source.destroy()
+
+ # Setup a new source with a higher priority than our main one
+ source = GLib.unix_signal_source_new(sig)
+ source.set_name(f"asyncio signal watch for {sig}")
+ source.set_priority(GLib.PRIORITY_HIGH)
+ source.attach(self._context)
+ source.set_callback(self._signal_cb, sig)
+
+ self.__signal_handlers[sig] = (source, callback, args)
+ del source
+
+ def remove_signal_handler(self, sig):
+ if sig not in self._GLIB_SIGNALS:
+ return super().remove_signal_handler(sig)
+
+ try:
+ source, _, _ = self.__signal_handlers[sig]
+ del self.__signal_handlers[sig]
+ # Really unref the underlying GSource so that GLib resets the signal handler
+ source.destroy()
+ source._clear_boxed()
+
+ # GLib does not restore the original signal handler.
+ # Try to restore the python handler for SIGINT, this makes
+ # Ctrl+C work after the mainloop has quit.
+ if sig == signal.SIGINT and _ossighelper.PyOS_getsig(signal.SIGINT) == 0:
+ if _ossighelper.startup_sigint_ptr > 0:
+ _ossighelper.PyOS_setsig(signal.SIGINT, _ossighelper.startup_sigint_ptr)
+
+ return True
+ except KeyError:
+ return False
+
+ def _signal_cb(self, sig):
+ source, cb, args = self.__signal_handlers.get(sig)
+
+ # Pass over to python mainloop
+ self.call_soon(cb, *args)
+
+ def close(self):
+ super().close()
+ for s in list(self.__signal_handlers):
+ self.remove_signal_handler(s)
+
+ def _fileobj_to_fd(fileobj):
+ # Note: SelectorEventloop should only be passing FDs
+ if isinstance(fileobj, int):
+ return fileobj
+ else:
+ return fileobj.fileno()
+
+ class _Source(_SourceBase):
+ def prepare(self):
+ timeout = self._loop()._get_timeout_ms()
+
+ # NOTE: Always return False, FDs are queried in check and the timeout
+ # needs to be rechecked anyway.
+ return False, timeout
+
+ def check(self):
+ ready = []
+
+ for key in self._selector._fd_to_key.values():
+ condition = self.query_unix_fd(key._tag)
+ events = 0
+ # ERR/HUP/NVAL trigger both read/write (PRI cannot happen)
+ if condition & ~GLib.IOCondition.OUT:
+ events |= selectors.EVENT_READ
+ if condition & ~GLib.IOCondition.IN:
+ events |= selectors.EVENT_WRITE
+ if events:
+ ready.append((key, events))
+ self._ready = ready
+
+ timeout = self._loop()._get_timeout_ms()
+ if timeout == 0:
+ return True
+
+ return bool(ready)
+
+ class _SelectorKey(selectors.SelectorKey):
+ # Subclass to attach _tag
+ pass
+
+ class _Selector(_SelectorMixin, selectors.BaseSelector):
+ """A Selector for gi.events.GLibEventLoop registering python IO with GLib."""
+
+ def attach(self):
+ self._source.attach(self._loop._context)
+
+ def detach(self):
+ self._source.destroy()
+ self._source = _Source(self)
+ # re-register the keys with the new source
+ for key in self._fd_to_key.values():
+ self._register_key(key)
+
+ def _register_key(self, key):
+ condition = GLib.IOCondition(0)
+ if key.events & selectors.EVENT_READ:
+ condition |= GLib.IOCondition.IN
+ if key.events & selectors.EVENT_WRITE:
+ condition |= GLib.IOCondition.OUT
+ key._tag = self._source.add_unix_fd(key.fd, condition)
+
+ def register(self, fileobj, events, data=None):
+ if (not events) or (events & ~(selectors.EVENT_READ | selectors.EVENT_WRITE)):
+ raise ValueError("Invalid events: {!r}".format(events))
+
+ fd = _fileobj_to_fd(fileobj)
+ assert fd not in self._fd_to_key
+
+ key = _SelectorKey(fileobj, fd, events, data)
+
+ self._register_key(key)
+
+ self._fd_to_key[fd] = key
+ return key
+
+ def unregister(self, fileobj):
+ # NOTE: may be called after __del__ has been called.
+ fd = _fileobj_to_fd(fileobj)
+ key = self._fd_to_key[fd]
+
+ if self._source:
+ self._source.remove_unix_fd(key._tag)
+ del self._fd_to_key[fd]
+
+ return key
+
+ # We could override modify, but it is only slightly when the "events" change.
+
+ def get_key(self, fileobj):
+ fd = _fileobj_to_fd(fileobj)
+ return self._fd_to_key[fd]
+
+ def get_map(self):
+ """Return a mapping of file objects to selector keys."""
+ # Horribly inefficient
+ # It should never be called and exists just to prevent issues if e.g.
+ # python decides to use it for debug purposes.
+ return {k.fileobj: k for k in self._fd_to_key.values()}
+
+
+else:
+ class _PushRunMixinBackMeta(type):
+ # This metaclass changes the MRO so that when run_forever is called, it
+ # first calls asyncio.ProactorEventLoop and then chains into
+ # _GLibEventLoopRunMixin.run_forever using super().
+ # The alternative would be to copy asyncio.ProactorEventLoop.run_forever
+ def mro(cls):
+ mro = type.mro(cls)
+ idx = mro.index(_GLibEventLoopRunMixin)
+
+ return [*mro[:idx], mro[idx + 1], mro[idx], *mro[idx + 2:]]
+
+ class GLibEventLoop(_GLibEventLoopMixin, _GLibEventLoopRunMixin, asyncio.ProactorEventLoop, metaclass=_PushRunMixinBackMeta):
+ """An asyncio event loop that runs the python mainloop inside GLib.
+
+ Based on the asyncio.WindowsProactorEventLoopPolicy"""
+
+ # This is based on the Windows ProactorEventLoop
+ def __init__(self, main_context):
+ _GLibEventLoopMixin.__init__(self, main_context)
+
+ proactor = _Proactor(self._context, self)
+ # Sets both self._proactor and self._selector to the proactor
+ asyncio.ProactorEventLoop.__init__(self, proactor)
+
+ # Used by run_once to not busy loop if the timeout is floor'ed to zero
+ self._clock_resolution = 1e-3
+
+ class _Source(_SourceBase):
+ def __init__(self, proactor):
+ self._proactor = proactor
+ super().__init__(proactor)
+
+ # None denotes it is disabled (and will also not handle timeouts)
+ self._poll_fd = None
+
+ def enable(self):
+ assert self._poll_fd is None
+
+ self._poll_fd = GLib.PollFD(self._proactor._iocp, GLib.IO_IN)
+ self.add_poll(self._poll_fd)
+
+ def disable(self):
+ self.remove_poll(self._poll_fd)
+ self._poll_fd = None
+
+ def prepare(self):
+ # Disabled, do not handle timeouts either
+ if self._poll_fd is None:
+ return False, -1
+
+ timeout = self._loop()._get_timeout_ms()
+
+ return bool(self._ready), timeout
+
+ def check(self):
+ if self._poll_fd is None:
+ return False
+
+ if self._poll_fd.revents:
+ self._ready.extend(self._proactor._real_select(0))
+
+ if self._ready:
+ return True
+
+ if self._loop()._get_timeout_ms() == 0:
+ return True
+
+ return False
+
+ class _Proactor(_SelectorMixin, asyncio.IocpProactor):
+ """A Proactor for gi.events.GLibEventLoop registering python IO with GLib."""
+
+ def __init__(self, context, loop):
+ super().__init__(context, loop)
+
+ # We always use the same Source on windows, it disables itself
+ self._source = _Source(self)
+ self._source.attach(context)
+
+ def attach(self):
+ self._source.enable()
+
+ def detach(self):
+ self._source.disable()
+
+
+class GLibEventLoopPolicy(asyncio.AbstractEventLoopPolicy):
+ """An asyncio event loop policy that runs the GLib main loop.
+
+ The policy allows creating a new EventLoop for threads other than the main
+ thread. For the main thread, you can use get_event_loop() to retrieve the
+ correct mainloop and run it.
+
+ Note that, unlike GLib, python does not support running the EventLoop
+ recursively. You should never iterate the GLib.MainContext from within
+ the python EventLoop as doing so prevents asyncio events from being
+ dispatched.
+
+ As such, do not use API such as GLib.MainLoop.run or Gtk.Dialog.run.
+ Instead use the proper asynchronous patterns to prevent entirely blocking
+ asyncio.
+ """
+
+ def __init__(self):
+ self._loops = {}
+ self._child_watcher = None
+
+ def get_event_loop(self):
+ """Get the event loop for the current context.
+
+ Returns an event loop object for the thread default GLib.MainContext
+ or in case of the main thread for the default GLib.MainContext.
+
+ An exception will be thrown if there is no GLib.MainContext for the
+ current thread. In that case, using new_event_loop() will create a new
+ main context and main loop which can subsequently attached to the thread
+ by calling set_event_loop().
+
+ Returns a new GLibEventLoop or raises an exception."""
+
+ # Get the thread default main context
+ ctx = GLib.MainContext.get_thread_default()
+ # If there is none, and we are on the main thread, then use the default context
+ if ctx is None and threading.current_thread() is threading.main_thread():
+ ctx = GLib.MainContext.default()
+
+ # We do not create a main context implicitly;
+ # we create a mainloop for an existing context though
+ if ctx is None:
+ raise RuntimeError('There is no main context set for thread %r.'
+ % threading.current_thread().name)
+
+ return self.get_event_loop_for_context(ctx)
+
+ def get_event_loop_for_context(self, ctx):
+ """Get the event loop for a specific context."""
+ # Note: We cannot attach it to ctx, as getting the default will always
+ # return a new python wrapper. But, we can use hash() as that returns
+ # the pointer to the C structure.
+ try:
+ loop = self._loops[hash(ctx)]
+ if not loop.is_closed():
+ return loop
+ except KeyError:
+ pass
+
+ self._loops[hash(ctx)] = GLibEventLoop(ctx)
+ if self._child_watcher and ctx == GLib.MainContext.default():
+ self._child_watcher.attach_loop(self.get_event_loop())
+ return self._loops[hash(ctx)]
+
+ def set_event_loop(self, loop):
+ """Set the event loop for the current context (python thread) to loop.
+
+ This is only permitted if the thread has no thread default main context
+ with the main thread using the default main context.
+ """
+
+ # Only accept glib event loops, otherwise things will just mess up
+ assert loop is None or isinstance(loop, GLibEventLoop)
+
+ ctx = ctx_td = GLib.MainContext.get_thread_default()
+ if ctx is None and threading.current_thread() is threading.main_thread():
+ ctx = GLib.MainContext.default()
+
+ if loop is None:
+ # We do permit unsetting the current loop/context
+ old = self._loops.pop(hash(ctx), None)
+ if old:
+ if hash(old._context) != hash(ctx):
+ warnings.warn('GMainContext was changed unknowingly by asyncio integration!', RuntimeWarning)
+ if ctx_td:
+ GLib.MainContext.pop_thread_default(ctx_td)
+ else:
+ # Only allow attaching if the thread has no main context yet
+ if ctx:
+ raise RuntimeError('Thread %r already has a main context, get_event_loop() will create a new loop if needed'
+ % threading.current_thread().name)
+
+ GLib.MainContext.push_thread_default(loop._context)
+ self._loops[hash(loop._context)] = loop
+
+ def new_event_loop(self):
+ """Create and return a new event loop that iterates a new
+ GLib.MainContext."""
+
+ return GLibEventLoop(GLib.MainContext())
+
+ # NOTE: We do *not* provide a GLib based ChildWatcher implementation!
+ # This is *intentional* and *required*. The issue is that python provides
+ # API which uses wait4() internally. GLib at the same time uses a thread to
+ # handle SIGCHLD signals, which causes a race condition resulting in a
+ # critical warning.
+ # We just provide a reasonable sane child watcher and disallow the user
+ # from choosing one as e.g. MultiLoopChildWatcher is problematic.
+ #
+ # TODO: Use PidfdChildWatcher when available
+ if sys.platform != 'win32':
+ def get_child_watcher(self):
+ if self._child_watcher is None:
+ self._child_watcher = asyncio.ThreadedChildWatcher()
+
+ if threading.current_thread() is threading.main_thread():
+ self._child_watcher.attach_loop(self.get_event_loop())
+
+ return self._child_watcher
diff --git a/gi/gimodule.c b/gi/gimodule.c
index 3541040..e27a239 100644
--- a/gi/gimodule.c
+++ b/gi/gimodule.c
@@ -34,6 +34,7 @@
#include "pygi-error.h"
#include "pygi-foreign.h"
#include "pygi-resulttuple.h"
+#include "pygi-async.h"
#include "pygi-source.h"
#include "pygi-ccallback.h"
#include "pygi-closure.h"
@@ -46,7 +47,6 @@
#include "pygoptioncontext.h"
#include "pygoptiongroup.h"
#include "pygspawn.h"
-#include "pygparamspec.h"
#include "pygpointer.h"
#include "pygobject-internal.h"
#include "pygi-value.h"
@@ -408,58 +408,20 @@ create_property (const gchar *prop_name,
return pspec;
}
+static PyObject *
+pyg_param_spec_new (GParamSpec *pspec)
+{
+ PyErr_SetString (PyExc_NotImplementedError,
+ "Creating ParamSpecs through pyg_param_spec_new is no longer supported");
+ return NULL;
+}
+
static GParamSpec *
pyg_param_spec_from_object (PyObject *tuple)
{
- Py_ssize_t val_length;
- const gchar *prop_name;
- GType prop_type;
- const gchar *nick, *blurb;
- PyObject *slice, *item, *py_prop_type;
- GParamSpec *pspec;
- gint intvalue;
-
- val_length = PyTuple_Size(tuple);
- if (val_length < 4) {
- PyErr_SetString(PyExc_TypeError,
- "paramspec tuples must be at least 4 elements long");
- return NULL;
- }
-
- slice = PySequence_GetSlice(tuple, 0, 4);
- if (!slice) {
- return NULL;
- }
-
- if (!PyArg_ParseTuple(slice, "sOzz", &prop_name, &py_prop_type, &nick, &blurb)) {
- Py_DECREF(slice);
- return NULL;
- }
-
- Py_DECREF(slice);
-
- prop_type = pyg_type_from_object(py_prop_type);
- if (!prop_type) {
- return NULL;
- }
-
- item = PyTuple_GetItem(tuple, val_length-1);
- if (!PyLong_Check (item)) {
- PyErr_SetString(PyExc_TypeError,
- "last element in tuple must be an int");
- return NULL;
- }
-
- if (!pygi_gint_from_py (item, &intvalue))
- return NULL;
-
- /* slice is the extra items in the tuple */
- slice = PySequence_GetSlice(tuple, 4, val_length-1);
- pspec = create_property(prop_name, prop_type,
- nick, blurb, slice,
- intvalue);
-
- return pspec;
+ PyErr_SetString (PyExc_NotImplementedError,
+ "Creating ParamSpecs through pyg_param_spec_from_object is no longer supported");
+ return NULL;
}
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
@@ -922,7 +884,7 @@ pyg_object_set_property (GObject *object, guint property_id,
return;
}
- py_pspec = pyg_param_spec_new(pspec);
+ py_pspec = pygi_fundamental_new(pspec);
py_value = pyg_value_as_pyobject (value, TRUE);
retval = PyObject_CallMethod(object_wrapper, "do_set_property",
@@ -2263,7 +2225,7 @@ pyg_object_class_list_properties (PyObject *self, PyObject *args)
return NULL;
}
for (i = 0; i < nprops; i++) {
- PyTuple_SetItem(list, i, pyg_param_spec_new(specs[i]));
+ PyTuple_SetItem(list, i, pygi_fundamental_new(specs[i]));
}
g_free(specs);
if (class)
@@ -2298,6 +2260,18 @@ _wrap_pyig_pyos_getsig (PyObject *self, PyObject *args)
return PyLong_FromVoidPtr ((void *)(PyOS_getsig (sig_num)));
}
+static PyObject *
+_wrap_pyig_pyos_setsig (PyObject *self, PyObject *args)
+{
+ int sig_num;
+ PyObject *sig_handler;
+
+ if (!PyArg_ParseTuple (args, "iO!:pyos_setsig", &sig_num, &PyLong_Type, &sig_handler))
+ return NULL;
+
+ return PyLong_FromVoidPtr ((void *)(PyOS_setsig (sig_num, (PyOS_sighandler_t) PyLong_AsVoidPtr (sig_handler))));
+}
+
static PyObject *
_wrap_pygobject_new_full (PyObject *self, PyObject *args)
{
@@ -2336,6 +2310,7 @@ static PyMethodDef _gi_functions[] = {
{ "variant_type_from_string", (PyCFunction) _wrap_pyg_variant_type_from_string, METH_VARARGS },
{ "source_new", (PyCFunction) pygi_source_new, METH_NOARGS },
{ "pyos_getsig", (PyCFunction) _wrap_pyig_pyos_getsig, METH_VARARGS },
+ { "pyos_setsig", (PyCFunction) _wrap_pyig_pyos_setsig, METH_VARARGS },
{ "source_set_callback", (PyCFunction) pygi_source_set_callback, METH_VARARGS },
{ "io_channel_read", (PyCFunction) pyg_channel_read, METH_VARARGS },
{ "require_foreign", (PyCFunction) pygi_require_foreign, METH_VARARGS | METH_KEYWORDS },
@@ -2372,6 +2347,8 @@ static struct PyGI_API CAPI = {
pygi_register_foreign_struct,
};
+const gpointer PyGParamSpec_Type_Stub = NULL;
+
struct _PyGObject_Functions pygobject_api_functions = {
pygobject_register_class,
pygobject_register_wrapper,
@@ -2411,7 +2388,7 @@ struct _PyGObject_Functions pygobject_api_functions = {
(PyGThreadBlockFunc)0, /* block_threads */
(PyGThreadBlockFunc)0, /* unblock_threads */
- &PyGParamSpec_Type,
+ (PyTypeObject *) &PyGParamSpec_Type_Stub,
pyg_param_spec_new,
pyg_param_spec_from_object,
@@ -2598,6 +2575,8 @@ _gi_exec (PyObject *module)
return ret;
if ((ret = pygi_resulttuple_register_types (module)) < 0)
return ret;
+ if ((ret = pygi_async_register_types (module) < 0))
+ return ret;
if ((ret = pygi_spawn_register_types (module_dict)) < 0)
return ret;
@@ -2618,8 +2597,6 @@ _gi_exec (PyObject *module)
return ret;
if ((ret = pygi_interface_register_types (module_dict)) < 0)
return ret;
- if ((ret = pygi_paramspec_register_types (module_dict)) < 0)
- return ret;
if ((ret = pygi_enum_register_types (module_dict)) < 0)
return ret;
if ((ret = pygi_flags_register_types (module_dict)) < 0)
diff --git a/gi/meson.build b/gi/meson.build
index c0ae04e..30e1410 100644
--- a/gi/meson.build
+++ b/gi/meson.build
@@ -4,7 +4,6 @@ sources = [
'pygflags.c',
'pyginterface.c',
'pygobject-object.c',
- 'pygparamspec.c',
'pygpointer.c',
'pygoptioncontext.c',
'pygoptiongroup.c',
@@ -17,6 +16,7 @@ sources = [
'pygi-source.c',
'pygi-argument.c',
'pygi-resulttuple.c',
+ 'pygi-async.c',
'pygi-type.c',
'pygi-boxed.c',
'pygi-closure.c',
@@ -45,6 +45,7 @@ headers = [
install_headers(headers, subdir : 'pygobject-@0@'.format(platform_version))
python_sources = [
+ 'events.py',
'_constants.py',
'docstring.py',
'_error.py',
diff --git a/gi/overrides/GLib.py b/gi/overrides/GLib.py
index 0425d50..ba32d75 100644
--- a/gi/overrides/GLib.py
+++ b/gi/overrides/GLib.py
@@ -23,7 +23,7 @@
import sys
import socket
-from .._ossighelper import wakeup_on_signal, register_sigint_fallback
+from .._ossighelper import register_sigint_fallback, get_event_loop
from ..module import get_introspection_module
from .._gi import (variant_type_from_string, source_new,
source_set_callback, io_channel_read)
@@ -493,7 +493,7 @@ def __init__(self, context=None):
def run(self):
with register_sigint_fallback(self.quit):
- with wakeup_on_signal():
+ with get_event_loop(self.get_context()).running(self.quit):
super(MainLoop, self).run()
@@ -504,7 +504,8 @@ def run(self):
class MainContext(GLib.MainContext):
# Backwards compatible API with default value
def iteration(self, may_block=True):
- return super(MainContext, self).iteration(may_block)
+ with get_event_loop(self).paused():
+ return super(MainContext, self).iteration(may_block)
MainContext = override(MainContext)
@@ -769,9 +770,6 @@ def __next__(self):
return buf
raise StopIteration
- # Python 2.x compatibility
- next = __next__
-
IOChannel = override(IOChannel)
__all__.append('IOChannel')
diff --git a/gi/overrides/GObject.py b/gi/overrides/GObject.py
index 823c0b0..0500b09 100644
--- a/gi/overrides/GObject.py
+++ b/gi/overrides/GObject.py
@@ -180,13 +180,11 @@
GInterface = _gi.GInterface
GObject = _gi.GObject
GObjectWeakRef = _gi.GObjectWeakRef
-GParamSpec = _gi.GParamSpec
GPointer = _gi.GPointer
GType = _gi.GType
Warning = _gi.Warning
__all__ += ['GBoxed', 'GEnum', 'GFlags', 'GInterface', 'GObject',
- 'GObjectWeakRef', 'GParamSpec', 'GPointer', 'GType',
- 'Warning']
+ 'GObjectWeakRef', 'GPointer', 'GType', 'Warning']
features = {'generic-c-marshaller': True}
@@ -667,3 +665,28 @@ def unbind(self):
property = Property
deprecated_attr("GObject", "property", "GObject.Property")
__all__ += ['Property', 'Signal', 'SignalOverride', 'property']
+
+
+@override
+class ParamSpec(GObjectModule.ParamSpec):
+
+ @property
+ def nick(self):
+ return self._nick
+
+ @nick.setter
+ def nick(self, nick):
+ self._nick = nick
+
+ @property
+ def blurb(self):
+ return self._blurb
+
+ @blurb.setter
+ def blurb(self, blurb):
+ self._blurb = blurb
+
+
+GParamSpec = ParamSpec
+deprecated_attr("GObject", "GParamSpec", "GObject.ParamSpec")
+__all__ += ["ParamSpec", "GParamSpec"]
diff --git a/gi/overrides/Gdk.py b/gi/overrides/Gdk.py
index 73f309f..73842aa 100644
--- a/gi/overrides/Gdk.py
+++ b/gi/overrides/Gdk.py
@@ -27,7 +27,6 @@
from gi import PyGIDeprecationWarning, require_version
Gdk = get_introspection_module('Gdk')
-GDK2 = Gdk._version == '2.0'
GDK3 = Gdk._version == '3.0'
GDK4 = Gdk._version == '4.0'
@@ -42,7 +41,7 @@
except (ValueError, ImportError):
pass
-if GDK2 or GDK3:
+if GDK3:
# Gdk.Color was deprecated since 3.14 and dropped in Gtk-4.0
class Color(Gdk.Color):
MAX_VALUE = 65535
@@ -138,22 +137,7 @@ def from_color(cls, color):
RGBA = override(RGBA)
__all__.append('RGBA')
-if GDK2:
- class Rectangle(Gdk.Rectangle):
-
- def __init__(self, x, y, width, height):
- Gdk.Rectangle.__init__(self)
- self.x = x
- self.y = y
- self.width = width
- self.height = height
-
- def __repr__(self):
- return 'Gdk.Rectangle(x=%d, y=%d, width=%d, height=%d)' % (self.x, self.y, self.height, self.width)
-
- Rectangle = override(Rectangle)
- __all__.append('Rectangle')
-elif GDK3:
+if GDK3:
# Newer GTK/gobject-introspection (3.17.x) include GdkRectangle in the
# typelib. See https://bugzilla.gnome.org/show_bug.cgi?id=748832 and
# https://bugzilla.gnome.org/show_bug.cgi?id=748833
@@ -171,14 +155,7 @@ def __repr__(self):
__all__.append('rectangle_intersect')
__all__.append('rectangle_union')
-if GDK2:
- class Drawable(Gdk.Drawable):
- def cairo_create(self):
- return Gdk.cairo_create(self)
-
- Drawable = override(Drawable)
- __all__.append('Drawable')
-elif GDK3:
+if GDK3:
class Window(Gdk.Window):
def __new__(cls, parent, attributes, attributes_mask):
# Gdk.Window had to be made abstract,
@@ -194,7 +171,7 @@ def cairo_create(self):
Window = override(Window)
__all__.append('Window')
-if GDK2 or GDK3:
+if GDK3:
Gdk.EventType._2BUTTON_PRESS = getattr(Gdk.EventType, "2BUTTON_PRESS")
Gdk.EventType._3BUTTON_PRESS = getattr(Gdk.EventType, "3BUTTON_PRESS")
@@ -233,9 +210,6 @@ class Event(Gdk.Event):
Gdk.EventType.UNMAP: 'any',
}
- if GDK2:
- _UNION_MEMBERS[Gdk.EventType.NO_EXPOSE] = 'no_expose'
-
if hasattr(Gdk.EventType, 'TOUCH_BEGIN'):
_UNION_MEMBERS.update(
{
@@ -293,9 +267,6 @@ def __repr__(self):
'EventWindowState',
'EventVisibility']
- if GDK2:
- event_member_classes.append('EventNoExpose')
-
if hasattr(Gdk, 'EventTouch'):
event_member_classes.append('EventTouch')
@@ -357,17 +328,6 @@ def __new__(cls, *args, **kwds):
PyGIDeprecationWarning)
return cls.new_from_pixbuf(*args, **kwds)
- elif total_len == 6:
- if not GDK2:
- # pixmaps don't exist in Gdk 3.0
- raise ValueError("Wrong number of parameters")
-
- warnings.warn('Calling "Gdk.Cursor(source, mask, fg, bg, x, y)" has been deprecated. '
- 'Please use Gdk.Cursor.new_from_pixmap(source, mask, fg, bg, x, y). '
- 'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations',
- PyGIDeprecationWarning)
- return cls.new_from_pixmap(*args, **kwds)
-
else:
raise ValueError("Wrong number of parameters")
@@ -479,6 +439,6 @@ def __getitem__(self, index):
SELECTION_TYPE_STRING = Gdk.atom_intern('STRING', True)
__all__.append('SELECTION_TYPE_STRING')
-if GDK2 or GDK3:
+if GDK3:
import sys
initialized, argv = Gdk.init_check(sys.argv)
diff --git a/gi/overrides/Gio.py b/gi/overrides/Gio.py
index c807fe0..48c3737 100644
--- a/gi/overrides/Gio.py
+++ b/gi/overrides/Gio.py
@@ -20,8 +20,8 @@
import warnings
-from .._ossighelper import wakeup_on_signal, register_sigint_fallback
-from ..overrides import override, deprecated_init, wrap_list_store_sort_func
+from .._ossighelper import register_sigint_fallback, get_event_loop
+from ..overrides import override, deprecated_init, wrap_list_store_equal_func, wrap_list_store_sort_func
from ..module import get_introspection_module
from gi import PyGIWarning
@@ -38,7 +38,7 @@ class Application(Gio.Application):
def run(self, *args, **kwargs):
with register_sigint_fallback(self.quit):
- with wakeup_on_signal():
+ with get_event_loop(GLib.MainContext.default()).running(self.quit):
return Gio.Application.run(self, *args, **kwargs)
@@ -89,6 +89,37 @@ class DBusArgInfo(Gio.DBusArgInfo):
__all__.append('DBusArgInfo')
+@override
+class DBusConnection(Gio.DBusConnection):
+ __init__ = _warn_init(Gio.DBusConnection)
+
+ def register_object(self,
+ object_path,
+ interface_info,
+ method_call_closure=None,
+ get_property_closure=None,
+ set_property_closure=None):
+ if method_call_closure is not None:
+ def wrapped_method_call_closure(connection, sender, object_path,
+ interface_name, method_name, parameters,
+ invocation):
+ method_call_closure(connection, sender, object_path,
+ interface_name, method_name, parameters,
+ invocation)
+ invocation._unref()
+ else:
+ wrapped_method_call_closure = None
+
+ return super().register_object(object_path,
+ interface_info,
+ wrapped_method_call_closure,
+ get_property_closure,
+ set_property_closure)
+
+
+__all__.append('DBusConnection')
+
+
@override
class DBusMethodInfo(Gio.DBusMethodInfo):
__init__ = _warn_init(Gio.DBusMethodInfo)
@@ -211,9 +242,6 @@ def __next__(self):
else:
raise StopIteration
- # python 2 compat for the iter protocol
- next = __next__
-
FileEnumerator = override(FileEnumerator)
__all__.append('FileEnumerator')
@@ -250,9 +278,6 @@ def __bool__(self):
# if the object isn't None
return True
- # alias for Python 2.x object protocol
- __nonzero__ = __bool__
-
def __getitem__(self, key):
# get_value() aborts the program on an unknown key
if key not in self:
@@ -545,6 +570,46 @@ def __setitem__(self, key, value):
else:
raise TypeError
+ def find_with_equal_func(self, item, equal_func, *user_data):
+ # find_with_equal_func() is not suited for language bindings,
+ # see: https://gitlab.gnome.org/GNOME/glib/-/issues/2447.
+ # Use find_with_equal_func_full() instead.
+ equal_func = wrap_list_store_equal_func(equal_func)
+ return self.find_with_equal_func_full(item, equal_func, *user_data)
+
ListStore = override(ListStore)
__all__.append('ListStore')
+
+
+class DataInputStream(Gio.DataInputStream):
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ line = self.read_line_utf8(None)[0]
+
+ if line is not None:
+ return line
+ else:
+ raise StopIteration
+
+
+DataInputStream = override(DataInputStream)
+__all__.append('DataInputStream')
+
+
+class File(Gio.File):
+
+ def __fspath__(self):
+ path = self.peek_path()
+ # A file isn't guaranteed to have a path associated and returning
+ # `None` here will result in a `TypeError` trying to subscribe to it.
+ if path is None or path == '':
+ raise TypeError('File has no associated path.')
+ return path
+
+
+File = override(File)
+__all__.append('File')
diff --git a/gi/overrides/Gtk.py b/gi/overrides/Gtk.py
index 75de843..1ab3aad 100644
--- a/gi/overrides/Gtk.py
+++ b/gi/overrides/Gtk.py
@@ -22,8 +22,8 @@
import sys
import warnings
-from gi.repository import GObject
-from .._ossighelper import wakeup_on_signal, register_sigint_fallback
+from gi.repository import GObject, GLib
+from .._ossighelper import register_sigint_fallback, get_event_loop
from .._gtktemplate import Template, _extract_handler_and_args
from ..overrides import (override, strip_boolean_result, deprecated_init,
wrap_list_store_sort_func)
@@ -160,9 +160,6 @@ def __iter__(self):
def __bool__(self):
return True
- # alias for Python 2.x object protocol
- __nonzero__ = __bool__
-
def child_get_property(self, child, property_name, value=None):
if value is None:
prop = self.find_child_property(property_name)
@@ -570,7 +567,7 @@ def __init__(self, *args, **kwargs):
def run(self, *args, **kwargs):
with register_sigint_fallback(self.destroy):
- with wakeup_on_signal():
+ with get_event_loop(GLib.MainContext.default()).running(self.destroy):
return Gtk.Dialog.run(self, *args, **kwargs)
action_area = property(lambda dialog: dialog.get_action_area())
@@ -804,10 +801,6 @@ def __len__(self):
def __bool__(self):
return True
- if GTK3:
- # alias for Python 2.x object protocol
- __nonzero__ = __bool__
-
def _getiter(self, key):
if isinstance(key, Gtk.TreeIter):
return key
@@ -1190,10 +1183,6 @@ def __next__(self):
self.iter = self.model.iter_next(self.iter)
return row
- if GTK3:
- # alias for Python 2.x object protocol
- next = __next__
-
def __iter__(self):
return self
@@ -1690,9 +1679,22 @@ def main_quit(*args):
@override(Gtk.main)
def main(*args, **kwargs):
with register_sigint_fallback(Gtk.main_quit):
- with wakeup_on_signal():
+ with get_event_loop(GLib.MainContext.default()).running(Gtk.main_quit):
return _Gtk_main(*args, **kwargs)
+ _Gtk_main_iteration = Gtk.main_iteration
+ _Gtk_main_iteration_do = Gtk.main_iteration_do
+
+ @override(Gtk.main_iteration)
+ def main_iteration():
+ with get_event_loop(GLib.MainContext.default()).paused():
+ return _Gtk_main_iteration()
+
+ @override(Gtk.main_iteration)
+ def main_iteration_do(blocking):
+ with get_event_loop(GLib.MainContext.default()).paused():
+ return _Gtk_main_iteration_do(blocking)
+
if GTK3:
stock_lookup = strip_boolean_result(Gtk.stock_lookup)
diff --git a/gi/overrides/__init__.py b/gi/overrides/__init__.py
index d8772d0..34ac5c3 100644
--- a/gi/overrides/__init__.py
+++ b/gi/overrides/__init__.py
@@ -345,3 +345,13 @@ def wrap(a, b, *user_data):
return func(a, b, *user_data)
return wrap
+
+
+def wrap_list_store_equal_func(func):
+
+ def wrap(a, b, *user_data):
+ a = pygobject_new_full(a, False)
+ b = pygobject_new_full(b, False)
+ return func(a, b, *user_data)
+
+ return wrap
diff --git a/gi/pygi-async.c b/gi/pygi-async.c
new file mode 100644
index 0000000..28823d3
--- /dev/null
+++ b/gi/pygi-async.c
@@ -0,0 +1,639 @@
+/* -*- Mode: C; c-basic-offset: 4 -*-
+ * vim: tabstop=4 shiftwidth=4 expandtab
+ *
+ * Copyright (C) 2015 Christoph Reiter
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see .
+ */
+
+#include
+#include
+#include
+#include "pygobject-object.h"
+#include "pygboxed.h"
+#include "pygi-async.h"
+#include "pygi-util.h"
+#include "pygi-info.h"
+#include "pygi-invoke.h"
+
+
+static PyObject *asyncio_InvalidStateError;
+static PyObject *asyncio_get_running_loop;
+#if defined(PYPY_VERSION)
+static PyObject *contextvars_copy_context;
+#endif
+static PyObject *cancellable_info;
+
+/* This is never instantiated. */
+PYGI_DEFINE_TYPE ("gi._gi.Async", PyGIAsync_Type, PyGIAsync)
+
+/**
+ * Async.__repr__() implementation.
+ * Takes the _Async.__repr_format format string and applies the finish function
+ * info to it.
+ */
+static PyObject*
+async_repr(PyGIAsync *self) {
+ PyObject *string;
+ char *func_descr;
+
+ func_descr = _pygi_g_base_info_get_fullname (self->finish_func->base.info);
+
+ string = PyUnicode_FromFormat ("%s(finish_func=%s, done=%s)",
+ Py_TYPE(self)->tp_name,
+ func_descr,
+ (self->result || self->exception) ? "True" : "False");
+
+ g_free (func_descr);
+
+ return string;
+}
+
+/**
+ * async_cancel:
+ *
+ * Cancel the asynchronous operation.
+ */
+static PyObject *
+async_cancel(PyGIAsync *self) {
+
+ return PyObject_CallMethod (self->cancellable, "cancel", NULL);
+}
+
+static PyObject *
+async_done(PyGIAsync *self) {
+
+ return PyBool_FromLong (self->result || self->exception);
+}
+
+static PyObject *
+async_result(PyGIAsync *self) {
+
+ if (!self->result && !self->exception) {
+ PyErr_SetString(asyncio_InvalidStateError, "Async task is still running!");
+ return NULL;
+ }
+
+ self->log_tb = FALSE;
+
+ if (self->result) {
+ Py_INCREF (self->result);
+ return self->result;
+ } else {
+ PyErr_SetObject(PyExceptionInstance_Class(self->exception), self->exception);
+ return NULL;
+ }
+}
+
+static PyObject *
+async_exception(PyGIAsync *self) {
+
+ PyObject *res;
+
+ if (!self->result && !self->exception) {
+ PyErr_SetString(asyncio_InvalidStateError, "Async task is still running!");
+ return NULL;
+ }
+
+ if (self->exception)
+ res =self->exception;
+ else
+ res = Py_None;
+
+ self->log_tb = FALSE;
+
+ Py_INCREF (res);
+ return res;
+}
+
+static PyObject*
+call_soon (PyGIAsync *self, PyGIAsyncCallback *cb)
+{
+ PyObject *call_soon;
+ PyObject *args, *kwargs = NULL;
+ PyObject *ret;
+
+ call_soon = PyObject_GetAttrString(self->loop, "call_soon");
+ if (!call_soon)
+ return NULL;
+
+ args = Py_BuildValue ("(OO)", cb->func, self);
+ kwargs = PyDict_New ();
+ PyDict_SetItemString (kwargs, "context", cb->context);
+ ret = PyObject_Call (call_soon, args, kwargs);
+
+ Py_CLEAR (args);
+ Py_CLEAR (kwargs);
+ Py_CLEAR (call_soon);
+
+ return ret;
+}
+
+static PyObject*
+async_add_done_callback (PyGIAsync *self, PyObject *args, PyObject *kwargs)
+{
+ PyGIAsyncCallback callback = { NULL };
+
+ static char * kwlist[] = {"", "context", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|$O:add_done_callback", kwlist,
+ &callback.func, &callback.context))
+ return NULL;
+
+ Py_INCREF(callback.func);
+ if (callback.context == NULL)
+#ifndef PYPY_VERSION
+ callback.context = PyContext_CopyCurrent ();
+#else
+ callback.context = PyObject_CallObject (contextvars_copy_context, NULL);
+#endif
+ else
+ Py_INCREF(callback.context);
+
+ /* Note that we don't need to copy the current context in this case. */
+ if (self->result || self->exception) {
+ PyObject *res = call_soon (self, &callback);
+
+ Py_DECREF(callback.func);
+ Py_DECREF(callback.context);
+ if (res) {
+ Py_DECREF(res);
+ Py_RETURN_NONE;
+ } else {
+ return NULL;
+ }
+ }
+
+ if (!self->callbacks)
+ self->callbacks = g_array_new (TRUE, TRUE, sizeof (PyGIAsyncCallback));
+
+ g_array_append_val (self->callbacks, callback);
+
+ Py_RETURN_NONE;
+}
+
+static PyObject*
+async_remove_done_callback (PyGIAsync *self, PyObject *fn)
+{
+ guint i = 0;
+ gssize removed = 0;
+
+ while (self->callbacks && i < self->callbacks->len) {
+ PyGIAsyncCallback *cb = &g_array_index (self->callbacks, PyGIAsyncCallback, i);
+
+ if (PyObject_RichCompareBool (cb->func, fn, Py_EQ) == 1) {
+ Py_DECREF(cb->func);
+ Py_DECREF(cb->context);
+
+ removed += 1;
+ g_array_remove_index (self->callbacks, i);
+ } else {
+ i += 1;
+ }
+ }
+
+ return PyLong_FromSsize_t(removed);
+}
+
+static int
+async_init(PyGIAsync *self, PyObject *args, PyObject *kwargs)
+{
+ static char *kwlist[] = { "finish_func", "cancellable", NULL };
+ PyObject *context = NULL;
+ GMainContext *ctx = NULL;
+ int ret = -1;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!|O!$:gi._gi.Async.__init__", kwlist,
+ &PyGICallableInfo_Type, &self->finish_func,
+ &PyGObject_Type, &self->cancellable))
+ goto out;
+
+ Py_INCREF(self->finish_func);
+
+ /* We need to pull in Gio.Cancellable at some point, but we delay it
+ * until really needed to avoid having a dependency.
+ */
+ if (G_UNLIKELY (!cancellable_info)) {
+ PyObject *gio;
+
+ gio = PyImport_ImportModule("gi.repository.Gio");
+ if (gio == NULL)
+ goto out;
+
+ cancellable_info = PyObject_GetAttrString(gio, "Cancellable");
+ Py_DECREF(gio);
+
+ if (!cancellable_info)
+ goto out;
+ }
+
+ if (self->cancellable) {
+ int res;
+
+ Py_INCREF (self->cancellable);
+
+ res = PyObject_IsInstance (self->cancellable, cancellable_info);
+ if (res == -1)
+ goto out;
+
+ if (res == 0) {
+ PyErr_SetString (PyExc_TypeError, "cancellable argument needs to be of type Gio.Cancellable");
+ goto out;
+ }
+ } else {
+ self->cancellable = PyObject_CallObject (cancellable_info, NULL);
+ }
+
+ self->loop = PyObject_CallObject (asyncio_get_running_loop, NULL);
+ if (!self->loop)
+ goto out;
+
+ /* We use g_main_context_ref_thread_default() here, as that is what GTask
+ * does. We then only allow creating an awaitable if python has a *running*
+ * EventLoop iterating this context (i.e. has it as its `_context` attr).
+ *
+ * NOTE: This is a bit backward. Instead, it would make more sense to just
+ * fetch the current EventLoop object for the ref'ed GMainContext.
+ * Python will then do the rest and ensure it is not awaited from the wrong
+ * EventLoop.
+ */
+ ctx = g_main_context_ref_thread_default ();
+ assert(ctx != NULL);
+
+ /* Duck-type the running loop. It needs to have a _context attribute. */
+ context = PyObject_GetAttrString (self->loop, "_context");
+ if (context == NULL)
+ goto out;
+
+ if (!pyg_boxed_check (context, G_TYPE_MAIN_CONTEXT) ||
+ pyg_boxed_get_ptr (context) != ctx) {
+ PyErr_SetString (PyExc_TypeError, "Running EventLoop is iterating a different GMainContext");
+ goto out;
+ }
+
+ /* Success! */
+ ret = 0;
+
+out:
+ g_main_context_unref (ctx);
+ Py_XDECREF (context);
+
+ return ret;
+}
+
+static PyMethodDef async_methods[] = {
+ {"cancel", (PyCFunction)async_cancel, METH_NOARGS},
+ {"done", (PyCFunction)async_done, METH_NOARGS},
+ {"result", (PyCFunction)async_result, METH_NOARGS},
+ {"exception", (PyCFunction)async_exception, METH_NOARGS},
+ {"add_done_callback", (PyCFunction)async_add_done_callback, METH_VARARGS | METH_KEYWORDS},
+ {"remove_done_callback", (PyCFunction)async_remove_done_callback, METH_O},
+ {NULL, NULL, 0},
+};
+
+static PyObject *
+async_await (PyGIAsync *self) {
+ /* We return ourselves as iterator. This is legal in principle, but we
+ * don't stop iterating after one item and just continue indefinately,
+ * meaning that certain errors cannot be caught!
+ */
+
+ if (!self->result && !self->exception)
+ self->_asyncio_future_blocking = TRUE;
+
+ Py_INCREF (self);
+ return (PyObject *) self;
+}
+
+static PyObject *
+async_iternext (PyGIAsync *self) {
+ /* Return ourselves if iteration needs to continue. */
+ if (!self->result && !self->exception) {
+ Py_INCREF (self);
+ return (PyObject *) self;
+ }
+
+ if (self->exception) {
+ PyErr_SetObject(PyExceptionInstance_Class(self->exception), self->exception);
+ return NULL;
+ } else {
+ PyObject *e;
+
+ e = PyObject_CallFunctionObjArgs(PyExc_StopIteration, self->result, NULL);
+ if (e == NULL)
+ return NULL;
+
+ PyErr_SetObject(PyExc_StopIteration, e);
+ Py_DECREF(e);
+ return NULL;
+ }
+}
+
+static PyAsyncMethods async_async_methods = {
+ .am_await = (unaryfunc) async_await,
+};
+
+static void
+async_finalize(PyGIAsync *self)
+{
+ PyObject *error_type, *error_value, *error_traceback;
+ PyObject *context = NULL;
+ PyObject *message = NULL;
+ PyObject *call_exception_handler = NULL;
+ PyObject *res = NULL;
+
+ if (!self->log_tb)
+ return;
+
+ assert(self->exception != NULL);
+ self->log_tb = 0;
+
+ /* Save the current exception, if any. */
+ PyErr_Fetch(&error_type, &error_value, &error_traceback);
+
+ context = PyDict_New();
+ if (context == NULL) {
+ goto finally;
+ }
+
+ message = PyUnicode_FromFormat(
+ "%s exception was never retrieved", Py_TYPE(self)->tp_name);
+ if (message == NULL)
+ goto finally;
+
+ if (PyDict_SetItemString(context, "message", message) < 0 ||
+ PyDict_SetItemString(context, "exception", self->exception) < 0 ||
+ PyDict_SetItemString(context, "future", (PyObject*) self) < 0)
+ goto finally;
+
+ call_exception_handler = PyObject_GetAttrString(self->loop, "call_exception_handler");
+ if (!call_exception_handler)
+ goto finally;
+
+ res = PyObject_CallFunction(call_exception_handler, "(O)", context);
+ if (res == NULL)
+ PyErr_WriteUnraisable(context);
+
+finally:
+ Py_CLEAR (res);
+ Py_CLEAR (context);
+ Py_CLEAR (message);
+ Py_CLEAR (call_exception_handler);
+
+ Py_CLEAR(self->loop);
+ Py_CLEAR(self->finish_func);
+ if (self->cancellable)
+ Py_CLEAR(self->cancellable);
+ if (self->result)
+ Py_CLEAR(self->result);
+ if (self->exception)
+ Py_CLEAR(self->exception);
+
+ /* Precation, cannot happen */
+ if (self->callbacks)
+ g_array_free (self->callbacks, TRUE);
+
+ /* Restore the saved exception. */
+ PyErr_Restore(error_type, error_value, error_traceback);
+}
+
+static void
+async_dealloc(PyGIAsync *self)
+{
+#ifndef PYPY_VERSION
+ /* The finalizer might resurrect the object */
+ if (PyObject_CallFinalizerFromDealloc((PyObject *)self) < 0)
+ return;
+#endif
+
+ Py_TYPE(self)->tp_free((PyObject *)self);
+}
+
+void
+pygi_async_finish_cb (GObject *source_object, gpointer res, PyGIAsync *self)
+{
+ PyGILState_STATE py_state;
+ PyObject *source_pyobj, *res_pyobj, *args;
+ PyObject *ret;
+ guint i;
+
+ /* Lock the GIL as we are coming into this code without the lock and we
+ may be executing python code */
+ py_state = PyGILState_Ensure ();
+
+ /* We might still be called at shutdown time. */
+ if (!Py_IsInitialized()) {
+ PyGILState_Release (py_state);
+ return;
+ }
+
+ res_pyobj = pygobject_new_full (res, FALSE, NULL);
+ if (source_object) {
+ source_pyobj = pygobject_new_full (source_object, FALSE, NULL);
+ args = Py_BuildValue ("(OO)", source_pyobj, res_pyobj);
+ } else {
+ source_pyobj = NULL;
+ args = Py_BuildValue ("(O)", res_pyobj);
+ }
+ ret = _wrap_g_callable_info_invoke ((PyGIBaseInfo *) self->finish_func, args, NULL);
+ Py_XDECREF (res_pyobj);
+ Py_XDECREF (source_pyobj);
+ Py_XDECREF (args);
+
+ if (PyErr_Occurred ()) {
+ PyObject *exc = NULL, *value = NULL, *traceback = NULL;
+
+ /* NOTE: cPython >=3.12 has PyErr_{Get,Set}RaisedException */
+ PyErr_Fetch (&exc, &value, &traceback);
+ PyErr_NormalizeException(&exc, &value, &traceback);
+
+ self->exception = value;
+ self->log_tb = TRUE;
+
+ Py_XDECREF (exc);
+ Py_XDECREF (traceback);
+ Py_XDECREF (ret);
+ } else {
+ self->result = ret;
+ }
+
+ for (i = 0; self->callbacks && i < self->callbacks->len; i++) {
+ PyGIAsyncCallback *cb = &g_array_index (self->callbacks, PyGIAsyncCallback, i);
+ /* We stop calling anything after the first exception, but still clear
+ * the internal state as if we did.
+ * This matches the pure python implementation of Future.
+ */
+ if (!PyErr_Occurred ()) {
+ ret = call_soon (self, cb);
+ if (!ret)
+ PyErr_PrintEx (FALSE);
+ else
+ Py_DECREF(ret);
+ }
+
+ Py_DECREF(cb->func);
+ Py_DECREF(cb->context);
+ }
+ if (self->callbacks)
+ g_array_free(self->callbacks, TRUE);
+ self->callbacks = NULL;
+
+ Py_DECREF(self);
+ PyGILState_Release (py_state);
+}
+
+/**
+ * pygi_async_new:
+ * @finish_func: A #GIFunctionInfo to wrap that is used to finish.
+ * @cancellable: A #PyObject containging a #GCancellable, or None
+ *
+ * Return a new async instance.
+ *
+ * Returns: An instance of gi.Async or %NULL on error.
+ */
+PyObject *
+pygi_async_new(PyObject *finish_func, PyObject *cancellable) {
+
+ PyObject *res;
+ PyObject *args;
+
+ res = PyGIAsync_Type.tp_alloc (&PyGIAsync_Type, 0);
+
+ if (res) {
+ if (cancellable && cancellable != Py_None)
+ args = Py_BuildValue ("(OO)", finish_func, cancellable);
+ else
+ args = Py_BuildValue ("(O)", finish_func);
+
+ if (PyGIAsync_Type.tp_init (res, args, NULL) < 0) {
+ Py_DECREF (args);
+ Py_DECREF (res);
+
+ /* Ignore exception from object initializer */
+ PyErr_Clear ();
+
+ return NULL;
+ }
+
+ Py_DECREF(args);
+ }
+
+ return res;
+}
+
+static struct PyMemberDef async_members[] = {
+ {
+ "_asyncio_future_blocking",
+ T_BOOL,
+ offsetof(PyGIAsync, _asyncio_future_blocking),
+ 0,
+ NULL
+ },
+ {
+ "_loop",
+ T_OBJECT,
+ offsetof(PyGIAsync, loop),
+ READONLY,
+ NULL
+ },
+ {
+ "_finish_func",
+ T_OBJECT,
+ offsetof(PyGIAsync, finish_func),
+ READONLY,
+ NULL
+ },
+ {
+ "cancellable",
+ T_OBJECT,
+ offsetof(PyGIAsync, cancellable),
+ READONLY,
+ "The Gio.Cancellable associated with the task."
+ },
+ { NULL, }
+};
+
+
+/**
+ * pygi_async_register_types:
+ * @module: A Python modules to which Async gets added to.
+ *
+ * Initializes the Async class and adds it to the passed @module.
+ *
+ * Returns: -1 on error, 0 on success.
+ */
+int pygi_async_register_types(PyObject *module) {
+ PyObject *asyncio = NULL;
+#ifdef PYPY_VERSION
+ PyObject *contextvars = NULL;
+#endif
+
+#ifndef PYPY_VERSION
+ PyGIAsync_Type.tp_finalize = (destructor)async_finalize;
+#else
+ PyGIAsync_Type.tp_del = (destructor)async_finalize;
+#endif
+ PyGIAsync_Type.tp_dealloc = (destructor)async_dealloc;
+ PyGIAsync_Type.tp_repr = (reprfunc)async_repr;
+ PyGIAsync_Type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_FINALIZE;
+ PyGIAsync_Type.tp_methods = async_methods;
+ PyGIAsync_Type.tp_members = async_members;
+ PyGIAsync_Type.tp_as_async = &async_async_methods;
+ PyGIAsync_Type.tp_iternext = (iternextfunc) &async_iternext;
+ PyGIAsync_Type.tp_init = (initproc)async_init;
+ PyGIAsync_Type.tp_new = PyType_GenericNew;
+
+ if (PyType_Ready (&PyGIAsync_Type) < 0)
+ return -1;
+
+ Py_INCREF (&PyGIAsync_Type);
+ if (PyModule_AddObject (module, "Async",
+ (PyObject *)&PyGIAsync_Type) < 0) {
+ Py_DECREF (&PyGIAsync_Type);
+ return -1;
+ }
+
+ asyncio = PyImport_ImportModule("asyncio");
+ if (asyncio == NULL) {
+ goto fail;
+ }
+ asyncio_InvalidStateError = PyObject_GetAttrString(asyncio, "InvalidStateError");
+ if (asyncio_InvalidStateError == NULL)
+ goto fail;
+
+ asyncio_get_running_loop = PyObject_GetAttrString(asyncio, "_get_running_loop");
+ if (asyncio_get_running_loop == NULL)
+ goto fail;
+
+#if defined(PYPY_VERSION)
+ contextvars = PyImport_ImportModule("contextvars");
+ if (asyncio == NULL) {
+ goto fail;
+ }
+
+ contextvars_copy_context = PyObject_GetAttrString(contextvars, "copy_context");
+ if (contextvars_copy_context == NULL)
+ goto fail;
+#endif
+
+ /* Only initialized when really needed! */
+ cancellable_info = NULL;
+
+ Py_CLEAR(asyncio);
+ return 0;
+
+fail:
+ Py_CLEAR(asyncio);
+ return -1;
+}
diff --git a/gi/pygi-async.h b/gi/pygi-async.h
new file mode 100644
index 0000000..d5e7a92
--- /dev/null
+++ b/gi/pygi-async.h
@@ -0,0 +1,59 @@
+/* -*- Mode: C; c-basic-offset: 4 -*-
+ * vim: tabstop=4 shiftwidth=4 expandtab
+ *
+ * Copyright (C) 2015 Christoph Reiter
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see .
+ */
+
+#ifndef __PYGI_ASYNC_H__
+#define __PYGI_ASYNC_H__
+
+#include "Python.h"
+
+#include "pygi-info.h"
+#include "pygi-cache.h"
+
+typedef struct {
+ PyObject *func;
+ PyObject *context;
+} PyGIAsyncCallback;
+
+typedef struct {
+ PyObject_HEAD
+
+ /* Everything for the instance, finish_func is kept in the class. */
+ PyGICallableInfo *finish_func;
+ PyObject *loop;
+ PyObject *cancellable;
+ int _asyncio_future_blocking;
+ PyObject *result;
+ PyObject *exception;
+
+ gboolean log_tb;
+
+ GArray *callbacks;
+} PyGIAsync;
+
+
+int
+pygi_async_register_types (PyObject *d);
+
+void
+pygi_async_finish_cb (GObject *source_object, gpointer res, PyGIAsync *async);
+
+PyObject*
+pygi_async_new (PyObject *async_finish, PyObject *cancellable);
+
+#endif /* __PYGI_ASYNCRESULT_H__ */
diff --git a/gi/pygi-cache.c b/gi/pygi-cache.c
index c6630de..500b648 100644
--- a/gi/pygi-cache.c
+++ b/gi/pygi-cache.c
@@ -172,6 +172,11 @@ pygi_arg_interface_setup (PyGIInterfaceCache *iface_cache,
iface_cache->g_type = g_registered_type_info_get_g_type ( (GIRegisteredTypeInfo *)iface_info);
iface_cache->py_type = pygi_type_import_by_gi_info ( (GIBaseInfo *) iface_info);
+ if (g_type_is_a (iface_cache->g_type, G_TYPE_OBJECT)) {
+ if (g_str_equal (g_type_name (iface_cache->g_type), "GCancellable"))
+ iface_cache->arg_cache.async_context = PYGI_ASYNC_CONTEXT_CANCELLABLE;
+ }
+
if (iface_cache->py_type == NULL) {
return FALSE;
}
@@ -787,8 +792,11 @@ _function_cache_invoke_real (PyGIFunctionCache *function_cache,
static void
_function_cache_deinit_real (PyGICallableCache *callable_cache)
{
+ PyGIFunctionCache *function_cache = (PyGIFunctionCache *) callable_cache;
g_function_invoker_destroy (&((PyGIFunctionCache *) callable_cache)->invoker);
+ Py_CLEAR (function_cache->async_finish);
+
_callable_cache_deinit_real (callable_cache);
}
@@ -799,6 +807,7 @@ _function_cache_init (PyGIFunctionCache *function_cache,
PyGICallableCache *callable_cache = (PyGICallableCache *) function_cache;
GIFunctionInvoker *invoker = &function_cache->invoker;
GError *error = NULL;
+ guint i;
callable_cache->calling_context = PYGI_CALLING_CONTEXT_IS_FROM_PY;
@@ -811,6 +820,76 @@ _function_cache_init (PyGIFunctionCache *function_cache,
if (!_callable_cache_init (callable_cache, callable_info))
return FALSE;
+ /* Check if this function is an async routine that is capable of returning
+ * an async awaitable object.
+ */
+ if (!callable_cache->has_return && callable_cache->n_to_py_args == 0) {
+ PyGIArgCache *cancellable = NULL;
+ PyGIArgCache *async_callback = NULL;
+
+ for (i = 0; i < _pygi_callable_cache_args_len (callable_cache); i++) {
+ PyGIArgCache *arg_cache = _pygi_callable_cache_get_arg (callable_cache, i);
+
+ /* Ignore any out or in/out parameters. */
+ if (arg_cache->async_context == PYGI_ASYNC_CONTEXT_CALLBACK) {
+ if (async_callback) {
+ async_callback = NULL;
+ break;
+ }
+ async_callback = arg_cache;
+ } else if (arg_cache->async_context == PYGI_ASYNC_CONTEXT_CANCELLABLE) {
+ if (cancellable) {
+ cancellable = NULL;
+ break;
+ }
+ cancellable = arg_cache;
+ }
+ }
+
+ if (cancellable && async_callback) {
+ GIBaseInfo *container = g_base_info_get_container ((GIBaseInfo*) callable_info);
+ GIBaseInfo *async_finish = NULL;
+ gint name_len;
+ gchar *finish_name = NULL;
+
+ /* This appears to be an async routine. As we have the
+ * GCallableInfo at this point, so guess the finish name and look
+ * up that information.
+ */
+ name_len = strlen (callable_cache->name);
+ if (g_str_has_suffix (callable_cache->name, "_async"))
+ name_len -= 6;
+
+ /* Original name without _async if it is there, _finish + NUL byte */
+ finish_name = g_malloc0 (name_len + 7 + 1);
+ strncat (finish_name, callable_cache->name, name_len);
+ strcat (finish_name, "_finish");
+
+ if (container && g_base_info_get_type (container) == GI_INFO_TYPE_OBJECT) {
+ async_finish = g_object_info_find_method ((GIObjectInfo *) container, finish_name);
+ } else if (container && g_base_info_get_type (container) == GI_INFO_TYPE_INTERFACE) {
+ async_finish = g_interface_info_find_method ((GIInterfaceInfo *) container, finish_name);
+ } else if (!container) {
+ async_finish = g_irepository_find_by_name (NULL,
+ callable_cache->namespace,
+ finish_name);
+ } else {
+ g_debug ("Awaitable async functions only work on GObjects and as toplevel functions.");
+ }
+
+ if (async_finish && g_base_info_get_type (async_finish)) {
+ function_cache->async_finish = _pygi_info_new ((GIBaseInfo *) async_finish);
+ function_cache->async_cancellable = cancellable;
+ function_cache->async_callback = async_callback;
+ }
+
+ if (async_finish)
+ g_base_info_unref (async_finish);
+
+ g_free (finish_name);
+ }
+ }
+
/* Set by PyGICCallbackCache and PyGIVFuncCache */
if (invoker->native_address == NULL) {
if (g_function_info_prep_invoker ((GIFunctionInfo *) callable_info,
diff --git a/gi/pygi-cache.h b/gi/pygi-cache.h
index fc5a616..252c96a 100644
--- a/gi/pygi-cache.h
+++ b/gi/pygi-cache.h
@@ -104,12 +104,18 @@ typedef enum {
PYGI_CALLING_CONTEXT_IS_FROM_PY
} PyGICallingContext;
+typedef enum {
+ PYGI_ASYNC_CONTEXT_NONE = 0,
+ PYGI_ASYNC_CONTEXT_CALLBACK,
+ PYGI_ASYNC_CONTEXT_CANCELLABLE,
+} PyGIAsyncContext;
struct _PyGIArgCache
{
const gchar *arg_name;
PyGIMetaArgType meta_type;
+ PyGIAsyncContext async_context;
gboolean is_pointer;
gboolean is_caller_allocates;
gboolean is_skipped;
@@ -218,6 +224,11 @@ struct _PyGICallableCache
struct _PyGIFunctionCache {
PyGICallableCache callable_cache;
+ /* Information about async functions. */
+ PyObject *async_finish;
+ PyGIArgCache *async_callback;
+ PyGIArgCache *async_cancellable;
+
/* An invoker with ffi_cif already setup */
GIFunctionInvoker invoker;
diff --git a/gi/pygi-closure.c b/gi/pygi-closure.c
index 4e19c5e..de1e656 100644
--- a/gi/pygi-closure.c
+++ b/gi/pygi-closure.c
@@ -23,6 +23,7 @@
#include "pygi-invoke.h"
#include "pygi-ccallback.h"
#include "pygi-info.h"
+#include "pygi-async.h"
extern PyObject *_PyGIDefaultArgPlaceholder;
@@ -720,6 +721,23 @@ _pygi_marshal_from_py_interface_callback (PyGIInvokeState *state,
callback_cache = (PyGICallbackCache *)arg_cache;
+ if (py_arg == _PyGIDefaultArgPlaceholder) {
+ /* We need to have an async to "marshal" instead in this case. */
+ if (!state->py_async)
+ return FALSE;
+
+ if (callback_cache->user_data_index <= 0)
+ return FALSE;
+
+ user_data_cache = _pygi_callable_cache_get_arg (callable_cache, (guint)callback_cache->user_data_index);
+
+ Py_INCREF (state->py_async);
+ arg->v_pointer = pygi_async_finish_cb;
+ state->args[user_data_cache->c_arg_index].arg_value.v_pointer = state->py_async;
+
+ return TRUE;
+ }
+
if (callback_cache->user_data_index > 0) {
user_data_cache = _pygi_callable_cache_get_arg (callable_cache, (guint)callback_cache->user_data_index);
if (user_data_cache->py_arg_index < state->n_py_in_args) {
@@ -937,6 +955,9 @@ pygi_arg_callback_setup_from_info (PyGICallbackCache *arg_cache,
arg_cache->closure_cache = pygi_closure_cache_new (arg_cache->interface_info);
cache->from_py_marshaller = _pygi_marshal_from_py_interface_callback;
cache->from_py_cleanup = _pygi_marshal_cleanup_from_py_interface_callback;
+
+ if (arg_cache->scope == GI_SCOPE_TYPE_ASYNC)
+ arg_cache->arg_cache.async_context = PYGI_ASYNC_CONTEXT_CALLBACK;
}
if (direction & PYGI_DIRECTION_TO_PYTHON) {
diff --git a/gi/pygi-fundamental.c b/gi/pygi-fundamental.c
index 374b86a..e938067 100644
--- a/gi/pygi-fundamental.c
+++ b/gi/pygi-fundamental.c
@@ -45,7 +45,8 @@ fundamental_dealloc (PyGIFundamental *self)
self->instance = NULL;
PyObject_GC_UnTrack ((PyObject *) self);
- PyObject_ClearWeakRefs ((PyObject *) self);
+ if (self->weaklist)
+ PyObject_ClearWeakRefs ((PyObject *) self);
Py_TYPE (self)->tp_free ((PyObject *) self);
}
@@ -191,6 +192,13 @@ _pygi_fundamental_new_internal (PyTypeObject *type,
self->ref_func = g_object_info_get_ref_function_pointer (info);
self->unref_func = g_object_info_get_unref_function_pointer (info);
+ /* A special case for GParamSpec. It has a floating reference when created.
+ * We make sure we have a proper reference, so we can ref/unref normally.
+ */
+ if (G_TYPE_IS_PARAM (self->gtype)) {
+ g_param_spec_ref_sink (self->instance);
+ }
+
g_base_info_unref (info);
return self;
@@ -235,6 +243,7 @@ pygi_fundamental_register_types (PyObject *m)
PyGIFundamental_Type.tp_richcompare = fundamental_richcompare;
PyGIFundamental_Type.tp_repr = (reprfunc) fundamental_repr;
PyGIFundamental_Type.tp_hash = (hashfunc) fundamental_hash;
+ PyGIFundamental_Type.tp_weaklistoffset = offsetof(PyGIFundamental, weaklist);
if (PyType_Ready (&PyGIFundamental_Type))
return -1;
diff --git a/gi/pygi-fundamental.h b/gi/pygi-fundamental.h
index cd3c942..b047fd4 100644
--- a/gi/pygi-fundamental.h
+++ b/gi/pygi-fundamental.h
@@ -37,6 +37,7 @@ extern PyTypeObject PyGIFundamental_Type;
typedef struct {
PyObject_HEAD
+ PyObject* weaklist;
gpointer instance;
GType gtype;
GIObjectInfoRefFunction ref_func;
@@ -49,7 +50,7 @@ PyObject* pygi_fundamental_new (gpointer instance);
void pygi_fundamental_ref (PyGIFundamental *self);
void pygi_fundamental_unref (PyGIFundamental *self);
-GTypeInstance* pygi_fundamental_get (PyObject *self);
+GTypeInstance* pygi_fundamental_get (PyObject *self);
int pygi_fundamental_register_types (PyObject *m);
diff --git a/gi/pygi-invoke-state-struct.h b/gi/pygi-invoke-state-struct.h
index dbf4e66..22969bb 100644
--- a/gi/pygi-invoke-state-struct.h
+++ b/gi/pygi-invoke-state-struct.h
@@ -56,6 +56,11 @@ typedef struct _PyGIInvokeState
gboolean failed;
+ /* An awaitable to return for an async function that was called with
+ * default arguments.
+ */
+ PyObject *py_async;
+
gpointer user_data;
/* Function pointer to call with ffi. */
diff --git a/gi/pygi-invoke.c b/gi/pygi-invoke.c
index 7b822e4..e457046 100644
--- a/gi/pygi-invoke.c
+++ b/gi/pygi-invoke.c
@@ -24,6 +24,7 @@
#include "pygi-marshal-cleanup.h"
#include "pygi-error.h"
#include "pygi-resulttuple.h"
+#include "pygi-async.h"
#include "pygi-foreign.h"
#include "pygi-boxed.h"
@@ -317,6 +318,7 @@ _invoke_state_clear (PyGIInvokeState *state, PyGIFunctionCache *function_cache)
{
_pygi_invoke_arg_state_free (state);
Py_XDECREF (state->py_in_args);
+ Py_XDECREF (state->py_async);
}
static gboolean
@@ -407,10 +409,28 @@ _invoke_marshal_in_args (PyGIInvokeState *state, PyGIFunctionCache *function_cac
return FALSE;
}
+ if (function_cache->async_finish && function_cache->async_callback &&
+ function_cache->async_callback->py_arg_index < state->n_py_in_args &&
+ PyTuple_GET_ITEM (state->py_in_args, function_cache->async_callback->py_arg_index) == _PyGIDefaultArgPlaceholder) {
+
+ /* We are dealing with an async call that returns an awaitable */
+ PyObject *cancellable = NULL;
+
+ /* Try to resolve any passed GCancellable. */
+ if (function_cache->async_cancellable && function_cache->async_cancellable->py_arg_index < state->n_py_in_args)
+ cancellable = PyTuple_GET_ITEM (state->py_in_args, function_cache->async_cancellable->py_arg_index);
+
+ if (cancellable == _PyGIDefaultArgPlaceholder)
+ cancellable = NULL;
+
+ state->py_async = pygi_async_new (function_cache->async_finish, cancellable);
+ }
+
for (i = 0; (gsize)i < _pygi_callable_cache_args_len (cache); i++) {
GIArgument *c_arg = &state->args[i].arg_value;
PyGIArgCache *arg_cache = g_ptr_array_index (cache->args_cache, i);
PyObject *py_arg = NULL;
+ gboolean marshal = TRUE;
switch (arg_cache->direction) {
case PYGI_DIRECTION_FROM_PYTHON:
@@ -510,9 +530,25 @@ _invoke_marshal_in_args (PyGIInvokeState *state, PyGIFunctionCache *function_cac
}
if (py_arg == _PyGIDefaultArgPlaceholder) {
- *c_arg = arg_cache->default_value;
- } else if (arg_cache->from_py_marshaller != NULL &&
- arg_cache->meta_type != PYGI_META_ARG_TYPE_CHILD) {
+ /* If this is the cancellable, then we may override it later if we
+ * detect an async call.
+ */
+ marshal = FALSE;
+
+ if (state->py_async && arg_cache->async_context == PYGI_ASYNC_CONTEXT_CANCELLABLE) {
+ marshal = TRUE;
+ py_arg = ((PyGIAsync*) state->py_async)->cancellable;
+ } else if (state->py_async && arg_cache->async_context == PYGI_ASYNC_CONTEXT_CALLBACK) {
+ marshal = TRUE;
+ } else {
+ *c_arg = arg_cache->default_value;
+ }
+ }
+
+ if (marshal &&
+ arg_cache->from_py_marshaller != NULL &&
+ arg_cache->meta_type != PYGI_META_ARG_TYPE_CHILD) {
+
gboolean success;
gpointer cleanup_data = NULL;
@@ -585,6 +621,17 @@ _invoke_marshal_out_args (PyGIInvokeState *state, PyGIFunctionCache *function_ca
}
}
+ /* Return the async future if we have one. */
+ if (state->py_async) {
+ /* We must have no return value */
+ g_assert (n_out_args == 0);
+ g_assert (cache->return_cache->is_skipped || cache->return_cache->type_tag == GI_TYPE_TAG_VOID);
+
+ Py_DECREF(py_return);
+ Py_INCREF(state->py_async);
+ return state->py_async;
+ }
+
if (n_out_args == 0) {
if (cache->return_cache->is_skipped && state->error == NULL) {
/* we skip the return value and have no (out) arguments to return,
diff --git a/gi/pygi-object.c b/gi/pygi-object.c
index 647c994..fc4268b 100644
--- a/gi/pygi-object.c
+++ b/gi/pygi-object.c
@@ -24,7 +24,6 @@
#include "pygi-object.h"
#include "pygi-fundamental.h"
#include "pygobject-object.h"
-#include "pygparamspec.h"
/*
* GObject from Python
@@ -240,12 +239,6 @@ pygi_arg_object_to_py (GIArgument *arg,
if (arg->v_pointer == NULL) {
pyobj = Py_None;
Py_INCREF (pyobj);
-
- } else if (G_IS_PARAM_SPEC(arg->v_pointer)) {
- pyobj = pyg_param_spec_new (arg->v_pointer);
- if (transfer == GI_TRANSFER_EVERYTHING)
- g_param_spec_unref (arg->v_pointer);
-
} else if (G_IS_OBJECT(arg->v_pointer)) {
pyobj = pygobject_new_full (arg->v_pointer,
/*steal=*/ transfer == GI_TRANSFER_EVERYTHING,
diff --git a/gi/pygi-property.c b/gi/pygi-property.c
index 4abaf04..7180c15 100644
--- a/gi/pygi-property.c
+++ b/gi/pygi-property.c
@@ -25,8 +25,8 @@
#include "pygi-value.h"
#include "pygi-argument.h"
#include "pygi-fundamental.h"
-#include "pygparamspec.h"
#include "pygi-type.h"
+#include "pygi-fundamental.h"
#include
@@ -106,7 +106,7 @@ pygi_call_do_get_property (PyObject *instance, GParamSpec *pspec)
PyObject *py_pspec;
PyObject *retval;
- py_pspec = pyg_param_spec_new (pspec);
+ py_pspec = pygi_fundamental_new (pspec);
retval = PyObject_CallMethod (instance, "do_get_property", "O", py_pspec);
Py_DECREF (py_pspec);
return retval;
diff --git a/gi/pygi-type.c b/gi/pygi-type.c
index 619c6a2..2aec76f 100644
--- a/gi/pygi-type.c
+++ b/gi/pygi-type.c
@@ -22,7 +22,6 @@
#include "pygboxed.h"
#include "pygenum.h"
#include "pygflags.h"
-#include "pygparamspec.h"
#include "pygi-util.h"
#include "pygpointer.h"
#include "pyginterface.h"
diff --git a/gi/pygi-value.c b/gi/pygi-value.c
index fa21316..7f2ba07 100644
--- a/gi/pygi-value.c
+++ b/gi/pygi-value.c
@@ -20,6 +20,7 @@
#include "pygi-value.h"
#include "pygi-struct.h"
#include "pygi-basictype.h"
+#include "pygi-fundamental.h"
#include "pygobject-object.h"
#include "pygi-type.h"
#include "pygi-fundamental.h"
@@ -27,7 +28,6 @@
#include "pygpointer.h"
#include "pygboxed.h"
#include "pygflags.h"
-#include "pygparamspec.h"
/* glib 2.62 has started to print warnings for these which can't be disabled selectively, so just copy them here */
@@ -561,18 +561,6 @@ pyg_value_from_pyobject_with_error(GValue *value, PyObject *obj)
}
break;
}
- case G_TYPE_PARAM:
- /* we need to support both the wrapped _gi.GParamSpec and the GI
- * GObject.ParamSpec */
- if (G_IS_PARAM_SPEC (pygobject_get (obj)))
- g_value_set_param(value, G_PARAM_SPEC (pygobject_get (obj)));
- else if (pyg_param_spec_check (obj))
- g_value_set_param(value, PyCapsule_GetPointer (obj, NULL));
- else {
- PyErr_SetString(PyExc_TypeError, "Expected ParamSpec");
- return -1;
- }
- break;
case G_TYPE_OBJECT:
if (obj == Py_None) {
g_value_set_object(value, NULL);
@@ -792,8 +780,6 @@ value_to_py_structured_type (const GValue *value, GType fundamental, gboolean co
g_value_get_boxed(value),FALSE,FALSE);
}
}
- case G_TYPE_PARAM:
- return pyg_param_spec_new(g_value_get_param(value));
case G_TYPE_OBJECT:
return pygobject_new(g_value_get_object(value));
case G_TYPE_VARIANT:
diff --git a/gi/pygobject-object.c b/gi/pygobject-object.c
index 8db78a6..9f43328 100644
--- a/gi/pygobject-object.c
+++ b/gi/pygobject-object.c
@@ -22,7 +22,6 @@
#include "pygobject-object.h"
#include "pyginterface.h"
-#include "pygparamspec.h"
#include "pygi-type.h"
#include "pygboxed.h"
#include "gimodule.h"
@@ -33,6 +32,7 @@
#include "pygi-property.h"
#include "pygi-signal-closure.h"
#include "pygi-basictype.h"
+#include "pygi-fundamental.h"
extern PyObject *PyGIDeprecationWarning;
@@ -220,7 +220,7 @@ static PyObject*
pygobject_props_iter_next(PyGPropsIter *iter)
{
if (iter->index < iter->n_props)
- return pyg_param_spec_new(iter->props[iter->index++]);
+ return pygi_fundamental_new(iter->props[iter->index++]);
else {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
@@ -305,7 +305,7 @@ PyGProps_getattro(PyGProps *self, PyObject *attr)
if (!self->pygobject) {
/* If we're doing it without an instance, return a GParamSpec */
- return pyg_param_spec_new(pspec);
+ return pygi_fundamental_new(pspec);
}
return pygi_get_property_value (self->pygobject, pspec);
@@ -1595,7 +1595,7 @@ pygbinding_closure_new (PyObject *callback, PyObject *extra_args)
}
static PyObject *
-pygobject_bind_property(PyGObject *self, PyObject *args)
+pygobject_bind_property(PyGObject *self, PyObject *args, PyObject *kwargs)
{
gchar *source_name, *target_name;
gchar *source_canon, *target_canon;
@@ -1608,9 +1608,20 @@ pygobject_bind_property(PyGObject *self, PyObject *args)
transform_from = NULL;
transform_to = NULL;
- if (!PyArg_ParseTuple(args, "sOs|iOOO:GObject.bind_property",
- &source_name, &target, &target_name, &flags,
- &transform_to, &transform_from, &user_data))
+ static char *kwlist[] = {
+ "source_property",
+ "target",
+ "target_property",
+ "flags",
+ "transform_to",
+ "transform_from",
+ "user_data",
+ NULL
+ };
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sOs|iOOO:GObject.bind_property", kwlist,
+ &source_name, &target, &target_name, &flags,
+ &transform_to, &transform_from, &user_data))
return NULL;
CHECK_GOBJECT(self);
diff --git a/gi/pygobject.h b/gi/pygobject.h
index a45a4b0..3a96454 100644
--- a/gi/pygobject.h
+++ b/gi/pygobject.h
@@ -75,19 +75,6 @@ typedef struct {
typedef void (*PyGFatalExceptionFunc) (void);
typedef void (*PyGThreadBlockFunc) (void);
-typedef struct {
- PyObject_HEAD
- GParamSpec *pspec;
-} PyGParamSpec;
-
-#define pyg_param_spec_get(v) (((PyGParamSpec *)v)->pspec)
-#define pyg_param_spec_set(v,p) (((PyGParamSpec *)v)->pspec = (GParamSpec*)p)
-#define pyg_param_spec_check(v) (PyObject_TypeCheck(v, &PyGParamSpec_Type))
-
-/* Deprecated in favor of lower case with underscore macros above. */
-#define PyGParamSpec_Get pyg_param_spec_get
-#define PyGParamSpec_Check pyg_param_spec_check
-
typedef int (*PyGClassInitFunc) (gpointer gclass, PyTypeObject *pyclass);
typedef PyTypeObject * (*PyGTypeRegistrationFunction) (const gchar *name,
gpointer data);
diff --git a/gi/pygparamspec.c b/gi/pygparamspec.c
deleted file mode 100644
index e49bd36..0000000
--- a/gi/pygparamspec.c
+++ /dev/null
@@ -1,423 +0,0 @@
-/* -*- Mode: C; c-basic-offset: 4 -*-
- * pygtk- Python bindings for the GTK toolkit.
- * Copyright (C) 1998-2003 James Henstridge
- * Copyright (C) 2004 Johan Dahlin
- *
- * pygenum.c: GEnum and GFlag wrappers
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, see .
- */
-
-#include
-
-#include
-#include
-
-#include "pygenum.h"
-#include "pygflags.h"
-#include "pygi-type.h"
-#include "pygparamspec.h"
-#include "pygi-util.h"
-#include "pygi-basictype.h"
-
-PYGI_DEFINE_TYPE("gobject.GParamSpec", PyGParamSpec_Type, PyGParamSpec);
-
-static PyObject*
-pyg_param_spec_richcompare(PyObject *self, PyObject *other, int op)
-{
- if (Py_TYPE(self) == Py_TYPE(other) && Py_TYPE(self) == &PyGParamSpec_Type)
- return pyg_ptr_richcompare (pyg_param_spec_get (self),
- pyg_param_spec_get (other),
- op);
- else {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
-}
-
-static Py_hash_t
-pyg_param_spec_hash(PyGParamSpec *self)
-{
- return (Py_hash_t)(gintptr)(pyg_param_spec_get (self));
-}
-
-static PyObject *
-pyg_param_spec_repr(PyGParamSpec *self)
-{
- char buf[80];
-
- g_snprintf(buf, sizeof(buf), "<%s '%s'>",
- G_PARAM_SPEC_TYPE_NAME (pyg_param_spec_get (self)),
- g_param_spec_get_name (pyg_param_spec_get (self)));
- return PyUnicode_FromString (buf);
-}
-
-static void
-pyg_param_spec_dealloc(PyGParamSpec *self)
-{
- g_param_spec_unref (pyg_param_spec_get (self));
- PyObject_DEL(self);
-}
-
-
-static PyObject *
-pygenum_from_pspec(GParamSpec *pspec)
-{
- PyObject *pyclass;
- GParamSpecEnum *enum_pspec;
- GType enum_type;
-
- enum_pspec = G_PARAM_SPEC_ENUM(pspec);
- enum_type = G_ENUM_CLASS_TYPE(enum_pspec->enum_class);
- pyclass = (PyObject*)g_type_get_qdata(enum_type, pygenum_class_key);
- if (pyclass == NULL) {
- pyclass = pyg_enum_add(NULL, g_type_name(enum_type), NULL, enum_type);
- if (pyclass == NULL)
- pyclass = Py_None;
- }
-
- Py_INCREF(pyclass);
- return pyclass;
-}
-
-static PyObject *
-pygflags_from_pspec(GParamSpec *pspec)
-{
- PyObject *pyclass;
- GParamSpecFlags *flag_pspec;
- GType flag_type;
-
- flag_pspec = G_PARAM_SPEC_FLAGS(pspec);
- flag_type = G_FLAGS_CLASS_TYPE(flag_pspec->flags_class);
- pyclass = (PyObject*)g_type_get_qdata(flag_type, pygflags_class_key);
- if (pyclass == NULL) {
- pyclass = pyg_flags_add(NULL, g_type_name(flag_type), NULL, flag_type);
- if (pyclass == NULL)
- pyclass = Py_None;
- }
- Py_INCREF(pyclass);
- return pyclass;
-}
-
-static PyObject *
-pyg_param_spec_getattr(PyGParamSpec *self, const gchar *attr)
-{
- GParamSpec *pspec;
-
- pspec = pyg_param_spec_get (self);
-
- /* common attributes */
- if (!strcmp(attr, "__gtype__")) {
- return pyg_type_wrapper_new(G_PARAM_SPEC_TYPE(pspec));
- } else if (!strcmp(attr, "name")) {
- return Py_BuildValue("s", g_param_spec_get_name(pspec));
- } else if (!strcmp(attr, "nick")) {
- return Py_BuildValue("s", g_param_spec_get_nick(pspec));
- } else if (!strcmp(attr, "blurb") || !strcmp(attr, "__doc__")) {
- return Py_BuildValue("s", g_param_spec_get_blurb(pspec));
- } else if (!strcmp(attr, "flags")) {
- return pygi_guint_to_py (pspec->flags);
- } else if (!strcmp(attr, "value_type")) {
- return pyg_type_wrapper_new(pspec->value_type);
- } else if (!strcmp(attr, "owner_type")) {
- return pyg_type_wrapper_new(pspec->owner_type);
- }
-
- if (G_IS_PARAM_SPEC_CHAR(pspec)) {
- if (!strcmp(attr, "default_value")) {
- return PyUnicode_FromFormat(
- "%c", G_PARAM_SPEC_CHAR(pspec)->default_value);
- } else if (!strcmp(attr, "minimum")) {
- return pygi_gint8_to_py (G_PARAM_SPEC_CHAR(pspec)->minimum);
- } else if (!strcmp(attr, "maximum")) {
- return pygi_gint8_to_py (G_PARAM_SPEC_CHAR(pspec)->maximum);
- }
- } else if (G_IS_PARAM_SPEC_UCHAR(pspec)) {
- if (!strcmp(attr, "default_value")) {
- return PyUnicode_FromFormat(
- "%c", G_PARAM_SPEC_UCHAR(pspec)->default_value);
- } else if (!strcmp(attr, "minimum")) {
- return pygi_guint8_to_py (G_PARAM_SPEC_UCHAR(pspec)->minimum);
- } else if (!strcmp(attr, "maximum")) {
- return pygi_guint8_to_py (G_PARAM_SPEC_UCHAR(pspec)->maximum);
- }
- } else if (G_IS_PARAM_SPEC_BOOLEAN(pspec)) {
- if (!strcmp(attr, "default_value")) {
- return pygi_gboolean_to_py (G_PARAM_SPEC_BOOLEAN(pspec)->default_value);
- }
- } else if (G_IS_PARAM_SPEC_INT(pspec)) {
- if (!strcmp(attr, "default_value")) {
- return pygi_gint_to_py (G_PARAM_SPEC_INT(pspec)->default_value);
- } else if (!strcmp(attr, "minimum")) {
- return pygi_gint_to_py (G_PARAM_SPEC_INT(pspec)->minimum);
- } else if (!strcmp(attr, "maximum")) {
- return pygi_gint_to_py (G_PARAM_SPEC_INT(pspec)->maximum);
- }
- } else if (G_IS_PARAM_SPEC_UINT(pspec)) {
- if (!strcmp(attr, "default_value")) {
- return pygi_guint_to_py (G_PARAM_SPEC_UINT(pspec)->default_value);
- } else if (!strcmp(attr, "minimum")) {
- return pygi_guint_to_py (G_PARAM_SPEC_UINT(pspec)->minimum);
- } else if (!strcmp(attr, "maximum")) {
- return pygi_guint_to_py (G_PARAM_SPEC_UINT(pspec)->maximum);
- }
- } else if (G_IS_PARAM_SPEC_LONG(pspec)) {
- if (!strcmp(attr, "default_value")) {
- return pygi_glong_to_py (G_PARAM_SPEC_LONG(pspec)->default_value);
- } else if (!strcmp(attr, "minimum")) {
- return pygi_glong_to_py (G_PARAM_SPEC_LONG(pspec)->minimum);
- } else if (!strcmp(attr, "maximum")) {
- return pygi_glong_to_py (G_PARAM_SPEC_LONG(pspec)->maximum);
- }
- } else if (G_IS_PARAM_SPEC_ULONG(pspec)) {
- if (!strcmp(attr, "default_value")) {
- return pygi_gulong_to_py (G_PARAM_SPEC_ULONG(pspec)->default_value);
- } else if (!strcmp(attr, "minimum")) {
- return pygi_gulong_to_py (G_PARAM_SPEC_ULONG(pspec)->minimum);
- } else if (!strcmp(attr, "maximum")) {
- return pygi_gulong_to_py (G_PARAM_SPEC_ULONG(pspec)->maximum);
- }
- } else if (G_IS_PARAM_SPEC_INT64(pspec)) {
- if (!strcmp(attr, "default_value")) {
- return pygi_gint64_to_py (G_PARAM_SPEC_INT64(pspec)->default_value);
- } else if (!strcmp(attr, "minimum")) {
- return pygi_gint64_to_py (G_PARAM_SPEC_INT64(pspec)->minimum);
- } else if (!strcmp(attr, "maximum")) {
- return pygi_gint64_to_py (G_PARAM_SPEC_INT64(pspec)->maximum);
- }
- } else if (G_IS_PARAM_SPEC_UINT64(pspec)) {
- if (!strcmp(attr, "default_value")) {
- return pygi_guint64_to_py (G_PARAM_SPEC_UINT64(pspec)->default_value);
- } else if (!strcmp(attr, "minimum")) {
- return pygi_guint64_to_py (G_PARAM_SPEC_UINT64(pspec)->minimum);
- } else if (!strcmp(attr, "maximum")) {
- return pygi_guint64_to_py (G_PARAM_SPEC_UINT64(pspec)->maximum);
- }
- } else if (G_IS_PARAM_SPEC_UNICHAR(pspec)) {
- if (!strcmp(attr, "default_value")) {
- return PyUnicode_FromFormat(
- "%c", G_PARAM_SPEC_UNICHAR(pspec)->default_value);
- }
- } else if (G_IS_PARAM_SPEC_ENUM(pspec)) {
- if (!strcmp(attr, "default_value")) {
- return pyg_enum_from_gtype(
- pspec->value_type, G_PARAM_SPEC_ENUM(pspec)->default_value);
- } else if (!strcmp(attr, "enum_class")) {
- return pygenum_from_pspec(pspec);
- }
- } else if (G_IS_PARAM_SPEC_FLAGS(pspec)) {
- if (!strcmp(attr, "default_value")) {
- return pyg_flags_from_gtype(
- pspec->value_type, G_PARAM_SPEC_FLAGS(pspec)->default_value);
- } else if (!strcmp(attr, "flags_class")) {
- return pygflags_from_pspec(pspec);
- }
- } else if (G_IS_PARAM_SPEC_FLOAT(pspec)) {
- if (!strcmp(attr, "default_value")) {
- return pygi_gfloat_to_py (G_PARAM_SPEC_FLOAT(pspec)->default_value);
- } else if (!strcmp(attr, "minimum")) {
- return pygi_gfloat_to_py (G_PARAM_SPEC_FLOAT(pspec)->minimum);
- } else if (!strcmp(attr, "maximum")) {
- return pygi_gfloat_to_py (G_PARAM_SPEC_FLOAT(pspec)->maximum);
- } else if (!strcmp(attr, "epsilon")) {
- return pygi_gfloat_to_py (G_PARAM_SPEC_FLOAT(pspec)->epsilon);
- }
- } else if (G_IS_PARAM_SPEC_DOUBLE(pspec)) {
- if (!strcmp(attr, "default_value")) {
- return pygi_gdouble_to_py (
- G_PARAM_SPEC_DOUBLE(pspec)->default_value);
- } else if (!strcmp(attr, "minimum")) {
- return pygi_gdouble_to_py (G_PARAM_SPEC_DOUBLE(pspec)->minimum);
- } else if (!strcmp(attr, "maximum")) {
- return pygi_gdouble_to_py (G_PARAM_SPEC_DOUBLE(pspec)->maximum);
- } else if (!strcmp(attr, "epsilon")) {
- return pygi_gdouble_to_py (G_PARAM_SPEC_DOUBLE(pspec)->epsilon);
- }
- } else if (G_IS_PARAM_SPEC_STRING(pspec)) {
- if (!strcmp(attr, "default_value")) {
- return Py_BuildValue(
- "s", G_PARAM_SPEC_STRING(pspec)->default_value);
- } else if (!strcmp(attr, "cset_first")) {
- return Py_BuildValue(
- "s", G_PARAM_SPEC_STRING(pspec)->cset_first);
- } else if (!strcmp(attr, "cset_nth")) {
- return Py_BuildValue(
- "s", G_PARAM_SPEC_STRING(pspec)->cset_nth);
- } else if (!strcmp(attr, "substitutor")) {
- return Py_BuildValue(
- "c", G_PARAM_SPEC_STRING(pspec)->substitutor);
- } else if (!strcmp(attr, "null_fold_if_empty")) {
- return pygi_gboolean_to_py (
- G_PARAM_SPEC_STRING(pspec)->null_fold_if_empty);
- } else if (!strcmp(attr, "ensure_non_null")) {
- return pygi_gboolean_to_py (
- G_PARAM_SPEC_STRING(pspec)->ensure_non_null);
- }
- } else {
- /* This is actually not what's exported by GObjects paramspecs,
- * But we exported this in earlier versions, so it's better to keep it here
- * compatibility. But don't return it in __dir__, to "hide" it.
- */
- if (!strcmp(attr, "default_value")) {
- /* XXX: Raise deprecation warning */
- Py_INCREF(Py_None);
- return Py_None;
- }
- }
-
- PyErr_SetString(PyExc_AttributeError, attr);
- return NULL;
-}
-
-
-static PyObject *
-pyg_param_spec_dir(PyGParamSpec *self, PyObject *dummy)
-{
- GParamSpec *pspec = pyg_param_spec_get (self);
-
- if (G_IS_PARAM_SPEC_CHAR(pspec)) {
- return Py_BuildValue("[sssssssssss]", "__doc__", "__gtype__",
- "blurb", "default_value", "flags",
- "maximum", "minimum", "name", "nick",
- "owner_type", "value_type");
- } else if (G_IS_PARAM_SPEC_UCHAR(pspec)) {
- return Py_BuildValue("[sssssssssss]", "__doc__", "__gtype__",
- "blurb", "default_value",
- "flags", "maximum", "minimum",
- "name", "nick", "owner_type",
- "value_type");
- } else if (G_IS_PARAM_SPEC_BOOLEAN(pspec)) {
- return Py_BuildValue("[sssssssss]", "__doc__", "__gtype__",
- "blurb", "default_value",
- "flags", "name", "nick", "owner_type",
- "value_type");
- } else if (G_IS_PARAM_SPEC_INT(pspec)) {
- return Py_BuildValue("[sssssssssss]", "__doc__", "__gtype__",
- "blurb", "default_value",
- "flags", "maximum", "minimum", "name",
- "nick", "owner_type", "value_type");
- } else if (G_IS_PARAM_SPEC_UINT(pspec)) {
- return Py_BuildValue("[sssssssssss]", "__doc__", "__gtype__",
- "blurb", "default_value",
- "flags", "maximum", "minimum",
- "name", "nick", "owner_type",
- "value_type");
- } else if (G_IS_PARAM_SPEC_LONG(pspec)) {
- return Py_BuildValue("[sssssssssss]", "__doc__", "__gtype__",
- "blurb", "default_value",
- "flags", "maximum", "minimum", "name",
- "nick", "owner_type", "value_type");
- } else if (G_IS_PARAM_SPEC_ULONG(pspec)) {
- return Py_BuildValue("[sssssssssss]", "__doc__", "__gtype__",
- "blurb", "default_value",
- "flags", "maximum", "minimum", "name",
- "nick", "owner_type", "value_type");
- } else if (G_IS_PARAM_SPEC_INT64(pspec)) {
- return Py_BuildValue("[sssssssssss]", "__doc__", "__gtype__",
- "blurb", "default_value",
- "flags", "maximum", "minimum", "name",
- "nick", "owner_type", "value_type");
- } else if (G_IS_PARAM_SPEC_UINT64(pspec)) {
- return Py_BuildValue("[sssssssssss]", "__doc__", "__gtype__",
- "blurb", "default_value",
- "flags", "maximum", "minimum",
- "name", "nick", "owner_type",
- "value_type");
- } else if (G_IS_PARAM_SPEC_UNICHAR(pspec)) {
- return Py_BuildValue("[sssssssss]", "__doc__", "__gtype__",
- "blurb", "default_value",
- "flags", "name", "nick", "owner_type",
- "value_type");
- } else if (G_IS_PARAM_SPEC_ENUM(pspec)) {
- return Py_BuildValue("[ssssssssss]", "__doc__", "__gtype__",
- "blurb", "default_value", "enum_class",
- "flags", "name", "nick", "owner_type",
- "value_type");
- } else if (G_IS_PARAM_SPEC_FLAGS(pspec)) {
- return Py_BuildValue("[ssssssssss]", "__doc__", "__gtype__",
- "blurb", "default_value",
- "flags", "flags_class", "name", "nick",
- "owner_type", "value_type");
- } else if (G_IS_PARAM_SPEC_FLOAT(pspec)) {
- return Py_BuildValue("[ssssssssssss]", "__doc__", "__gtype__",
- "blurb", "epsilon",
- "flags", "maximum", "minimum", "name", "nick", "owner_type",
- "value_type",
- "default_value");
- } else if (G_IS_PARAM_SPEC_DOUBLE(pspec)) {
- return Py_BuildValue("[ssssssssssss]", "__doc__", "__gtype__",
- "blurb", "default_value", "epsilon",
- "flags", "maximum", "minimum", "name", "nick",
- "owner_type", "value_type");
- } else if (G_IS_PARAM_SPEC_STRING(pspec)) {
- return Py_BuildValue("[ssssssssssssss]", "__doc__", "__gtype__",
- "blurb", "cset_first", "cset_nth", "default_value",
- "ensure_non_null", "flags", "name", "nick",
- "null_fold_if_empty", "owner_type", "substitutor",
- "value_type");
- } else {
- return Py_BuildValue("[ssssssss]", "__doc__", "__gtype__", "blurb",
- "flags", "name", "nick",
- "owner_type", "value_type");
- }
-}
-
-static PyMethodDef pyg_param_spec_methods[] = {
- { "__dir__", (PyCFunction)pyg_param_spec_dir, METH_NOARGS},
- { NULL, NULL, 0}
-};
-
-/**
- * pyg_param_spec_new:
- * @pspec: a GParamSpec.
- *
- * Creates a wrapper for a GParamSpec.
- *
- * Returns: the GParamSpec wrapper.
- */
-PyObject *
-pyg_param_spec_new(GParamSpec *pspec)
-{
- PyGParamSpec *self;
-
- self = (PyGParamSpec *)PyObject_NEW(PyGParamSpec,
- &PyGParamSpec_Type);
- if (self == NULL)
- return NULL;
-
- pyg_param_spec_set (self, g_param_spec_ref (pspec));
- return (PyObject *)self;
-}
-
-/**
- * Returns 0 on success, or -1 and sets an exception.
- */
-int
-pygi_paramspec_register_types(PyObject *d)
-{
- Py_SET_TYPE(&PyGParamSpec_Type, &PyType_Type);
- PyGParamSpec_Type.tp_dealloc = (destructor)pyg_param_spec_dealloc;
- PyGParamSpec_Type.tp_getattr = (getattrfunc)pyg_param_spec_getattr;
- PyGParamSpec_Type.tp_richcompare = pyg_param_spec_richcompare;
- PyGParamSpec_Type.tp_flags = Py_TPFLAGS_DEFAULT;
- PyGParamSpec_Type.tp_repr = (reprfunc)pyg_param_spec_repr;
- PyGParamSpec_Type.tp_hash = (hashfunc)pyg_param_spec_hash;
- PyGParamSpec_Type.tp_methods = pyg_param_spec_methods;
-
- if (PyType_Ready(&PyGParamSpec_Type))
- return -1;
- PyDict_SetItemString(d, "GParamSpec", (PyObject *)&PyGParamSpec_Type);
-
- return 0;
-}
diff --git a/gi/pygparamspec.h b/gi/pygparamspec.h
deleted file mode 100644
index 8798535..0000000
--- a/gi/pygparamspec.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/* -*- Mode: C; c-basic-offset: 4 -*-
- * pygtk- Python bindings for the GTK toolkit.
- * Copyright (C) 1998-2003 James Henstridge
- * 2004-2008 Johan Dahlin
- * pyginterface.c: wrapper for the gobject library.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, see .
- */
-
-#ifndef __PYGOBJECT_PARAMSPEC_H__
-#define __PYGOBJECT_PARAMSPEC_H__
-
-#include
-
-extern PyTypeObject PyGParamSpec_Type;
-PyObject * pyg_param_spec_new (GParamSpec *pspec);
-
-int pygi_paramspec_register_types(PyObject *d);
-
-#endif /* __PYGOBJECT_PARAMSPEC_H__ */
diff --git a/gi/pygspawn.c b/gi/pygspawn.c
index 56ecf06..10e862f 100644
--- a/gi/pygspawn.c
+++ b/gi/pygspawn.c
@@ -32,22 +32,31 @@ struct _PyGChildSetupData {
PyObject *data;
};
-PYGI_DEFINE_TYPE("gi._gi.Pid", PyGPid_Type, PyLongObject)
+typedef struct {
+ PyLongObject obj;
+ /*
+ * This exists for two reasons:
+ * 1. We must only close once (ideally we would not have "close" in python)
+ * 2. In PyPy we cannot use PyLong_AsLong during free
+ */
+ GPid unclosed;
+} PyGPid;
-static GPid
-pyg_pid_get_pid (PyObject *self)
+PYGI_DEFINE_TYPE("gi._gi.Pid", PyGPid_Type, PyGPid)
+
+static PyObject *
+pyg_pid_close(PyObject *self, PyObject *args, PyObject *kwargs)
{
+ PyGPid* gpid = (PyGPid*) self;
+
+ if (gpid->unclosed)
+ g_spawn_close_pid(gpid->unclosed);
#ifdef G_OS_WIN32
- return (GPid)PyLong_AsVoidPtr (self);
+ gpid->unclosed = NULL;
#else
- return (GPid)PyLong_AsLong (self);
+ gpid->unclosed = 0;
#endif
-}
-static PyObject *
-pyg_pid_close(PyObject *self, PyObject *args, PyObject *kwargs)
-{
- g_spawn_close_pid(pyg_pid_get_pid (self));
Py_INCREF(Py_None);
return Py_None;
}
@@ -58,10 +67,14 @@ static PyMethodDef pyg_pid_methods[] = {
};
static void
-pyg_pid_free(PyObject *gpid)
+pyg_pid_free(PyObject *self)
{
- g_spawn_close_pid(pyg_pid_get_pid (gpid));
- PyLong_Type.tp_free((void *) gpid);
+ PyGPid* gpid = (PyGPid*) self;
+
+ if (gpid->unclosed)
+ g_spawn_close_pid(gpid->unclosed);
+
+ PyLong_Type.tp_free((void *) self);
}
static int
diff --git a/meson.build b/meson.build
index 8c8a021..73589a0 100644
--- a/meson.build
+++ b/meson.build
@@ -1,8 +1,10 @@
-project('pygobject', 'c',
- version : '3.48.2',
+project(
+ 'pygobject',
+ 'c',
+ version : '3.50.0',
meson_version : '>= 0.64.0',
- default_options : [ 'warning_level=1',
- 'buildtype=debugoptimized'])
+ default_options : ['warning_level=1', 'buildtype=debugoptimized']
+)
pygobject_version = meson.project_version()
version_arr = pygobject_version.split('.')
@@ -15,8 +17,8 @@ platform_version = '@0@.0'.format(pygobject_version_major)
pymod = import('python')
python = pymod.find_installation(get_option('python'), pure: false)
-if python.language_version().version_compare('< 3.8')
- error('Requires Python >= 3.8')
+if python.language_version().version_compare('< 3.9')
+ error('Requires Python >= 3.9')
endif
python_dep = python.dependency()
@@ -194,10 +196,10 @@ if not for_wheel
pkginfo_conf = configuration_data()
pkginfo_conf.set('VERSION', py_version)
- configure_file(input : 'PKG-INFO.in',
- output : 'PyGObject-@0@.egg-info'.format(py_version),
+ configure_file(input : 'METADATA.in',
+ output : 'METADATA',
configuration : pkginfo_conf,
- install_dir : python.get_install_dir(pure : false))
+ install_dir : python.get_install_dir(pure : false) / 'PyGObject-@0@.dist-info'.format(py_version))
endif
pygobject_dep = declare_dependency(
diff --git a/pygobject.doap b/pygobject.doap
index 62d378d..4cd0de7 100644
--- a/pygobject.doap
+++ b/pygobject.doap
@@ -43,4 +43,11 @@ PyGObject now dynamically accesses any GObject libraries that uses GObject Intro
amolenaar
+
+
+ Dan Yeaw
+
+ danyeaw
+
+
diff --git a/pygtkcompat/generictreemodel.py b/pygtkcompat/generictreemodel.py
index 449275f..68fb878 100644
--- a/pygtkcompat/generictreemodel.py
+++ b/pygtkcompat/generictreemodel.py
@@ -109,11 +109,11 @@ class GenericTreeModel(GObject.GObject, Gtk.TreeModel):
#
def __init__(self):
"""Initialize. Make sure to call this from derived classes if overridden."""
- warnings.warn("pygtkcompat is deprecated, see https://gnome.pages.gitlab.gnome.org/pygobject for migration instructions", gi.PyGIDeprecationWarning)
+ warnings.warn("pygtkcompat is deprecated, see https://pygobject.gnome.org for migration instructions", gi.PyGIDeprecationWarning)
super(GenericTreeModel, self).__init__()
self.stamp = 0
- #: Dictionary of (id(user_data): user_data), used when leak-refernces=False
+ #: Dictionary of (id(user_data): user_data), used when leak-references=False
self._held_refs = dict()
# Set initial stamp
diff --git a/pygtkcompat/pygtkcompat.py b/pygtkcompat/pygtkcompat.py
index bfef9a3..9b68c57 100644
--- a/pygtkcompat/pygtkcompat.py
+++ b/pygtkcompat/pygtkcompat.py
@@ -107,7 +107,7 @@ def _check_enabled(name, version=None):
def enable():
- warnings.warn("pygtkcompat is deprecated, see https://gnome.pages.gitlab.gnome.org/pygobject for migration instructions", gi.PyGIDeprecationWarning)
+ warnings.warn("pygtkcompat is deprecated, see https://pygobject.gnome.org for migration instructions", gi.PyGIDeprecationWarning)
if _check_enabled(""):
return
diff --git a/pyproject.toml b/pyproject.toml
index 09a286b..ef8a485 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,14 +1,16 @@
[project]
name = "PyGObject"
-version = "3.48.2"
description = "Python bindings for GObject Introspection"
+readme = 'README.rst'
license = { text = "GNU Lesser General Public License v2.1 (LGPLv2.1)" }
authors = [
{ name="James Henstridge", email="james@daa.com.au" }
]
maintainers = [
- { name="Simon Feltman", email="sfeltman@src.gnome.org" },
- { name="Christoph Reiter" },
+ { name="Christoph Reiter", email="creiter@src.gnome.org" },
+ { name="Arjan Molenaar", email="amolenaar@gnome.org" },
+ { name="Dan Yeaw", email="danyeaw@gnome.org" },
+ { name="Ignacio Casal Quinteiro", email="icq@gnome.org" },
]
classifiers = [
"Development Status :: 5 - Production/Stable",
@@ -20,26 +22,44 @@ classifiers = [
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
]
-requires-python = ">=3.8, <4"
+requires-python = ">=3.9, <4.0"
dependencies = [
"pycairo>=1.16"
]
+dynamic = ["version"]
[project.urls]
-Homepage = "https://gnome.pages.gitlab.gnome.org/pygobject"
+Homepage = "https://pygobject.gnome.org"
Repository = "https://gitlab.gnome.org/GNOME/pygobject.git"
-Changelog = "https://gitlab.gnome.org/GNOME/pygobject/-/blob/master/NEWS"
+Changelog = "https://gitlab.gnome.org/GNOME/pygobject/-/blob/main/NEWS"
-[project.optional-dependencies]
-dev = [
+[tool.pdm.dev-dependencies]
+build = [
+ "setuptools",
+ "meson-python",
+ "ninja",
+ "pycairo",
+]
+test = [
"pytest",
"pytest-cov",
"flake8",
]
docs = [
- "sphinx>=4.0,<5.0",
- "sphinx-rtd-theme>=0.5,<2.0",
+ "sphinx",
+ "sphinx-rtd-theme",
+ "sphinx-copybutton>=0.5.2",
+ "furo",
+]
+
+[tool.pdm.options]
+install = [
+ "--no-isolation",
+ "--config-setting=setup-args=-Dtests=true",
+ "--config-setting=setup-args=-Dbuildtype=debug",
+ "--config-setting=editable-verbose=true",
]
+build = ["--no-wheel"]
[tool.meson-python.args]
setup = ["-Dtests=false", "-Dwheel=true", "--wrap-mode=nofallback"]
diff --git a/subprojects/gobject-introspection.wrap b/subprojects/gobject-introspection.wrap
index c63dc22..7a15f04 100644
--- a/subprojects/gobject-introspection.wrap
+++ b/subprojects/gobject-introspection.wrap
@@ -4,3 +4,4 @@ url=https://gitlab.gnome.org/GNOME/gobject-introspection.git
push-url=git@gitlab.gnome.org:GNOME/gobject-introspection.git
revision=main
depth=1
+clone-recursive=true
\ No newline at end of file
diff --git a/tests/gimarshallingtestsextra.h b/tests/gimarshallingtestsextra.h
index 8feecaa..8873d88 100644
--- a/tests/gimarshallingtestsextra.h
+++ b/tests/gimarshallingtestsextra.h
@@ -22,6 +22,10 @@
#include
#include
+#ifndef GI_TEST_EXTERN
+#define GI_TEST_EXTERN extern
+#endif
+
typedef enum
{
GI_MARSHALLING_TESTS_EXTRA_ENUM_VALUE1,
@@ -37,36 +41,36 @@ typedef enum
} GIMarshallingTestsExtraFlags;
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
GType gi_marshalling_tests_extra_flags_get_type (void) G_GNUC_CONST;
#define GI_MARSHALLING_TESTS_TYPE_EXTRA_FLAGS (gi_marshalling_tests_extra_flags_get_type ())
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
void gi_marshalling_tests_compare_two_gerrors_in_gvalue (GValue *v, GValue *v1);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
gboolean gi_marshalling_tests_nullable_gerror(GError *error);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
void gi_marshalling_tests_ghashtable_enum_none_in (GHashTable *hash_table);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
GHashTable * gi_marshalling_tests_ghashtable_enum_none_return (void);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
gchar * gi_marshalling_tests_filename_copy (gchar *path_in);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
gboolean gi_marshalling_tests_filename_exists (gchar *path);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
gchar * gi_marshalling_tests_filename_to_glib_repr (gchar *path_in, gsize *len);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
GIMarshallingTestsExtraEnum * gi_marshalling_tests_enum_array_return_type (gsize *n_members);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
void gi_marshalling_tests_extra_flags_large_in (GIMarshallingTestsExtraFlags value);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
gchar *gi_marshalling_tests_extra_utf8_full_return_invalid (void);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
void gi_marshalling_tests_extra_utf8_full_out_invalid (gchar **utf8);
#endif /* EXTRA_TESTS */
diff --git a/tests/meson.build b/tests/meson.build
index f3b2c02..28f779e 100644
--- a/tests/meson.build
+++ b/tests/meson.build
@@ -9,12 +9,15 @@ if get_option('default_library') != 'static'
if host_system == 'windows'
visibility_args += ['-DDLL_EXPORT']
if cc.get_id() == 'msvc'
+ visibility_args += ['-DGI_TEST_EXTERN=__declspec(dllexport) extern']
visibility_args += ['-D_GI_EXTERN=__declspec(dllexport) extern']
elif cc.has_argument('-fvisibility=hidden')
+ visibility_args += ['-DGI_TEST_EXTERN=__attribute__((visibility("default"))) __declspec(dllexport) extern']
visibility_args += ['-D_GI_EXTERN=__attribute__((visibility("default"))) __declspec(dllexport) extern']
visibility_args += ['-fvisibility=hidden']
endif
elif cc.has_argument('-fvisibility=hidden')
+ visibility_args += ['-DGI_TEST_EXTERN=__attribute__((visibility("default"))) extern']
visibility_args += ['-D_GI_EXTERN=__attribute__((visibility("default"))) extern']
visibility_args += ['-fvisibility=hidden']
endif
@@ -40,7 +43,6 @@ else
endif
marshalling_sources += ['gimarshallingtestsextra.c']
-
marshalling_headers += ['gimarshallingtestsextra.h']
marshalling_lib = library(
@@ -73,7 +75,7 @@ regress_c_args = []
if cairo_dep.found()
regress_deps += [cairo_dep, cairo_gobject_dep]
else
- regress_c_args += ['-D_GI_DISABLE_CAIRO']
+ regress_c_args += ['-D_GI_DISABLE_CAIRO', '-DGI_TEST_DISABLE_CAIRO']
endif
regress_lib = library(
diff --git a/tests/regressextra.h b/tests/regressextra.h
index 86ed14c..a799409 100644
--- a/tests/regressextra.h
+++ b/tests/regressextra.h
@@ -3,76 +3,80 @@
#include
+#ifndef GI_TEST_EXTERN
+#define GI_TEST_EXTERN extern
+#endif
+
typedef struct _RegressTestBoxedC RegressTestBoxedC;
typedef struct _RegressTestBoxedCWrapper RegressTestBoxedCWrapper;
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
GType regress_test_boxed_c_wrapper_get_type (void);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
RegressTestBoxedCWrapper *regress_test_boxed_c_wrapper_new (void);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
RegressTestBoxedCWrapper * regress_test_boxed_c_wrapper_copy (RegressTestBoxedCWrapper *self);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
RegressTestBoxedC *regress_test_boxed_c_wrapper_get (RegressTestBoxedCWrapper *self);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
gchar** regress_test_array_of_non_utf8_strings (void);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
void regress_test_array_fixed_boxed_none_out (RegressTestBoxedC ***objs);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
void regress_test_gvalue_out_boxed (GValue *value, int init);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
GList *regress_test_glist_boxed_none_return (guint count);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
GList *regress_test_glist_boxed_full_return (guint count);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
gboolean regress_test_array_of_fundamental_objects_in (RegressTestFundamentalObject **list, gsize len);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
RegressTestFundamentalObject** regress_test_array_of_fundamental_objects_out (gsize *len);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
gboolean regress_test_fundamental_argument_in (RegressTestFundamentalObject *obj);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
RegressTestFundamentalObject* regress_test_fundamental_argument_out (RegressTestFundamentalObject *obj);
#ifndef _GI_DISABLE_CAIRO
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
cairo_t *regress_test_cairo_context_none_return (void);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
void regress_test_cairo_context_full_in (cairo_t *context);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
cairo_path_t *regress_test_cairo_path_full_return (void);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
void regress_test_cairo_path_none_in (cairo_path_t *path);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
cairo_path_t * regress_test_cairo_path_full_in_full_return (cairo_path_t *path);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
void regress_test_cairo_pattern_full_in (cairo_pattern_t *pattern);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
void regress_test_cairo_pattern_none_in (cairo_pattern_t *pattern);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
cairo_pattern_t* regress_test_cairo_pattern_none_return (void);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
cairo_pattern_t * regress_test_cairo_pattern_full_return (void);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
cairo_font_options_t *regress_test_cairo_font_options_full_return (void);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
cairo_font_options_t *regress_test_cairo_font_options_none_return (void);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
void regress_test_cairo_font_options_full_in (cairo_font_options_t *options);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
void regress_test_cairo_font_options_none_in (cairo_font_options_t *options);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
void regress_test_cairo_region_full_in (cairo_region_t *region);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
void regress_test_cairo_surface_full_in (cairo_surface_t *surface);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
void regress_test_cairo_matrix_none_in (const cairo_matrix_t *matrix);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
cairo_matrix_t *regress_test_cairo_matrix_none_return (void);
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
void regress_test_cairo_matrix_out_caller_allocates (cairo_matrix_t *matrix);
#endif
@@ -87,7 +91,7 @@ typedef struct {
GInitiallyUnownedClass parent_class;
} RegressTestActionClass;
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
GType regress_test_action_get_type (void);
@@ -109,7 +113,7 @@ GType regress_test_action_get_type (void);
#define REGRESS_TYPE_BITMASK (regress_bitmask_get_type())
-_GI_TEST_EXTERN
+GI_TEST_EXTERN
GType regress_bitmask_get_type (void);
#endif /* REGRESS_EXTRA_H */
diff --git a/tests/test_async.py b/tests/test_async.py
new file mode 100644
index 0000000..abee637
--- /dev/null
+++ b/tests/test_async.py
@@ -0,0 +1,197 @@
+# -*- Mode: Python; py-indent-offset: 4 -*-
+# vim: tabstop=4 shiftwidth=4 expandtab
+
+import pytest
+import platform
+import unittest
+
+import asyncio
+from gi.repository import GLib, Gio
+from gi.events import GLibEventLoopPolicy
+
+
+class TestAsync(unittest.TestCase):
+
+ def setUp(self):
+ policy = GLibEventLoopPolicy()
+ asyncio.set_event_loop_policy(policy)
+ self.addCleanup(asyncio.set_event_loop_policy, None)
+ self.loop = policy.get_event_loop()
+ self.addCleanup(self.loop.close)
+
+ def test_async_enumerate(self):
+ f = Gio.file_new_for_path("./")
+
+ called = False
+
+ def cb():
+ nonlocal called
+ called = True
+
+ async def run():
+ nonlocal called, self
+
+ self.loop.call_soon(cb)
+
+ iter_info = []
+ for info in await f.enumerate_children_async("standard::*", 0, GLib.PRIORITY_DEFAULT):
+ iter_info.append(info.get_name())
+
+ # The await runs the mainloop and cb is called.
+ self.assertEqual(called, True)
+
+ next_info = []
+ enumerator = f.enumerate_children("standard::*", 0, None)
+ while True:
+ info = enumerator.next_file(None)
+ if info is None:
+ break
+ next_info.append(info.get_name())
+
+ self.assertEqual(iter_info, next_info)
+
+ self.loop.run_until_complete(run())
+
+ def test_async_cancellation(self):
+ """Cancellation raises G_IO_ERROR_CANCELLED"""
+
+ f = Gio.file_new_for_path("./")
+
+ async def run():
+ nonlocal self
+
+ # cancellable created implicitly
+ res = f.enumerate_children_async("standard::*", 0, GLib.PRIORITY_DEFAULT)
+ res.cancel()
+ with self.assertRaisesRegex(GLib.GError, "Operation was cancelled"):
+ await res
+
+ # cancellable passed explicitly
+ cancel = Gio.Cancellable()
+ res = f.enumerate_children_async("standard::*", 0, GLib.PRIORITY_DEFAULT, cancel)
+ self.assertEqual(res.cancellable, cancel)
+ cancel.cancel()
+ with self.assertRaisesRegex(GLib.GError, "Operation was cancelled"):
+ await res
+
+ self.loop.run_until_complete(run())
+
+ def test_not_completed(self):
+ """Querying an uncompleted task raises exceptions"""
+
+ f = Gio.file_new_for_path("./")
+
+ async def run():
+ nonlocal self
+
+ # cancellable created implicitly
+ res = f.enumerate_children_async("standard::*", 0, GLib.PRIORITY_DEFAULT)
+ with self.assertRaises(asyncio.InvalidStateError):
+ res.result()
+
+ with self.assertRaises(asyncio.InvalidStateError):
+ res.exception()
+
+ # And, await it
+ await res
+
+ self.loop.run_until_complete(run())
+
+ def test_async_cancel_completed(self):
+ """Cancelling a completed task just cancels the cancellable"""
+
+ f = Gio.file_new_for_path("./")
+
+ async def run():
+ nonlocal self
+
+ res = f.enumerate_children_async("standard::*", 0, GLib.PRIORITY_DEFAULT)
+ await res
+ assert not res.cancellable.is_cancelled()
+ res.cancel()
+ assert res.cancellable.is_cancelled()
+
+ self.loop.run_until_complete(run())
+
+ def test_async_completed_add_cb(self):
+ """Adding a done cb to a completed future queues it with call_soon"""
+
+ f = Gio.file_new_for_path("./")
+
+ called = False
+
+ def cb():
+ nonlocal called
+ called = True
+
+ async def run():
+ nonlocal called, self
+
+ res = f.enumerate_children_async("standard::*", 0, GLib.PRIORITY_DEFAULT)
+ await res
+ self.loop.call_soon(cb)
+
+ # Python await is smart and does not iterate the EventLoop
+ await res
+ assert not called
+
+ # So create a new future and wait on that
+ fut = asyncio.Future()
+
+ def done_cb(res):
+ nonlocal fut
+ fut.set_result(res.result())
+
+ res.add_done_callback(done_cb)
+ await fut
+ assert called
+
+ self.loop.run_until_complete(run())
+
+ @pytest.mark.xfail(platform.python_implementation() == "PyPy", reason="Exception reporting does not work in pypy")
+ def test_deleting_failed_logs(self):
+ f = Gio.file_new_for_path("./")
+
+ async def run():
+ nonlocal self
+
+ res = f.enumerate_children_async("standard::*", 0, GLib.PRIORITY_DEFAULT)
+ res.cancel()
+ # Cancellation in Gio is not immediate, so sleep for a bit
+ await asyncio.sleep(0.5)
+
+ exc = None
+ msg = None
+
+ def handler(loop, context):
+ nonlocal exc, msg
+ msg = context['message']
+ exc = context['exception']
+
+ self.loop.set_exception_handler(handler)
+ self.loop.run_until_complete(run())
+
+ self.assertRegex(msg, ".*exception was never retrieved")
+ self.assertIsInstance(exc, GLib.GError)
+ assert exc.matches(Gio.io_error_quark(), Gio.IOErrorEnum.CANCELLED)
+
+ def test_no_running_loop(self):
+ f = Gio.file_new_for_path("./")
+
+ res = f.enumerate_children_async("standard::*", 0, GLib.PRIORITY_DEFAULT)
+ self.assertIsNone(res)
+
+ def test_wrong_default_context(self):
+ f = Gio.file_new_for_path("./")
+
+ async def run():
+ nonlocal self
+
+ ctx = GLib.MainContext.new()
+ GLib.MainContext.push_thread_default(ctx)
+ self.addCleanup(GLib.MainContext.pop_thread_default, ctx)
+
+ res = f.enumerate_children_async("standard::*", 0, GLib.PRIORITY_DEFAULT)
+ self.assertIsNone(res)
+
+ self.loop.run_until_complete(run())
diff --git a/tests/test_events.py b/tests/test_events.py
new file mode 100644
index 0000000..81409ab
--- /dev/null
+++ b/tests/test_events.py
@@ -0,0 +1,264 @@
+import sys
+import unittest
+
+try:
+ if sys.platform != 'win32':
+ from test.test_asyncio.test_events import UnixEventLoopTestsMixin as GLibEventLoopTestsMixin
+ else:
+ from test.test_asyncio.test_events import EventLoopTestsMixin
+
+ # There is Mixin for the ProactorEventLoop, so copy the skips
+ class GLibEventLoopTestsMixin(EventLoopTestsMixin):
+ def test_reader_callback(self):
+ raise unittest.SkipTest("IocpEventLoop does not have add_reader()")
+
+ def test_reader_callback_cancel(self):
+ raise unittest.SkipTest("IocpEventLoop does not have add_reader()")
+
+ def test_writer_callback(self):
+ raise unittest.SkipTest("IocpEventLoop does not have add_writer()")
+
+ def test_writer_callback_cancel(self):
+ raise unittest.SkipTest("IocpEventLoop does not have add_writer()")
+
+ def test_remove_fds_after_closing(self):
+ raise unittest.SkipTest("IocpEventLoop does not have add_reader()")
+
+ from test.test_asyncio.test_subprocess import SubprocessMixin
+ from test.test_asyncio.utils import TestCase
+except:
+ class GLibEventLoopTestsMixin():
+ def test_unix_event_loop_tests_missing(self):
+ import warnings
+ warnings.warn('UnixEventLoopTestsMixin is unavailable, not running tests!')
+ self.skipTest('UnixEventLoopTestsMixin is unavailable, not running tests!')
+
+ class SubprocessMixin():
+ def test_subprocess_mixin_tests_missing(self):
+ import warnings
+ warnings.warn('SubprocessMixin is unavailable, not running tests!')
+ self.skipTest('SubprocessMixin is unavailable, not running tests!')
+
+ from unittest import TestCase
+
+import sys
+import gi
+import gi.events
+import asyncio
+import threading
+from gi.repository import GLib
+
+try:
+ from gi.repository import Gtk
+except ImportError:
+ Gtk = None
+
+
+GTK4 = (Gtk and Gtk._version == "4.0")
+
+
+class GLibEventLoopTests(GLibEventLoopTestsMixin, TestCase):
+
+ def __init__(self, *args):
+ super().__init__(*args)
+ self.loop = None
+
+ def create_event_loop(self):
+ return gi.events.GLibEventLoop(GLib.MainContext())
+
+
+class SubprocessWatcherTests(SubprocessMixin, TestCase):
+
+ def setUp(self):
+ super().setUp()
+ policy = gi.events.GLibEventLoopPolicy()
+ asyncio.set_event_loop_policy(policy)
+ self.loop = policy.get_event_loop()
+
+ def tearDown(self):
+ asyncio.set_event_loop_policy(None)
+ self.loop.close()
+ super().tearDown()
+
+
+class GLibEventLoopPolicyTests(unittest.TestCase):
+
+ def create_policy(self):
+ return gi.events.GLibEventLoopPolicy()
+
+ def test_get_event_loop(self):
+ policy = self.create_policy()
+ loop = policy.get_event_loop()
+ self.assertIsInstance(loop, gi.events.GLibEventLoop)
+ self.assertIs(loop, policy.get_event_loop())
+ loop.close()
+
+ def test_new_event_loop(self):
+ policy = self.create_policy()
+ loop = policy.new_event_loop()
+ self.assertIsInstance(loop, gi.events.GLibEventLoop)
+ loop.close()
+
+ # Attaching a loop to the main thread fails
+ with self.assertRaises(RuntimeError):
+ policy.set_event_loop(loop)
+
+ def test_nested_context_iteration(self):
+ policy = self.create_policy()
+ loop = policy.new_event_loop()
+
+ called = False
+
+ def cb():
+ nonlocal called
+ called = True
+
+ async def run():
+ nonlocal loop, called
+
+ loop.call_soon(cb)
+ self.assertEqual(called, False)
+
+ # Iterating the main context does not cause cb to be called
+ while loop._context.iteration(False):
+ pass
+ self.assertEqual(called, False)
+
+ # Awaiting on anything *does* cause the cb to fire
+ await asyncio.sleep(0)
+ self.assertEqual(called, True)
+
+ loop.run_until_complete(run())
+ loop.close()
+
+ def test_thread_event_loop(self):
+ policy = self.create_policy()
+ loop = policy.new_event_loop()
+
+ res = []
+
+ def thread_func(res):
+ try:
+ # We cannot get an event loop for the current thread
+ with self.assertRaises(RuntimeError):
+ policy.get_event_loop()
+
+ # We can attach our loop
+ policy.set_event_loop(loop)
+ # Now we can get it, and it is the same
+ self.assertIs(policy.get_event_loop(), loop)
+
+ # Simple call_soon test
+ results = []
+
+ def callback(arg1, arg2):
+ results.append((arg1, arg2))
+ loop.stop()
+
+ loop.call_soon(callback, 'hello', 'world')
+ loop.run_forever()
+ self.assertEqual(results, [('hello', 'world')])
+
+ # We can detach it again
+ policy.set_event_loop(None)
+
+ # Which means we have none and get a runtime error
+ with self.assertRaises(RuntimeError):
+ policy.get_event_loop()
+ except:
+ res += sys.exc_info()
+
+ # Initially, the thread has no event loop
+ thread = threading.Thread(target=lambda: thread_func(res))
+ thread.start()
+ thread.join()
+
+ if res:
+ t, v, tb = res
+ raise t(v).with_traceback(tb)
+
+ loop.close()
+
+ def test_outside_context_iteration(self):
+ """Iterating the main context from the outside, does not cause the
+ EventLoop to dispatch."""
+ policy = self.create_policy()
+ loop = policy.new_event_loop()
+
+ called = False
+
+ def cb():
+ nonlocal called
+ called = True
+
+ loop.call_soon(cb)
+ while loop._context.iteration(False):
+ pass
+ loop.close()
+ self.assertEqual(called, False)
+
+ def test_inside_context_iteration(self):
+ """Iterating the main context from the inside, does not cause the
+ EventLoop to dispatch."""
+ policy = self.create_policy()
+ loop = policy.get_event_loop()
+
+ done = asyncio.Future(loop=loop)
+
+ called = False
+
+ def cb():
+ nonlocal called
+ called = True
+
+ def ctx_iterate():
+ nonlocal called
+
+ loop.call_soon(cb)
+ while loop._context.iteration(False):
+ pass
+ self.assertEqual(called, False)
+
+ # If we by-pass the override, then the callback is called
+ while super(GLib.MainContext, loop._context).iteration(False):
+ pass
+ self.assertEqual(called, True)
+
+ # It'll also be called (again) before run_until_complete finishes
+ called = False
+ loop.call_soon(cb)
+
+ done.set_result(True)
+
+ return GLib.SOURCE_REMOVE
+
+ GLib.idle_add(ctx_iterate)
+ loop.run_until_complete(done)
+ loop.close()
+ self.assertEqual(called, True)
+
+ @unittest.skipUnless(Gtk, 'no Gtk')
+ def test_recursive_stop(self):
+ """Calling stop() on the EventLoop will quit it, even if iteration
+ is done recursively."""
+ policy = self.create_policy()
+ asyncio.set_event_loop_policy(policy)
+ self.addCleanup(asyncio.set_event_loop_policy, None)
+ loop = policy.get_event_loop()
+
+ if not GTK4:
+ def main_gtk():
+ GLib.idle_add(loop.stop)
+ Gtk.main()
+
+ GLib.idle_add(main_gtk)
+ Gtk.main()
+
+ def main_glib():
+ GLib.idle_add(loop.stop)
+ GLib.MainLoop().run()
+
+ GLib.idle_add(main_glib)
+ GLib.MainLoop().run()
+
+ loop.close()
diff --git a/tests/test_fundamental.py b/tests/test_fundamental.py
index 815aa73..2374ec1 100644
--- a/tests/test_fundamental.py
+++ b/tests/test_fundamental.py
@@ -1,4 +1,5 @@
import gc
+import weakref
import pytest
from gi.repository import GObject, Regress
@@ -130,6 +131,18 @@ def test_multiple_objects():
assert obj1 != obj2
+def test_fundamental_weak_ref():
+ obj = Regress.TestFundamentalSubObject()
+ weak = weakref.ref(obj)
+
+ assert weak() == obj
+
+ del obj
+ gc.collect()
+
+ assert weak() is None
+
+
def test_fundamental_primitive_object():
bitmask = Regress.Bitmask(2)
@@ -139,6 +152,7 @@ def test_fundamental_primitive_object():
def test_custom_fundamental_type_vfunc_override(capsys):
obj = MyCustomFundamentalObject()
del obj
+ gc.collect()
out = capsys.readouterr().out
diff --git a/tests/test_gdbus.py b/tests/test_gdbus.py
index 6c9afb0..afbf94c 100644
--- a/tests/test_gdbus.py
+++ b/tests/test_gdbus.py
@@ -253,3 +253,107 @@ def __init__(self):
Gio.DBusProxy.__init__(self)
SomeProxy()
+
+
+class TestDBusConnection:
+
+ @unittest.skipUnless(has_dbus, "no dbus running")
+ def test_register_object(self):
+ object_path = "/pygobject/Test"
+ interface_xml = """
+
+
+
+
+ """
+ interface_info = Gio.DBusNodeInfo.new_for_xml(interface_xml).interfaces[0]
+ bus = Gio.bus_get_sync(Gio.BusType.SESSION)
+
+ for args in (
+ (object_path, interface_info),
+ (object_path, interface_info, None, None, None)
+ ):
+ reg_id = bus.register_object(*args)
+ bus.unregister_object(reg_id)
+
+ for kwargs in (
+ {"object_path": object_path, "interface_info": interface_info},
+ {"object_path": object_path, "interface_info": interface_info,
+ "method_call_closure": None, "get_property_closure": None,
+ "set_property_closure": None},
+ ):
+ reg_id = bus.register_object(**kwargs)
+ bus.unregister_object(reg_id)
+
+ @unittest.skipUnless(has_dbus, "no dbus running")
+ def test_connection_invocation_ref_count(self):
+ """Invocation object should not leak a reference."""
+ invocation, errors = self.run_server(self.client_call)
+
+ assert not errors
+ assert invocation
+ assert invocation.ref_count == 1
+
+ def run_server(self, client_callback):
+ self.invocation = None
+ self.errors = []
+ self.loop = GLib.MainLoop()
+
+ def on_name_acquired(bus, name):
+ client_callback(bus)
+
+ self.reg_id = None
+ bus = Gio.bus_get_sync(Gio.BusType.SESSION)
+ owner_id = Gio.bus_own_name(Gio.BusType.SESSION,
+ "org.pygobject.Test",
+ Gio.BusNameOwnerFlags.NONE,
+ self.on_bus_acquired,
+ on_name_acquired,
+ self.on_name_lost)
+ try:
+ self.loop.run()
+ finally:
+ Gio.bus_unown_name(owner_id)
+ if self.reg_id:
+ bus.unregister_object(self.reg_id)
+
+ return (self.invocation, self.errors)
+
+ def on_name_lost(self, _bus, name):
+ self.errors.append(f"Name {name} lost")
+ self.loop.quit()
+
+ def on_bus_acquired(self, bus, name):
+ interface_xml = """
+
+
+
+
+ """
+ self.reg_id = bus.register_object("/pygobject/Test",
+ Gio.DBusNodeInfo.new_for_xml(interface_xml).interfaces[0],
+ self.on_incoming_method_call,
+ None,
+ None)
+
+ def on_incoming_method_call(self, bus, sender, object_path, interface_name, method_name, parameters, invocation):
+ invocation.return_value(GLib.Variant("()", ()))
+ self.invocation = invocation
+
+ def client_call(self, bus):
+
+ def call_done(obj, result):
+ try:
+ obj.call_finish(result)
+ finally:
+ self.loop.quit()
+
+ bus.call("org.pygobject.Test",
+ "/pygobject/Test",
+ "org.pygobject.Test",
+ "test",
+ parameters=None,
+ reply_type=None,
+ flags=Gio.DBusCallFlags.NONE,
+ timeout_msec=5000,
+ callback=call_done)
diff --git a/tests/test_gi.py b/tests/test_gi.py
index f59b3ec..0962f7b 100644
--- a/tests/test_gi.py
+++ b/tests/test_gi.py
@@ -2269,12 +2269,12 @@ def test_repr(self):
self.assertRegex(
repr(GIMarshallingTests.PointerStruct()),
r"")
+ r"\((void|GIMarshallingTestsPointerStruct) at 0x[^\s]+\)>")
self.assertRegex(
repr(GIMarshallingTests.SimpleStruct()),
r"")
+ r"\((void|GIMarshallingTestsSimpleStruct) at 0x[^\s]+\)>")
self.assertRegex(
repr(GIMarshallingTests.Union()),
@@ -2970,8 +2970,7 @@ def test_modules_list(self):
class TestParamSpec(unittest.TestCase):
- # https://bugzilla.gnome.org/show_bug.cgi?id=682355
- @unittest.expectedFailure
+
def test_param_spec_in_bool(self):
ps = GObject.param_spec_boolean('mybool', 'test-bool', 'boolblurb',
True, GObject.ParamFlags.READABLE)
diff --git a/tests/test_gobject.py b/tests/test_gobject.py
index fbc3bb7..1d29a7c 100644
--- a/tests/test_gobject.py
+++ b/tests/test_gobject.py
@@ -560,7 +560,7 @@ def transform_to(binding, value, user_data=None):
binding = self.source.bind_property('int_prop', self.target, 'int_prop',
GObject.BindingFlags.DEFAULT,
- transform_to, None, 'test-data')
+ transform_to, user_data='test-data')
binding = binding # PyFlakes
self.source.int_prop = 1
@@ -578,7 +578,7 @@ def transform_from(binding, value, user_data=None):
binding = self.source.bind_property('int_prop', self.target, 'int_prop',
GObject.BindingFlags.BIDIRECTIONAL,
- None, transform_from)
+ transform_from=transform_from)
binding = binding # PyFlakes
self.source.int_prop = 1
diff --git a/tests/test_overrides_gio.py b/tests/test_overrides_gio.py
index db09859..5a10bf0 100644
--- a/tests/test_overrides_gio.py
+++ b/tests/test_overrides_gio.py
@@ -1,10 +1,11 @@
-import random
+import os
import platform
+import random
import warnings
import pytest
-from gi.repository import Gio, GObject
+from gi.repository import Gio, GLib, GObject
from gi import PyGIWarning
@@ -358,3 +359,70 @@ def test_types_init_warn():
warnings.simplefilter('always')
t()
assert issubclass(warn[0].category, PyGIWarning)
+
+
+def test_file_fspath():
+ file, stream = Gio.File.new_tmp('TestGFile.XXXXXX')
+ content = b'hello\0world\x7F!'
+ stream.get_output_stream().write_bytes(GLib.Bytes(content))
+ stream.close()
+ path = file.peek_path()
+ assert isinstance(path, str)
+ fspath = file.__fspath__()
+ assert isinstance(fspath, str)
+ assert fspath == path
+
+ with open(file, 'rb') as file_like:
+ assert file_like.read() == content
+
+
+def test_file_fspath_with_no_path():
+ file = Gio.File.new_for_path('')
+ path = file.peek_path()
+ # In older versions of GLib, creating a GFile for an empty path will result
+ # in one representing the current pwd instead of a GDummyFile with no path.
+ if path is None:
+ with pytest.raises(TypeError):
+ file.__fspath__()
+ else:
+ assert path == file.__fspath__()
+ assert path == os.getcwd()
+
+
+@pytest.mark.skipif(
+ not hasattr(Gio.ListStore, "find_with_equal_func_full"),
+ reason="ListStore.find_with_equal_func_full() is available in Gio 2.74"
+)
+def test_list_store_find_with_equal_func():
+
+ def test(*user_data):
+ class TestObject(GObject.Object):
+ def __init__(self, val):
+ super().__init__()
+ self.val = val
+
+ NUM = 5
+ data = [TestObject(i) for i in range(NUM)]
+ list_store = Gio.ListStore()
+ for d in data:
+ list_store.append(d)
+
+ def equal_func(a, b, *data):
+ assert data == user_data
+ return a.val == b.val
+
+ for i in range(NUM):
+ res, position = (list_store.find_with_equal_func(
+ data[i], equal_func, *user_data
+ ))
+ assert res
+ assert position == i
+
+ not_in_list_store = TestObject(NUM + 1)
+ res, position = (list_store.find_with_equal_func(
+ not_in_list_store, equal_func, *user_data
+ ))
+ assert not res
+
+ test()
+ test((100, "data"))
diff --git a/tests/test_source.py b/tests/test_source.py
index 40e09cd..ead5b51 100644
--- a/tests/test_source.py
+++ b/tests/test_source.py
@@ -264,10 +264,11 @@ def finalize(s):
assert not self.dispatched
assert context.find_source_by_id(id_) is None
+ @unittest.skipIf(sys.implementation.name == "pypy", "PyPy doesn't __del__ immediately")
def test_python_unref_during_dispatch(self):
# Tests a Python derived Source which is free'd in the context of
# Python, while being dispatched
- # i.e. finalize is never called as the python object is destroyed
+ # NOTE: Finalize is explicitly called by __del__ for consistency
self.dispatched = False
self.finalized = False
diff --git a/tests/test_typeclass.py b/tests/test_typeclass.py
index 1f34a09..48f77ce 100644
--- a/tests/test_typeclass.py
+++ b/tests/test_typeclass.py
@@ -31,7 +31,7 @@ def test_coerce_from_class(self):
prop = GObject.ObjectClass.find_property(GIMarshallingTests.PropertiesObject,
'some-int')
- self.assertIsInstance(prop, GObject.GParamSpec)
+ self.assertIsInstance(prop, GObject.ParamSpec)
self.assertEqual(prop.name, 'some-int')
self.assertEqual(prop.value_type, GObject.TYPE_INT)
self.assertEqual(prop.owner_type,
@@ -41,7 +41,7 @@ def test_coerce_from_gtype(self):
gtype = GIMarshallingTests.PropertiesObject.__gtype__
prop = GObject.ObjectClass.find_property(gtype, 'some-int')
- self.assertIsInstance(prop, GObject.GParamSpec)
+ self.assertIsInstance(prop, GObject.ParamSpec)
self.assertEqual(prop.name, 'some-int')
self.assertEqual(prop.value_type, GObject.TYPE_INT)
self.assertEqual(prop.owner_type, gtype)
@@ -50,7 +50,7 @@ def test_coerce_from_instance(self):
obj = GIMarshallingTests.PropertiesObject()
prop = GObject.ObjectClass.find_property(obj, 'some-int')
- self.assertIsInstance(prop, GObject.GParamSpec)
+ self.assertIsInstance(prop, GObject.ParamSpec)
self.assertEqual(prop.name, 'some-int')
self.assertEqual(prop.value_type, GObject.TYPE_INT)
self.assertEqual(prop.owner_type, obj.__gtype__)