[
  {
    "path": ".bumpversion.cfg",
    "content": "[bumpversion]\ncurrent_version = 0.25.2\n\n[bumpversion:file:setup.py]\n\n[bumpversion:file:tomate/__init__.py]\n\n[bumpversion:file:tomate/ui/dialogs/about.py]\n\n[bumpversion:file:CHANGELOG.md]\nsearch = [Unreleased]\nreplace = {new_version}\n"
  },
  {
    "path": ".envfile",
    "content": "XDG_CONFIG_HOME=$PROJECT_DIR$/tests/data\nXDG_DATA_HOME=$PROJECT_DIR$/tests/data\nXDG_DATA_DIRS=$PROJECT_DIR$/tests/data\nPYTHONPATH=$PROJECT_DIR$:$PROJECT_DIR$/data/plugins\n"
  },
  {
    "path": ".github/workflows/lint.yml",
    "content": "name: lint\n\non:\n  push:\n    branches:\n      - main\n      - develop\n  pull_request:\n  workflow_dispatch: \n\njobs:\n  lint:\n    name: Run linter\n    runs-on: ubuntu-latest\n\n    steps:\n      - uses: actions/checkout@v3\n        \n      - uses: chartboost/ruff-action@v1"
  },
  {
    "path": ".github/workflows/release.yml",
    "content": "name: release\n\non:\n  push:\n    branches:\n      - master\n    paths:\n      - 'data/**'\n      - 'tomate/**'\n      - 'setup.py'\n      - '.bumpversion.cfg'\n\nconcurrency:\n  group: ${{ github.workflow }}\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n\n    steps:\n      - uses: actions/checkout@v3\n\n      - name: Trigger build\n        env:\n          TOKEN: ${{ secrets.OBS_TOKEN }}\n        run: make trigger-build"
  },
  {
    "path": ".github/workflows/test.yml",
    "content": "name: test\n\non:\n  push:\n    branches:\n      - main\n      - develop\n  pull_request: \n  workflow_dispatch: \n\njobs:\n  test:\n    name: Run tests\n    runs-on: ubuntu-latest\n    container:\n      image: eliostvs/tomate\n      volumes:\n        - ${{ github.workspace }}:/code\n    \n    steps:\n      - uses: actions/checkout@v3\n        \n      - name: Create mime database\n        run: |\n          make mime\n        \n      - name: Test\n        run: |\n          make test"
  },
  {
    "path": ".gitignore",
    "content": "*.egg\n*.egg-info\n*.log\n*.py[cod]\n*.pyc\n.coverage\nvenv/\n\n.idea/\n*.deb\n.cache\n.envrc\n.pytest_cache\ntests/data/mime/mime.cache\n"
  },
  {
    "path": ".pre-commit-config.yaml",
    "content": "repos:\n  - repo: https://github.com/psf/black\n    rev: 23.3.0\n    hooks:\n      - id: black\n  - repo: https://github.com/pre-commit/pre-commit-hooks\n    rev: v4.4.0\n    hooks:\n      - id: trailing-whitespace\n        types: [python]\n      - id: check-added-large-files\n      - id: check-ast\n      - id: check-merge-conflict\n      - id: debug-statements\n      - id: detect-private-key\n  - repo: local\n    hooks:\n      - id: test\n        name: Running tests\n        always_run: true\n        language: system\n        require_serial: true\n        stages: [push]\n        entry: make test"
  },
  {
    "path": "AUTHORS",
    "content": "Copyright (C) 2012 <Elio Esteves Duarte> <elio.esteves.duarte@gmail.com>"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Changelog\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),\nand this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n## 0.25.2\n\n### Fixed\n\n- Autopause plugin freezing the app.\n\n## 0.25.1\n\n### Removed\n\n- Dependency on python-tomate package.\n\n## 0.25.0\n\n### Changed\n\n- Rename template variable $type to $session\n\n## 0.24.0\n\n### Changed\n\n- Move player auto pause plugin to the tomate-gtk package\n\n## 0.23.1\n\n### Fixed\n\n- The script plugin name in the metadata file\n\n## 0.23.0\n\n### Changed\n\n- Move exec plugin to the tomate-gtk package\n- Rename exec plugin to script plugin\n- Move break screen plugin to the tomate-gtk package\n\n## 0.22.0\n\n### Changed\n\n- Move notify plugin to the tomate-gtk package\n\n## 0.21.0\n\n### Changed\n\n- Move alarm plugin to the tomate-gtk package\n\n## 0.20.0\n\n### Added\n\n- Start playing the ticking sound when the plugin is activated during a Pomodoro session\n\n## 0.19.1\n\n### Fixed\n\n- Missing core plugin and sound files\n\n## 0.19.0\n\n### Added\n\n- Ticking core plugin (without settings interface) \n- Audio player with volume control\n- `get_float` method to Config class\n\n## 0.18.1\n\n### Changed\n\n- Workaround setuptools auto discovery behaviour\n\n## 0.18.0\n\n### Fixed\n\n- Change STOCK_ICON labels to freedesktop names\n\n## 0.17.0\n\n### Changed\n\n- Remove the SessionEndPayload and start sending SessionPayload with the finished session data\n- Send SessionPayload instead of the SessionEndPayload in the Events.SESSION\\_END event\n\n### Added\n\n- Session triggers an Events.SESSION\\_CHANGE after the Events.SESSION\\_END\n\n## 0.16.0\n\n### Changed\n\n- Remove event type, sender, from the blinker receiver callback\n\n## 0.15.0\n\n### Added\n\n- Send Events.SESSION\\_READY when the main window is created to initialize widget components\n\n### Changed\n\n- Session.change receive a position argument instead of a keyword one\n\n## 0.14.0\n\n### Added\n\n- Read boolean values from config with the Config.get\\_bool method\n\n### Fixed\n\n- Save and send event after remove option\n\n## 0.13.0\n\n### Added\n\n- Countdown field to the timer and session payloads\n\n## 0.12.0\n\n### Fixed\n\n- Ratio rounding in Timer payload\n\n### Added\n\n- Shortcuts to change session to pomodoro (Ctrl+1), short break (Ctrl+2) and long break (Ctrl+3)\n- Shortcut to open settings\n- EndSessionPayload have the same fields of a SessionPayload plus the previous field that is the last SessionPayload\n\n### Changed\n\n- Session actions (start, stop, reset) keys in shortcuts section in the config\n- Join python-tomate and tomate-gtk projects\n- Timer, Session and App have their own state values instead of a shared Enum\n- Redesign the event API\n- Redesign the plugin API\n\n### Removed\n\n- Remove Session, Timer, Config, and View blinker.Signal objects\n- Remove State and Session enums\n\n## 0.11.0\n\n### Added\n\n- Session keyboard shortcuts\n\n## 0.10.0\n\n### Changed\n\n- The timer, session and settings now emit a payload object instead of a dictionary\n\n## 0.9.2\n\n### Fixed\n\n- Timer countdown blinking\n\n## 0.9.1\n\n### Changed\n\n- Arch linux installation instructions\n\n## 0.9.0\n\n### Changed\n\n- Change UI to use a headerbar widget instead of a toolbar\n- The Task enum was renamed to Sessions\n\n### Removed\n\n- Show notifications in then main widget (**show\\_message view interface**)\n\n## 0.8.0\n\n## Added\n\n- Show notifications in the main widget (**show\\_message** view interface)\n\n### Fixed\n\n- Reopen from command line\n\n### Changed\n\n- Arch installation instructions\n\n## 0.7.0\n\n### Added\n\n- Using wiring.scanning\n- Add plugin settings window\n  \n### Changed\n\n- Python 3 only\n\n## 0.6.0\n\n### Added\n\n- Add menu widget\n\n## 0.5.0\n\n### Fixed\n\n- Fix Gtk warnings\n\n## 0.4.0\n\n### Added\n\n- Using the new event system\n  \n### Removed\n\n- Remove appindicator3 dependency\n"
  },
  {
    "path": "COPYING",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM ubuntu:22.04\n\nENV DEBIAN_FRONTEND noninteractive\n\nRUN apt-get update -qq && apt-get install -y --no-install-recommends \\\n    dbus-x11 \\\n    gir1.2-appindicator3-0.1 \\\n    gir1.2-gdkpixbuf-2.0 \\\n    gir1.2-glib-2.0 \\\n    gir1.2-gstreamer-1.0 \\\n    gir1.2-gtk-3.0 \\\n    gir1.2-gtk-3.0 \\\n    gir1.2-notify-0.7 \\\n    gir1.2-playerctl-2.0 \\\n    gir1.2-unity-5.0 \\\n    git \\\n    gstreamer1.0-plugins-base \\\n    make \\\n    notification-daemon \\\n    python3-blinker \\\n    python3-dbus \\\n    python3-dbusmock \\\n    python3-gi \\\n    python3-pip \\\n    python3-pytest \\\n    python3-pytest-cov \\\n    python3-pytest-flake8 \\\n    python3-pytest-mock \\\n    python3-venusian \\\n    python3-wrapt \\\n    python3-xdg \\\n    python3-yapsy \\\n    xvfb \\\n    && apt-get clean && rm -rf /var/lib/apt/lists/*\n\nRUN pip3 install --no-cache-dir \\\n    black \\\n    isort \\\n    ruff \\\n    git+https://git@github.com/eliostvs/wiring.git@master\n\nWORKDIR /code\n\nENTRYPOINT [\"make\"]\n\nCMD [\"test\"]\n"
  },
  {
    "path": "LICENSE",
    "content": "License\n-------\n\nThis program is free software: you can redistribute it and/or modify it\nunder the terms of the GNU General Public License version 3, as published\nby the Free Software Foundation.\n\nThis program is distributed in the hope that it will be useful, but\nWITHOUT ANY WARRANTY; without even the implied warranties of\nMERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR\nPURPOSE.  See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along\nwith this program.  If not, see <http://www.gnu.org/licenses/>."
  },
  {
    "path": "MANIFEST.in",
    "content": "include AUTHORS COPYING CHANGELOG.md README.md\nrecursive-include data/applications *.desktop\nrecursive-include data/icons *.png *.svg"
  },
  {
    "path": "Makefile",
    "content": "ifeq ($(origin .RECIPEPREFIX), undefined)\n\t$(error This Make does not support .RECIPEPREFIX. Please use GNU Make 4.0 or later)\nendif\n\n.DEFAULT_GOAL = help\n.DELETE_ON_ERROR:\n.ONESHELL:\n.SHELLFLAGS   := -eu -o pipefail -c\n.SILENT:\nMAKEFLAGS     += --no-builtin-rules\nMAKEFLAGS     += --warn-undefined-variables\nSHELL         = bash\n\nDATAPATH     = $(CURDIR)/tests/data\nDOCKER_IMAGE = eliostvs/$(PACKAGE)\nOBS_API_URL  = https://api.opensuse.org/trigger/runservice\nPACKAGE      = tomate\nPYTHON       ?= python3\nPLUGINPATH   = $(CURDIR)/data/plugins\nPYTEST       ?= pytest-3\nPYTHONPATH   = PYTHONPATH=$(CURDIR):$(PLUGINPATH)\nTESTARGS     ?=\nVERSION      = `cat .bumpversion.cfg | grep current_version | awk '{print $$3}'`\nWORKDIR      = /code\nXDGPATH      = XDG_CONFIG_HOME=$(DATAPATH) XDG_DATA_HOME=$(DATAPATH) XDG_DATA_DIRS=$(DATAPATH)\n\nifeq ($(shell which xvfb-run 1> /dev/null && echo yes),yes)\n\tARGS = xvfb-run -a\nelse\n\tARGS ?=\nendif\n\n## help: print this help message\nhelp:\n\techo 'Usage:'\n\tsed -n 's/^##//p' ${MAKEFILE_LIST} | column -t -s ':' | sed -e 's/^/ /' | sort\n.PHONY: help\n\n## clean: clean development files\nclean:\n\tfind . \\( -iname \"__pycache__\" \\) -print0 | xargs -0 rm -rf\n\trm -rf .eggs *.egg-info/ .coverage build/ .cache .pytest_cache tests/data/mime/mime.cache venv\n.PHONY: clean\n\n## venv: create develop environment\nvenv:\n\tpython3 -m venv --system-site-package --upgrade-deps --prompt \".\" venv\n\tsource venv/bin/activate\n\tpip install \\\n\t\tblack \\\n\t\tisort \\\n\t\tpytest \\\n\t\tpytest-cov \\\n\t\tpytest-flake8 \\\n\t\tpytest-mock \\\n\t\tpython-dbusmock \\\n\t\truff \n\n## mime: generate test mine index\nmime: clean\n\t$(XDGPATH) update-mime-database tests/data/mime\n\trm -rf tests/data/mime/{image,aliases,generic-icons,globs,globs2,icons,magic,subclasses,treemagic,types,version,XMLnamespaces}\n.PHONY: mime\n\n## format: run code formatter\nformat:\n\tblack $(PACKAGE) tests/ $(PLUGINPATH)\n\tisort $(PACKAGE) tests/ $(PLUGINPATH)\n.PHONY: format\n\n## lint: run lint\nlint:\n\truff check $(ARGS) $(PACKAGE) tests/ $(PLUGINPATH)\n.PHONY: lint\n\n## test: run tests\ntest:\n\t$(XDGPATH) $(PYTHONPATH) $(ARGS) $(PYTEST) $(TESTARGS) -v --cov=$(PACKAGE)\n.PHONY: test\n\n## run: run app locally\nrun:\n\t$(XDGPATH) $(PYTHONPATH) TOMATE_DEBUG=true $(PYTHON) -m $(PACKAGE) -v\n.PHONY: run\n\n## release-[major|minor|patch]: create release\nrelease-%:\n\tgit flow init -d\n\t@grep -q '\\[Unreleased\\]' CHANGELOG.md || (echo 'Create the [Unreleased] section in the changelog first!' && exit)\n\tbumpversion --verbose --commit $*\n\tgit flow release start $(VERSION)\n\tGIT_MERGE_AUTOEDIT=no git flow release finish -m \"Merge branch release/$(VERSION)\" -T $(VERSION) $(VERSION) -p\n\n## trigger-build: trigger obs build\ntrigger-build:\n\tcurl -X POST -H \"Authorization: Token $(TOKEN)\" $(OBS_API_URL)\n.PHONY: trigger-build\n\n## docker: create docker image\ndocker:\n\tdocker built -t $(DOCKER_IMAGE) .\n\n## docker: push image to docker hub\ndocker-push:\n\tdocker image push $(DOCKER_IMAGE):latest\n\n## docker-run: run app inside\ndocker-run:\n\tdocker run --rm -it -e DISPLAY --net=host \\\n\t-v $(CURDIR):/$(WORKDIR) \\\n\t-v $(HOME)/.Xauthority:/root/.Xauthority \\\n\t$(DOCKER_IMAGE) run\n.PHONY: docker-run\n\n## docker-test: run tests inside docker\ndocker-test:\n\tdocker run --rm -it -v $(CURDIR):$(WORKDIR) --workdir $(WORKDIR) $(DOCKER_IMAGE) mime test\n.PHONY: docker-test\n\n## docker-enter: open terminal inside docker environment\ndocker-enter:\n\tdocker run --rm -v $(CURDIR):$(WORKDIR) -it --workdir $(WORKDIR) --entrypoint=\"bash\" $(DOCKER_IMAGE)\n.PHONY: docker-enter\n"
  },
  {
    "path": "README.md",
    "content": "# Tomate\n\nA Pomodoro timer written in Gtk3 and Python for Linux desktops.\n\n## About the technique\n\nThe Pomodoro Technique® is a management technique developed by Francesco Cirillo that helps you keep focused.\nRead more about it at the [official website](http://pomodorotechnique.com/).\n\nPomodoro Technique® and Pomodoro™ are registered and filed trademarks owned by Francesco Cirillo.\nTomate is not affiliated by, associated with nor endorsed by Francesco Cirillo.\n\n## Screenshots\n\n![main screen](docs/img/main-screen.png)\n\n![preference duration](docs/img/preference-duration.png)\n\n![preference extension](docs/img/preference-extension.png)\n\n## Installation\n\n### Ubuntu 20.04+\n\nIf you have installed the program using the **old ppa repository** uninstall the old version first.\nIf you use an Ubuntu-based distro, such as Mint, manually set the **RELEASE** variable to the Ubuntu version number, such as 16.04, rather than running the sed script bellow.\n\n```bash\nRELEASE=`sed -n 's/VERSION_ID=\"\\(.*\\)\"/\\1/p' /etc/os-release`\ncurl -fsSL \"http://download.opensuse.org/repositories/home:/eliostvs:/tomate/xUbuntu_$RELEASE/Release.key\" | gpg --dearmor | sudo tee /etc/apt/trusted.gpg.d/tomate.gpg > /dev/null\necho \"deb http://download.opensuse.org/repositories/home:/eliostvs:/tomate/xUbuntu_$RELEASE/ ./\" | sudo tee /etc/apt/sources.list.d/tomate.list\nsudo apt-get update && sudo apt-get install tomate-gtk\n```\n\n### Debian 10+\n\n```bash\nRELEASE=`sed -n 's/VERSION_ID=\"\\(.*\\)\"/\\1/p' /etc/os-release`\ncurl -fsSL \"http://download.opensuse.org/repositories/home:/eliostvs:/tomate/Debian_$RELEASE/Release.key\" | gpg --dearmor | sudo tee /etc/apt/trusted.gpg.d/tomate.gpg > /dev/null\necho \"deb http://download.opensuse.org/repositories/home:/eliostvs:/tomate/Debian_$RELEASE/ ./\" | sudo tee /etc/apt/sources.list.d/tomate.list\nsudo apt-get update && sudo apt-get install tomate-gtk\n```\n\n### Opensuse Tumbleweed\n\n```bash\nsudo zypper ar -f http://download.opensuse.org/repositories/home:/eliostvs:/tomate/openSUSE_Tumbleweed/home:eliostvs:tomate.repo\nsudo zypper install tomate-gtk\n```\n\n### Fedora 36+\n\n```bash\nRELEASE=`cat /etc/fedora-release | grep -o '[0-9][0-9]*'`\nsudo dnf config-manager --add-repo http://download.opensuse.org/repositories/home:/eliostvs:/tomate/Fedora_$RELEASE/home:eliostvs:tomate.repo\nsudo dnf install tomate-gtk\n```\n\n### Arch\n\nThe packages are available in [aur repository](https://aur.archlinux.org/packages/tomate-gtk/)\n\n## Plugins\n\n### Pre-installed\n\n- [Alarm][alarm-plugin] Play a alarm when the timer end\n- [Ticking][ticking-plugin] Play a ticking sound during a work session\n- [Notify][notify-plugin] Display notification end the timer start, stop and end\n- [Script][script-plugin] Run scripts when the timer start, stop or end\n- [Break Screen][breakscreen-plugin] Block all screens during break tim\n- [Auto Pause][autopause-plugin] Pause all the playing media when a work session ends\n\n### External\n\n- [Indicator][indicator-plugin] Displays a countdown icon in the systray (uses libappindicator)\n- [StatusIcon][statusicon-plugin] Displays a countdown icon in the systray (old method for creating a systray with GNOME)\n- [StatusNotifierItem][statusnotifieritem-plugin] Displays a countdown icon in the systray (freedesktop standard for creating a systray)\n- [Launcher][launcher-plugin] Shows the timer countdown and the total of sessions in the launcher (ubuntu only)\n\n---\n\n[alarm-plugin]: ./data/plugins/alarm.plugin\n[ticking-plugin]: ./data/plugins/ticking.plugin\n[notify-plugin]: ./data/plugins/notify.plugin\n[script-plugin]: ./data/plugins/script.plugin\n[breakscreen-plugin]: ./data/plugins/breakscreen.plugin\n[autopause-plugin]: ./data/plugins/autopause.plugin\n[indicator-plugin]: https://github.com/eliostvs/tomate-indicator-plugin\n[statusicon-plugin]: https://github.com/eliostvs/tomate-statusicon-plugin\n[launcher-plugin]: https://github.com/eliostvs/tomate-launcher-plugin\n[statusnotifieritem-plugin]: https://github.com/eliostvs/tomate-statusnotifieritem-plugin\n"
  },
  {
    "path": "data/applications/tomate-gtk.desktop",
    "content": "[Desktop Entry]\nName=Tomate\nGenericName=Clock\nComment=Gtk version from Tomate pomodoro timer.\nCategories=Utility;Clock;\nExec=tomate-gtk\nIcon=tomate\nTerminal=false\nType=Application\n"
  },
  {
    "path": "data/plugins/alarm.plugin",
    "content": "[Core]\nName = Alarm\nModule = alarm\n\n[Documentation]\nAuthor = Elio Esteves Duarte\nVersion = 0.12.0\nWebsite = https://github.com/eliostvs/tomate-gtk\nDescription = Plays alarm at session end"
  },
  {
    "path": "data/plugins/alarm.py",
    "content": "import logging\nfrom locale import gettext as _\nfrom os import path\nfrom urllib.parse import urlparse\n\nimport gi\nfrom wiring import Graph\n\ngi.require_version(\"Gtk\", \"3.0\")\n\nfrom gi.repository import Gtk\n\nimport tomate.pomodoro.plugin as plugin\nfrom tomate.audio import GStreamerPlayer\nfrom tomate.pomodoro import Bus, Config, Events, on, suppress_errors\n\nlogger = logging.getLogger(__name__)\n\nSECTION_NAME = \"alarm_plugin\"\nOPTION_NAME = \"uri\"\n\n\nclass AlarmPlugin(plugin.Plugin):\n    has_settings = True\n\n    @suppress_errors\n    def __init__(self):\n        super().__init__()\n        self.config = None\n        self.player = None\n\n    def configure(self, bus: Bus, graph: Graph) -> None:\n        super().configure(bus, graph)\n        self.config = graph.get(\"tomate.config\")\n\n    @suppress_errors\n    def activate(self) -> None:\n        super().activate()\n        logger.debug(\"action=activate uri=%s volume=%f\", self.audio_path, self.volume)\n        self.player = GStreamerPlayer(repeat=False)\n        self.player.file = self.audio_path\n        self.player.volume = self.volume\n\n    @suppress_errors\n    def deactivate(self) -> None:\n        super().deactivate()\n        logger.debug(\"action=deactivate\")\n\n        if self.player:\n            self.player.stop()\n\n    @suppress_errors\n    @on(Events.SESSION_END)\n    def on_end(self, **__) -> None:\n        logger.debug(\"action=on_end\")\n        if self.player:\n            self.player.play()\n\n    @property\n    def audio_path(self) -> str:\n        return self.config.get(SECTION_NAME, OPTION_NAME, fallback=self.config.media_uri(\"alarm.ogg\"))\n\n    @property\n    def volume(self) -> float:\n        return self.config.get_float(SECTION_NAME, \"volume\", fallback=1.0)\n\n    def settings_window(self, toplevel: Gtk.Dialog) -> \"SettingsDialog\":\n        return SettingsDialog(self.config, toplevel)\n\n\nclass SettingsDialog:\n    def __init__(self, config: Config, toplevel: Gtk.Dialog):\n        self.config = config\n        self.widget = self.create_dialog(toplevel)\n\n    def create_dialog(self, toplevel: Gtk.Dialog) -> Gtk.Dialog:\n        dialog = Gtk.Dialog(\n            border_width=12,\n            modal=True,\n            resizable=False,\n            title=_(\"Preferences\"),\n            transient_for=toplevel,\n            window_position=Gtk.WindowPosition.CENTER_ON_PARENT,\n        )\n        dialog.add_button(_(\"Close\"), Gtk.ResponseType.CLOSE)\n        dialog.connect(\"response\", lambda widget, _: widget.destroy())\n        dialog.set_size_request(350, -1)\n        dialog.get_content_area().add(self.create_options())\n        return dialog\n\n    def create_options(self) -> Gtk.Grid:\n        custom_audio = self.config.get(SECTION_NAME, OPTION_NAME, fallback=\"\")\n\n        grid = Gtk.Grid(column_spacing=12, row_spacing=12, margin_bottom=12, margin_top=12)\n        label = Gtk.Label(label=_(\"Custom:\"), hexpand=True, halign=Gtk.Align.END)\n        grid.attach(label, 0, 0, 1, 1)\n\n        entry = self.create_custom_alarm_input(custom_audio)\n        grid.attach(entry, 0, 1, 4, 1)\n\n        switch = self.create_custom_alarm_switch(custom_audio, entry)\n        grid.attach_next_to(switch, label, Gtk.PositionType.RIGHT, 1, 1)\n\n        return grid\n\n    def create_custom_alarm_input(self, custom_audio) -> Gtk.Entry:\n        entry = Gtk.Entry(\n            editable=False,\n            hexpand=True,\n            name=\"custom_entry\",\n            secondary_icon_activatable=True,\n            secondary_icon_name=Gtk.STOCK_FILE,\n            sensitive=bool(custom_audio),\n            text=custom_audio,\n        )\n        entry.connect(\"icon-press\", self.select_custom_alarm)\n        entry.connect(\"notify::text\", self.custom_alarm_changed)\n        return entry\n\n    def create_custom_alarm_switch(self, custom_audio, entry) -> Gtk.Switch:\n        switch = Gtk.Switch(\n            hexpand=True,\n            halign=Gtk.Align.START,\n            active=bool(custom_audio),\n            name=\"custom_switch\",\n        )\n        switch.connect(\"notify::active\", self.custom_alarm_toggle, entry)\n        return switch\n\n    def select_custom_alarm(self, entry: Gtk.Entry, *_) -> None:\n        dialog = self.create_file_chooser(self.dirname(entry.props.text))\n        response = dialog.run()\n\n        if response == Gtk.ResponseType.OK:\n            entry.set_text(dialog.get_uri())\n\n        dialog.destroy()\n\n    def dirname(self, audio_path: str) -> str:\n        return path.dirname(urlparse(audio_path).path) if audio_path else path.expanduser(\"~\")\n\n    def create_file_chooser(self, current_folder: str) -> Gtk.FileChooserDialog:\n        dialog = Gtk.FileChooserDialog(\n            _(\"Please choose a file\"),\n            self.widget,\n            Gtk.FileChooserAction.OPEN,\n            (\n                Gtk.STOCK_CANCEL,\n                Gtk.ResponseType.CANCEL,\n                Gtk.STOCK_OPEN,\n                Gtk.ResponseType.OK,\n            ),\n        )\n        dialog.add_filter(self.create_filter(\"audio/mp3\", \"audio/mpeg\"))\n        dialog.add_filter(self.create_filter(\"audio/ogg\", \"audio/ogg\"))\n        dialog.set_current_folder(current_folder)\n        return dialog\n\n    @staticmethod\n    def create_filter(name: str, mime_type: str) -> Gtk.FileFilter:\n        mime_type_filter = Gtk.FileFilter()\n        mime_type_filter.set_name(name)\n        mime_type_filter.add_mime_type(mime_type)\n        return mime_type_filter\n\n    def custom_alarm_changed(self, entry: Gtk.Entry, _) -> None:\n        custom_alarm = entry.props.text\n\n        if custom_alarm:\n            logger.debug(\"action=set_option section=%s option=%s value\", SECTION_NAME, OPTION_NAME)\n            self.config.set(SECTION_NAME, OPTION_NAME, custom_alarm)\n        else:\n            logger.debug(\"action=remove_option section=%s option=%s\", SECTION_NAME, OPTION_NAME)\n            self.config.remove(SECTION_NAME, OPTION_NAME)\n\n    @staticmethod\n    def custom_alarm_toggle(switch: Gtk.Switch, _, entry: Gtk.Entry) -> None:\n        if switch.props.active:\n            entry.set_properties(sensitive=True)\n        else:\n            entry.set_properties(text=\"\", sensitive=False)\n\n    def run(self) -> Gtk.Dialog:\n        self.widget.show_all()\n        return self.widget\n"
  },
  {
    "path": "data/plugins/autopause.plugin",
    "content": "[Core]\nName = Auto Pause\nModule = autopause\n\n[Documentation]\nAuthor = Elio Esteves Duarte\nVersion = 0.2.0\nWebsite =  https://github.com/eliostvs/tomate-gtk\nDescription = Pauses all running media players when the session ends\n"
  },
  {
    "path": "data/plugins/autopause.py",
    "content": "import logging\n\nimport gi\n\nimport tomate.pomodoro.plugin as plugin\nfrom tomate.pomodoro import Events, on, suppress_errors\n\ngi.require_version(\"Playerctl\", \"2.0\")\n\nfrom gi.repository import GLib, Playerctl\n\nlogger = logging.getLogger(__name__)\n\n\nclass AutoPausePlugin(plugin.Plugin):\n    @suppress_errors\n    @on(Events.SESSION_END)\n    def on_session_end(self, **_):\n        self.pause()\n\n    def pause(self) -> None:\n        try:\n            for player in Playerctl.list_players():\n                instance = Playerctl.Player.new_for_source(player.instance, player.source)\n                logger.debug(\n                    \"action=check player=%s status=%s\",\n                    player.name,\n                    instance.props.playback_status,\n                )\n\n                # pause is not an idempotent operation, it can start a paused player :(\n                # so we need to check if the player is running first\n                if instance.props.playback_status == Playerctl.PlaybackStatus.PLAYING:\n                    instance.pause()\n                    logger.debug(\"action=paused player=%s\", player.name)\n\n        except GLib.Error as err:\n            logger.error(\"action=failed error='%s'\", err)\n"
  },
  {
    "path": "data/plugins/breakscreen.plugin",
    "content": "[Core]\nName = Break Screen\nModule = breakscreen\n\n[Documentation]\nAuthor = Elio Esteves Duarte\nVersion = 0.7.0\nWebsite = https://github.com/eliostva/tomate-gtk\nDescription = Shows a full screen window which prevents users from using the computer during a break\n"
  },
  {
    "path": "data/plugins/breakscreen.py",
    "content": "import logging\nfrom collections import namedtuple\nfrom locale import gettext as _\nfrom typing import Dict\n\nimport gi\n\ngi.require_version(\"Gtk\", \"3.0\")\ngi.require_version(\"Gdk\", \"3.0\")\n\nfrom gi.repository import Gdk, GLib, Gtk\n\nimport tomate.pomodoro.plugin as plugin\nfrom tomate.pomodoro import (\n    Config,\n    ConfigPayload,\n    Events,\n    Session,\n    SessionPayload,\n    SessionType,\n    Subscriber,\n    Timer,\n    TimerPayload,\n    on,\n    suppress_errors,\n)\n\nlogger = logging.getLogger(__name__)\n\nSECTION_NAME = \"break_screen\"\nSKIP_BREAK_OPTION = \"skip_break\"\nAUTO_START_OPTION = \"auto_start\"\n\n\nclass Monitor(namedtuple(\"Monitor\", \"number geometry\")):\n    @property\n    def x(self) -> int:\n        return self.geometry.x\n\n    @property\n    def y(self) -> int:\n        return self.geometry.y\n\n    @property\n    def width(self) -> int:\n        return self.geometry.width\n\n    @property\n    def height(self) -> int:\n        return self.geometry.height\n\n\nclass BreakScreen(Subscriber):\n    def __init__(self, monitor: Monitor, session: Session, config: Config):\n        logger.debug(\"action=init_screen monitor=%s\", monitor)\n\n        self.monitor = monitor\n        self.session = session\n        self.options = self.create_options(config)\n        self.countdown = Gtk.Label(label=\"00:00\", name=\"countdown\")\n        self.skip_button = self.create_button()\n        content = self.create_content_area(self.countdown, self.skip_button)\n        self.widget = self.create_window(self.monitor, content)\n\n    def create_options(self, config) -> Dict[str, bool]:\n        return {\n            SKIP_BREAK_OPTION: config.get_bool(SECTION_NAME, SKIP_BREAK_OPTION, fallback=False),\n            AUTO_START_OPTION: config.get_bool(SECTION_NAME, AUTO_START_OPTION, fallback=False),\n        }\n\n    def create_button(self) -> Gtk.Button:\n        logger.debug(\"action=create_skip_button visibile=%s\", self.options[SKIP_BREAK_OPTION])\n        button = Gtk.Button(label=_(\"Skip\"), name=\"skip\", visible=self.options[SKIP_BREAK_OPTION], no_show_all=True)\n        button.connect(\"clicked\", self.skip_break)\n        button.grab_focus()\n        return button\n\n    def skip_break(self, _) -> None:\n        logger.debug(\"action=skip_break\")\n        self.session.stop()\n        self.session.change(SessionType.POMODORO)\n\n    def create_content_area(self, countdown: Gtk.Label, skip_button: Gtk.Button) -> Gtk.Box:\n        content = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)\n        content.pack_start(countdown, False, False, 0)\n        content.pack_start(skip_button, False, False, 0)\n\n        space = Gtk.Box(halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER)\n        space.pack_start(content, True, True, 0)\n        return space\n\n    def create_window(self, monitor: Monitor, box: Gtk.Box) -> Gtk.Window:\n        window = Gtk.Window(\n            can_focus=False,\n            decorated=False,\n            deletable=False,\n            focus_on_map=False,\n            gravity=Gdk.Gravity.CENTER,\n            name=\"breakscreen\",\n            skip_taskbar_hint=True,\n            urgency_hint=True,\n        )\n        window.set_visual(window.get_screen().get_rgba_visual())\n        window.stick()\n        window.set_keep_above(True)\n        window.fullscreen()\n        window.move(monitor.x, monitor.y)\n        window.resize(monitor.width, monitor.height)\n        window.add(box)\n        return window\n\n    @on(Events.SESSION_START)\n    def on_session_start(self, payload=SessionPayload) -> None:\n        logger.debug(\"action=session_start monitor=%d session=%s\", self.monitor.number, payload.type)\n\n        if payload.type != SessionType.POMODORO:\n            self.countdown.set_text(payload.countdown)\n            self.widget.show_all()\n\n    @on(Events.SESSION_INTERRUPT)\n    def on_session_interrupt(self, **__) -> None:\n        logger.debug(\"action=session_start monitor=%d\", self.monitor.number)\n        self.widget.hide()\n\n    @on(Events.SESSION_END)\n    def on_session_end(self, payload: SessionPayload) -> None:\n        logger.debug(\n            \"action=session_end monitor=%d auto_start=%s session_type=%s\",\n            self.monitor.number,\n            self.auto_start,\n            payload.type,\n        )\n\n        if payload.type == SessionType.POMODORO and self.auto_start:\n            GLib.timeout_add_seconds(Timer.ONE_SECOND, self._start_session)\n        else:\n            self.widget.hide()\n\n    def _start_session(self) -> bool:\n        self.session.start()\n        return False\n\n    @property\n    def auto_start(self) -> bool:\n        return self.options[AUTO_START_OPTION]\n\n    @on(Events.TIMER_UPDATE)\n    def on_timer_update(self, payload: TimerPayload) -> None:\n        logger.debug(\"action=update_countdown monitor=%s countdown=%s\", payload.countdown, self.monitor.number)\n        self.countdown.set_text(payload.countdown)\n\n    @on(Events.CONFIG_CHANGE)\n    def on_settings_change(self, payload: ConfigPayload) -> None:\n        if payload.section != SECTION_NAME:\n            return\n\n        logger.debug(\n            \"action=change_option monitor=%d config=%s option=%s\",\n            self.monitor.number,\n            payload.action,\n            payload.option,\n        )\n        self.options[payload.option] = payload.action == \"set\"\n        self.skip_button.props.visible = self.options[SKIP_BREAK_OPTION]\n\n\nclass SettingsDialog:\n    def __init__(self, config: Config, toplevel):\n        self.options = {SKIP_BREAK_OPTION: False, AUTO_START_OPTION: False}\n        self.config = config\n        self.widget = self.create_dialog(toplevel)\n\n    def create_dialog(self, toplevel) -> Gtk.Dialog:\n        dialog = Gtk.Dialog(\n            border_width=12,\n            modal=True,\n            resizable=False,\n            title=_(\"Preferences\"),\n            transient_for=toplevel,\n            window_position=Gtk.WindowPosition.CENTER_ON_PARENT,\n        )\n        dialog.add_button(_(\"Close\"), Gtk.ResponseType.CLOSE)\n        dialog.connect(\"response\", lambda widget, _: widget.destroy())\n        dialog.set_size_request(350, -1)\n        dialog.get_content_area().add(self.create_options())\n        return dialog\n\n    def create_options(self):\n        grid = Gtk.Grid(column_spacing=12, row_spacing=12, margin_bottom=12, margin_top=12)\n        self.create_option(grid, 0, _(\"Auto start:\"), AUTO_START_OPTION)\n        self.create_option(grid, 1, _(\"Skip break:\"), SKIP_BREAK_OPTION)\n        return grid\n\n    def run(self):\n        self.widget.show_all()\n        return self.widget\n\n    def create_option(self, grid: Gtk.Grid, row: int, label: str, option):\n        active = self.config.get_bool(SECTION_NAME, option, fallback=False)\n        self.options[option] = active\n\n        label = Gtk.Label(label=_(label), hexpand=True, halign=Gtk.Align.END)\n        grid.attach(label, 0, row, 1, 1)\n\n        switch = Gtk.Switch(hexpand=True, halign=Gtk.Align.START, name=option, active=active)\n        switch.connect(\"notify::active\", self.on_option_change, option)\n        grid.attach_next_to(switch, label, Gtk.PositionType.RIGHT, 1, 1)\n\n    def on_option_change(self, switch: Gtk.Switch, _, option: str):\n        self.options[option] = switch.props.active\n\n        if switch.props.active:\n            self.config.set(SECTION_NAME, option, \"true\")\n        else:\n            logger.debug(\"action=remove_option name=%s\", option)\n            self.config.remove(SECTION_NAME, option)\n\n\nclass BreakScreenPlugin(plugin.Plugin):\n    has_settings = True\n\n    @suppress_errors\n    def __init__(self, display=Gdk.Display.get_default()):\n        super().__init__()\n        self.display = display\n        self.screens = []\n        self.configure_style()\n\n    @staticmethod\n    def configure_style():\n        style = b\"\"\"\n        #breakscreen {\n            background-color: #1c1c1c;\n        }\n\n        #skip {\n            color: white;\n            font-size: 1.5em;\n            font-weight: 900;\n            background: transparent;\n            border-color: white;\n            border-image: none;\n            border-radius: 25px;\n            border-width: 2px;\n            padding-bottom: 10px;\n            padding-left: 25px;\n            padding-right: 25px;\n            padding-top: 10px;\n        }\n\n        #skip:hover, #skip:active {\n            background: white;\n            color: black;\n        }\n\n        #countdown {\n            font-size: 10em;\n        }\n        \"\"\"\n        style_provider = Gtk.CssProvider()\n        style_provider.load_from_data(style)\n        Gtk.StyleContext.add_provider_for_screen(\n            Gdk.Screen.get_default(), style_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION\n        )\n\n    @suppress_errors\n    def activate(self):\n        super().activate()\n\n        for monitor in range(self.display.get_n_monitors()):\n            geometry = self.display.get_monitor(monitor).get_geometry()\n            screen = BreakScreen(\n                Monitor(monitor, geometry), self.graph.get(\"tomate.session\"), self.graph.get(\"tomate.config\")\n            )\n            screen.connect(self.bus)\n            self.screens.append(screen)\n\n    @suppress_errors\n    def deactivate(self):\n        super().deactivate()\n\n        for screen in self.screens:\n            screen.disconnect(self.bus)\n            screen.widget.destroy()\n\n        del self.screens[:]\n\n    def settings_window(self, toplevel) -> SettingsDialog:\n        return SettingsDialog(self.graph.get(\"tomate.config\"), toplevel)\n"
  },
  {
    "path": "data/plugins/notify.plugin",
    "content": "[Core]\nName = Notify\nModule = notify\n\n[Documentation]\nAuthor = Elio Esteves Duarte\nVersion = 0.15.0\nWebsite = https://github.com/eliostvs/tomate-gtk\nDescription = Shows screen notifications"
  },
  {
    "path": "data/plugins/notify.py",
    "content": "import logging\nfrom locale import gettext as _\nfrom typing import Tuple\n\nimport gi\nfrom wiring import Graph\n\nimport tomate.pomodoro.plugin as plugin\nfrom tomate.pomodoro import (\n    Bus,\n    Events,\n    SessionPayload,\n    SessionType,\n    on,\n    suppress_errors,\n)\n\ngi.require_version(\"Notify\", \"0.7\")\n\nfrom gi.repository import Notify\n\nlogger = logging.getLogger(__name__)\n\n\nclass NotifyPlugin(plugin.Plugin):\n    messages = {\n        SessionType.POMODORO: {\"title\": _(\"Pomodoro\"), \"content\": _(\"Get back to work!\")},\n        SessionType.SHORT_BREAK: {\"title\": _(\"Short Break\"), \"content\": _(\"It's coffee time!\")},\n        SessionType.LONG_BREAK: {\"title\": _(\"Long Break\"), \"content\": _(\"Step away from the machine!\")},\n    }\n\n    @suppress_errors\n    def __init__(self):\n        super().__init__()\n        self.config = None\n        self.notification = Notify.Notification.new(\"tomate-notify-plugin\")\n\n    def configure(self, bus: Bus, graph: Graph) -> None:\n        super().configure(bus, graph)\n        self.config = graph.get(\"tomate.config\")\n\n    @suppress_errors\n    def activate(self):\n        super().activate()\n        Notify.init(\"tomate-notify-plugin\")\n\n    @suppress_errors\n    def deactivate(self):\n        super().deactivate()\n        Notify.uninit()\n\n    @on(Events.SESSION_START)\n    def on_session_started(self, payload: SessionPayload):\n        self.show_notification(*self.get_message(payload.type))\n\n    @on(Events.SESSION_END)\n    def on_session_finished(self, **__):\n        self.show_notification(title=\"The time is up!\")\n\n    @on(Events.SESSION_INTERRUPT)\n    def on_session_stopped(self, **__):\n        self.show_notification(title=\"Session stopped manually\")\n\n    def get_message(self, session: SessionType) -> Tuple[str, str]:\n        return (\n            self.messages[session][\"title\"],\n            self.messages[session][\"content\"],\n        )\n\n    @suppress_errors\n    def show_notification(self, title, message=\"\"):\n        self.notification.update(title, message, self.icon_path)\n        result = self.notification.show()\n\n        logger.debug(\n            'action=show title=\"%s\" message=\"%s\" success=%r icon=%s',\n            title,\n            message,\n            result,\n            self.icon_path,\n        )\n\n    @property\n    def icon_path(self):\n        return self.config.icon_path(\"tomate\", 32)\n"
  },
  {
    "path": "data/plugins/script.plugin",
    "content": "[Core]\nName = Script\nModule = script\n\n[Documentation]\nAuthor = Elio Esteves Duarte\nVersion = 0.2.0\nWebsite = https://github.com/eliostvs/tomate-gtk\nDescription = Run scripts when a session starts, stops or finishes\n"
  },
  {
    "path": "data/plugins/script.py",
    "content": "import locale\nimport logging\nimport subprocess\nfrom locale import gettext as _\nfrom string import Template\nfrom typing import Dict, Optional\n\nimport gi\nfrom wiring import Graph\n\ngi.require_version(\"Gtk\", \"3.0\")\n\nfrom gi.repository import Gtk\n\nimport tomate.pomodoro.plugin as plugin\nfrom tomate.pomodoro import Bus, Config, Events, SessionPayload, on, suppress_errors\n\nlocale.textdomain(\"tomate\")\nlogger = logging.getLogger(__name__)\n\nSECTION_NAME = \"script_plugin\"\nSTART_OPTION = \"start_command\"\nSTOP_OPTION = \"stop_command\"\nFINISH_OPTION = \"finish_command\"\n\n\ndef strip_space(command: Optional[str]) -> Optional[str]:\n    if command is not None:\n        return command.strip()\n\n\nclass ScriptPlugin(plugin.Plugin):\n    has_settings = True\n\n    @suppress_errors\n    def __init__(self):\n        super().__init__()\n        self.config = None\n\n    def configure(self, bus: Bus, graph: Graph) -> None:\n        super().configure(bus, graph)\n        self.config = graph.get(\"tomate.config\")\n\n    @suppress_errors\n    @on(Events.SESSION_START)\n    def on_session_started(self, payload: SessionPayload):\n        return self.call_command(START_OPTION, Events.SESSION_START, payload)\n\n    @suppress_errors\n    @on(Events.SESSION_INTERRUPT)\n    def on_session_interrupted(self, payload: SessionPayload):\n        return self.call_command(STOP_OPTION, Events.SESSION_INTERRUPT, payload)\n\n    @suppress_errors\n    @on(Events.SESSION_END)\n    def on_session_end(self, payload: SessionPayload):\n        return self.call_command(FINISH_OPTION, Events.SESSION_END, payload)\n\n    def call_command(self, section, event: Events, payload: SessionPayload):\n        command = self.read_command(section, {\"event\": event.name, \"session\": payload.type.name})\n        if command:\n            try:\n                logger.debug(\"action=call-command cmd=%s\", command)\n                subprocess.run(command, shell=True, check=True)\n                return True\n            except subprocess.CalledProcessError as error:\n                logger.debug(\n                    \"action=run-command-failed event=%s cmd=%s output=%s return-code=%s\",\n                    event,\n                    error.cmd,\n                    error.output,\n                    error.returncode,\n                )\n        return False\n\n    def read_command(self, section: str, repl: Dict[str, str]) -> Optional[str]:\n        template = strip_space(self.config.get(SECTION_NAME, section))\n        return self._interpolate(template, repl) if template else None\n\n    @staticmethod\n    def _interpolate(template: str, replacements: Dict[str, str]) -> str:\n        return Template(template).substitute(**replacements)\n\n    def settings_window(self, toplevel):\n        return SettingsDialog(self.config, toplevel)\n\n\nclass SettingsDialog:\n    def __init__(self, config: Config, toplevel):\n        self.config = config\n        self.widget = self.create_dialog(toplevel)\n\n    def create_dialog(self, toplevel) -> Gtk.Dialog:\n        dialog = Gtk.Dialog(\n            border_width=12,\n            modal=True,\n            resizable=False,\n            title=_(\"Preferences\"),\n            transient_for=toplevel,\n            window_position=Gtk.WindowPosition.CENTER_ON_PARENT,\n        )\n        dialog.add_button(_(\"Close\"), Gtk.ResponseType.CLOSE)\n        dialog.connect(\"response\", lambda widget, _: widget.destroy())\n        dialog.set_size_request(350, -1)\n        dialog.get_content_area().add(self.create_options())\n        return dialog\n\n    def create_options(self):\n        grid = Gtk.Grid(column_spacing=12, row_spacing=12, margin_bottom=12)\n        self.create_section(grid)\n        self.create_option(grid, 3, _(\"On start:\"), START_OPTION)\n        self.create_option(grid, 5, _(\"On stop:\"), STOP_OPTION)\n        self.create_option(grid, 7, _(\"On finish:\"), FINISH_OPTION)\n        return grid\n\n    @staticmethod\n    def create_section(grid: Gtk.Grid) -> None:\n        title = Gtk.Label(\n            label=\"<b>{0}</b>\".format(_(\"Scripts\")),\n            halign=Gtk.Align.START,\n            hexpand=True,\n            use_markup=True,\n        )\n        grid.attach(title, 0, 0, 1, 1)\n\n        help_text = Gtk.Label(\n            label=_(\n                \"You can use the session and event names in your script using the\"\n                \" <i>$session</i> and <i>$event</i> template variables.\"\n            ),\n            halign=Gtk.Align.CENTER,\n            margin_bottom=24,\n            hexpand=False,\n            wrap=True,\n            max_width_chars=40,\n            use_markup=True,\n        )\n        grid.attach(help_text, 0, 1, 4, 1)\n\n    def run(self) -> None:\n        self.widget.show_all()\n        return self.widget\n\n    def create_option(self, grid: Gtk.Grid, row: int, label: str, option: str) -> None:\n        command = self.config.get(SECTION_NAME, option, fallback=\"\")\n\n        label = Gtk.Label(label=_(label), hexpand=True, halign=Gtk.Align.END)\n        grid.attach(label, 0, row, 1, 1)\n\n        entry = Gtk.Entry(editable=True, sensitive=bool(command), text=command, name=option + \"_entry\")\n        entry.connect(\"notify::text\", self.on_command_change, option)\n        grid.attach(entry, 0, row + 1, 4, 1)\n\n        switch = Gtk.Switch(hexpand=True, halign=Gtk.Align.START, active=bool(command), name=option + \"_switch\")\n        switch.connect(\"notify::active\", self.on_option_change, entry, option)\n        grid.attach_next_to(switch, label, Gtk.PositionType.RIGHT, 1, 1)\n\n    def on_command_change(self, entry: Gtk.Entry, _, option: str) -> None:\n        command = strip_space(entry.props.text)\n        if command:\n            logger.debug(\"action=set_option option=%s command=%s\", option, command)\n            self.config.set(SECTION_NAME, option, command)\n\n    def on_option_change(self, switch: Gtk.Switch, _, entry: Gtk.Entry, option: str) -> None:\n        if switch.props.active:\n            entry.props.sensitive = True\n        else:\n            self.remove_option(entry, option)\n\n    def remove_option(self, entry: Gtk.Entry, option: str) -> None:\n        logger.debug(\"action=remove_option option=%s\", option)\n        self.config.remove(SECTION_NAME, option)\n        entry.set_properties(text=\"\", sensitive=False)\n"
  },
  {
    "path": "data/plugins/ticking.plugin",
    "content": "[Core]\nName = Ticking\nModule = ticking\n\n[Documentation]\nAuthor = Elio Esteves Duarte\nVersion = 0.0.2\nWebsite = https://github.com/eliostvs/tomate-gtk\nDescription = Ticking sound during a pomodoro session"
  },
  {
    "path": "data/plugins/ticking.py",
    "content": "import logging\n\nimport gi\nfrom wiring import Graph\n\ngi.require_version(\"Gst\", \"1.0\")\n\nimport tomate.pomodoro.plugin as plugin\nfrom tomate.audio import GStreamerPlayer\nfrom tomate.pomodoro import (\n    Bus,\n    Events,\n    SessionPayload,\n    SessionType,\n    on,\n    suppress_errors,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass TickingPlugin(plugin.Plugin):\n    has_settings = False\n    SECTION_NAME = \"ticking_plugin\"\n\n    @suppress_errors\n    def __init__(self):\n        super().__init__()\n        self.config = None\n        self.player = None\n        self.session = None\n\n    def configure(self, bus: Bus, graph: Graph) -> None:\n        super().configure(bus, graph)\n        self.config = graph.get(\"tomate.config\")\n        self.session = graph.get(\"tomate.session\")\n\n    @suppress_errors\n    def activate(self) -> None:\n        super().activate()\n        logger.debug(\"action=activate uri=%s volume=%f\", self.audio_path, self.volume)\n        self.player = GStreamerPlayer(repeat=True)\n        self.player.file = self.audio_path\n        self.player.volume = self.volume\n\n        if self.session.is_running() and self.session.current == SessionType.POMODORO:\n            self.player.play()\n\n    @suppress_errors\n    def deactivate(self) -> None:\n        super().deactivate()\n        logger.debug(\"action=deactivate\")\n\n        if self.player:\n            self.player.stop()\n\n    @suppress_errors\n    @on(Events.SESSION_START)\n    def on_start(self, payload: SessionPayload) -> None:\n        logger.debug(f\"action=play session_type={payload.type}\")\n        if self.player and payload.type == SessionType.POMODORO:\n            self.player.play()\n\n    @suppress_errors\n    @on(Events.SESSION_INTERRUPT, Events.SESSION_END)\n    def on_end(self, **_) -> None:\n        logger.debug(\"action=stop\")\n        if self.player:\n            self.player.stop()\n\n    @property\n    def audio_path(self) -> str:\n        return self.config.get(self.SECTION_NAME, \"uri\", fallback=self.config.media_uri(\"clock.ogg\"))\n\n    @property\n    def volume(self) -> float:\n        return self.config.get_float(self.SECTION_NAME, \"volume\", fallback=1.0)\n"
  },
  {
    "path": "pyproject.toml",
    "content": "[tool.black]\nline-length = 120\ninclude = '\\.pyi?$'\nexclude = '''\n/(\n    \\.git\n  | \\.hg\n  | \\.mypy_cache\n  | \\.tox\n  | \\.venv\n  | _build\n  | buck-out\n  | build\n  | dist\n)/\n'''\n\n[tool.ruff]\nline-length = 120\nignore = [\"E402\", \"S101\"]\ntarget-version = \"py39\"\n\n[tool.isort]\nprofile = \"black\"\n"
  },
  {
    "path": "setup.cfg",
    "content": "[global]\nverbose=1\n\n[wheel]\nuniversal = 1\n\n[tool:pytest]\naddopts = --verbose --cov-report term-missing\n\n[coverage:run]\ninclude =\n    tomate\n"
  },
  {
    "path": "setup.py",
    "content": "#!/bin/env python\nimport os\n\nfrom setuptools import find_packages, setup\n\n\ndef find_xdg_data_files(from_dir, to_dir, package_name, data_files):\n    for root, _, files in os.walk(from_dir):\n        if files:\n            to_dir = to_dir.format(pkgname=package_name)\n\n            sub_path = root.split(from_dir)[1]\n            if sub_path.startswith(\"/\"):\n                sub_path = sub_path[1:]\n\n            files = [os.path.join(root, file) for file in files]\n            data_files.append((os.path.join(to_dir, sub_path), files))\n\n\ndef find_data_files(data_map, package_name):\n    data_files = []\n\n    for from_dir, to_dir in data_map:\n        find_xdg_data_files(from_dir, to_dir, package_name, data_files)\n\n    return data_files\n\n\nDATA_FILES = [\n    (\"data/icons\", \"share/icons\"),\n    (\"data/applications\", \"share/applications\"),\n    (\"data/plugins\", \"share/{pkgname}/plugins\"),\n    (\"data/media\", \"share/{pkgname}/media\"),\n]\n\nsetup(\n    author=\"Elio Esteves Duarte\",\n    author_email=\"elio.esteves.duarte@gmail.com\",\n    description=\"A pomodoro timer\",\n    include_package_data=True,\n    keywords=\"pomodoro,tomate\",\n    license=\"GPL-3\",\n    long_description=open(\"README.md\", \"r\", encoding=\"utf-8\").read(),\n    name=\"tomate-gtk\",\n    packages=find_packages(exclude=[\"tests\"]),\n    py_modules=[],\n    data_files=find_data_files(DATA_FILES, \"tomate\"),\n    url=\"https://github.com/eliostvs/tomate-gtk\",\n    version=\"0.25.2\",\n    zip_safe=False,\n    entry_points={\"console_scripts\": [\"tomate-gtk=tomate.__main__:main\"]},\n)\n"
  },
  {
    "path": "tests/conftest.py",
    "content": "import os\n\nimport gi\nimport pytest\nfrom wiring import Graph\n\ngi.require_version(\"Gtk\", \"3.0\")\n\nfrom gi.repository import Gtk\n\nfrom tomate.pomodoro import Bus, Config, PluginEngine, Session\nfrom tomate.ui import ShortcutEngine, Window\n\nTEST_DATA_DIR = os.path.join(os.path.dirname(__file__), \"data\")\n\n\n@pytest.fixture\ndef session(mocker):\n    return mocker.Mock(spec=Session)\n\n\n@pytest.fixture\ndef bus() -> Bus:\n    return Bus()\n\n\n@pytest.fixture\ndef graph() -> Graph:\n    g = Graph()\n    g.register_instance(Graph, g)\n    return g\n\n\n@pytest.fixture\ndef window(mocker):\n    return mocker.Mock(spec=Window, widget=Gtk.Window())\n\n\n@pytest.fixture\ndef config(bus, tmpdir) -> Config:\n    cfg = Config(bus)\n    tmp_path = tmpdir.mkdir(\"tomate\").join(\"tomate.config\")\n    cfg.config_path = lambda: tmp_path.strpath\n    return cfg\n\n\n@pytest.fixture\ndef shortcut_engine(config: Config) -> ShortcutEngine:\n    return ShortcutEngine(config)\n\n\n@pytest.fixture\ndef plugin_engine(bus: Bus, graph: Graph, config: Config) -> PluginEngine:\n    return PluginEngine(bus, config, graph)\n"
  },
  {
    "path": "tests/data/icons/hicolor/index.theme",
    "content": "[Icon Theme]\nName=Hicolor\nComment=Fallback icon theme\nHidden=true\nDirectories=16x16/apps,24x24/apps,scalable/apps,scalable/actions,scalable/categories,scalable/status\n\n[16x16/apps]\nSize=16\nContext=Applications\n\n[24x24/apps]\nSize=24\nContext=Applications\n\n[scalable/apps]\nSize=16\nMaxSize=48\nType=Scalable\nContext=Applications\n\n[scalable/apps]\nSize=16\nMaxSize=48\nType=Scalable\nContext=Applications\n\n[scalable/actions]\nSize=16\nMaxSize=48\nType=Scalable\nContext=Actions\n\n[scalable/categories]\nSize=16\nMaxSize=48\nType=Scalable\nContext=Categories\n\n[scalable/status]\nSize=16\nMaxSize=48\nType=Scalable\nContext=Status"
  },
  {
    "path": "tests/data/mime/packages/freedesktop.org.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!--\nThe freedesktop.org shared MIME database (this file) was created by merging\nseveral existing MIME databases (all released under the GPL).\n\nIt comes with ABSOLUTELY NO WARRANTY, to the extent permitted by law. You may\nredistribute copies of update-mime-database under the terms of the GNU General\nPublic License. For more information about these matters, see the file named\nCOPYING.\n\nThe latest version is available from:\n\n\thttp://www.freedesktop.org/wiki/Software/shared-mime-info/\n\nTo extend this database, users and applications should create additional\nXML files in the 'packages' directory and run the update-mime-database\ncommand to generate the output files.\n-->\n<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n  <mime-type type=\"image/png\">\n    <comment>PNG image</comment>\n    <magic priority=\"50\">\n      <match type=\"string\" value=\"\\x89PNG\" offset=\"0\"/>\n    </magic>\n    <glob pattern=\"*.png\"/>\n  </mime-type>\n  <mime-type type=\"image/svg+xml\">\n    <comment>SVG image</comment>\n    <acronym>SVG</acronym>\n    <expanded-acronym>Scalable Vector Graphics</expanded-acronym>\n    <sub-class-of type=\"application/xml\"/>\n    <magic priority=\"80\">\n      <match type=\"string\" value=\"&lt;!DOCTYPE svg\" offset=\"0:256\"/>\n    </magic>\n    <magic priority=\"80\">\n      <match type=\"string\" value=\"&lt;!-- Created with Inkscape\" offset=\"0\"/>\n      <match type=\"string\" value=\"&lt;svg\" offset=\"0\"/>\n    </magic>\n    <magic priority=\"45\">\n      <match type=\"string\" value=\"&lt;svg\" offset=\"1:256\"/>\n    </magic>\n    <glob pattern=\"*.svg\"/>\n    <root-XML namespaceURI=\"http://www.w3.org/2000/svg\" localName=\"svg\"/>\n  </mime-type>\n</mime-info>\n"
  },
  {
    "path": "tests/data/pulse/cookie",
    "content": "\u0016\u0011\u0006?Q/\"$\"cܗR\u0007dk\b\u0013r}\u000fJ\u001aM\u001cDiqf_~V9asj\u000b7pGm\"\u0005\u0018kF)C\u0014ޭޝ\u001d\u001egGBkH0\nO\t\u0014o\u0019\u0017ʢm\fD\u0018V>N\u001d{i\bq>\u0002X\u0002䟤ߺB]uքe1Hۅ\ncX=)h\u0016\u0013&]\rٍamm^K?\u0011\u0017\u0018I3rA\u0013\u000f1hn%J4He}d/q\u0010|[`ir\u000f"
  },
  {
    "path": "tests/data/tomate/plugins/.gitkeep",
    "content": ""
  },
  {
    "path": "tests/data/tomate/plugins/plugin_a.plugin",
    "content": "[Core]\nName = PluginA\nModule = plugin_a\n\n[Documentation]\nAuthor = Elio Esteves Duarte\nVersion = 1.0.0\nWebsite = https://github.com/eliostvs/tomate-plugin-a\nDescription = Description A"
  },
  {
    "path": "tests/data/tomate/plugins/plugin_a.py",
    "content": "from gi.repository import Gtk\n\nimport tomate.pomodoro.plugin as plugin\nfrom tomate.pomodoro import Events, on\n\n\nclass PluginA(plugin.Plugin):\n    has_settings = True\n\n    def __init__(self):\n        super().__init__()\n        self.parent = None\n\n    @on(Events.WINDOW_SHOW)\n    def listener(self, **__) -> str:\n        return \"plugin_a\"\n\n    def settings_window(self, parent: Gtk.Widget) -> Gtk.Dialog:\n        self.parent = parent\n        dialog = Gtk.MessageDialog(\n            message_type=Gtk.MessageType.INFO,\n            transient_for=parent,\n            buttons=Gtk.ButtonsType.OK,\n            text=\"Plugin A Settings\",\n        )\n        dialog.connect(\"response\", lambda widget, _: widget.destroy())\n        return dialog\n"
  },
  {
    "path": "tests/data/tomate/plugins/plugin_b.plugin",
    "content": "[Core]\nName = PluginB\nModule = plugin_b\n\n[Documentation]\nAuthor = Elio Esteves Duarte\nVersion = 2.0.0\nWebsite = https://github.com/eliostvs/tomate-plugin-b\nDescription = Description B"
  },
  {
    "path": "tests/data/tomate/plugins/plugin_b.py",
    "content": "import tomate.pomodoro.plugin as plugin\nfrom tomate.pomodoro import Events, on\n\n\nclass PluginB(plugin.Plugin):\n    has_settings = False\n\n    @on(Events.WINDOW_SHOW)\n    def listener(self, **__) -> str:\n        return \"plugin_b\"\n"
  },
  {
    "path": "tests/data/tomate/plugins/plugin_b_old.plugin",
    "content": "[Core]\nName = PluginB\nModule = plugin_b\n\n[Documentation]\nAuthor = Elio Esteves Duarte\nVersion = 1.5.0\nWebsite = https://github.com/eliostvs/tomate-plugin-b\nDescription = Should not loaded because has an older version"
  },
  {
    "path": "tests/data/tomate/tomate.conf",
    "content": "[DEFAULT]\npomodoro_duration = 25\nshortbreak_duration = 5\nlongbreak_duration = 15\nlong_break_interval = 4\n\n[timer]\npomodoro_duration = 25\nshortbreak_duration = 5\nlongbreak_duration = 15\n\n[shortcuts]\ntest = <control>S\n\n[Plugin Management]\ndefault_plugins_to_load = PluginB\n\n[ticking_plugin]\nvolume=0.5\n\n[alarm_plugin]\nvolume=0.8\n\n[script_plugin]\nstart_command = echo start\nstop_command = echo stop\nfinish_command = echo finish\n"
  },
  {
    "path": "tests/plugins/test_alarm.py",
    "content": "from os.path import dirname, join\nfrom unittest.mock import patch\n\nimport gi\nimport pytest\n\ngi.require_version(\"Gtk\", \"3.0\")\ngi.require_version(\"Gst\", \"1.0\")\n\nfrom gi.repository import Gtk\n\nfrom tomate.pomodoro import Events\nfrom tomate.ui.testing import Q\n\nCUSTOM_ALARM = f'file://{join(dirname(dirname(__file__)), \"data\", \"tomate\", \"media\", \"custom.ogg\")}'\nDEFAULT_ALARM = f'file://{join(dirname(dirname(__file__)), \"data\", \"tomate\", \"media\", \"alarm.ogg\")}'\nSECTION_NAME = \"alarm_plugin\"\nURI_OPTION_NAME = \"uri\"\n\n\n@pytest.fixture\ndef plugin(bus, config, graph):\n    graph.providers.clear()\n    graph.register_instance(\"tomate.config\", config)\n    graph.register_instance(\"tomate.bus\", bus)\n\n    from alarm import AlarmPlugin\n\n    instance = AlarmPlugin()\n    instance.configure(bus, graph)\n    return instance\n\n\nclass TestPlugin:\n    def test_loads_configuration_when_is_activated(self, bus, config, plugin):\n        plugin.activate()\n\n        assert pytest.approx(plugin.player.volume, rel=1e-3) == 0.8\n        assert plugin.player.file == DEFAULT_ALARM\n        assert not plugin.player.repeat\n\n    @patch(\"alarm.GStreamerPlayer\")\n    def test_plays_alarm_when_session_ends(self, player, bus, config, plugin):\n        plugin.activate()\n\n        bus.send(Events.SESSION_END)\n\n        assert player.return_value.play.called\n\n\nclass TestSettingsWindow:\n    def test_without_custom_alarm(self, config, plugin):\n        config.remove(SECTION_NAME, URI_OPTION_NAME)\n        dialog = plugin.settings_window(Gtk.Window())\n\n        entry = Q.select(dialog.widget, Q.props(\"name\", \"custom_entry\"))\n        assert entry.props.text == \"\"\n        assert entry.props.sensitive is False\n\n        switch = Q.select(dialog.widget, Q.props(\"name\", \"custom_switch\"))\n        assert switch.props.active is False\n\n    def test_with_custom_alarm(self, plugin, config):\n        config.set(SECTION_NAME, URI_OPTION_NAME, CUSTOM_ALARM)\n\n        dialog = plugin.settings_window(Gtk.Window())\n        dialog.run()\n\n        entry = Q.select(dialog.widget, Q.props(\"name\", \"custom_entry\"))\n        assert entry.props.text == CUSTOM_ALARM\n        assert entry.props.sensitive is True\n\n        switch = Q.select(dialog.widget, Q.props(\"name\", \"custom_switch\"))\n        assert switch.props.active is True\n\n    def test_configures_custom_alarm(self, config, plugin):\n        dialog = plugin.settings_window(Gtk.Window())\n\n        switch = Q.select(dialog.widget, Q.props(\"name\", \"custom_switch\"))\n        switch.props.active = True\n\n        entry = Q.select(dialog.widget, Q.props(\"name\", \"custom_entry\"))\n        assert entry.props.sensitive is True\n        entry.set_text(CUSTOM_ALARM)\n\n        dialog.widget.emit(\"response\", 0)\n        assert dialog.widget.props.window is None\n\n        assert config.get(SECTION_NAME, URI_OPTION_NAME) == CUSTOM_ALARM\n\n    def test_disables_custom_alarm(self, config, plugin):\n        config.set(SECTION_NAME, URI_OPTION_NAME, CUSTOM_ALARM)\n\n        dialog = plugin.settings_window(Gtk.Window())\n\n        switch = Q.select(dialog.widget, Q.props(\"name\", \"custom_switch\"))\n        switch.props.active = False\n\n        entry = Q.select(dialog.widget, Q.props(\"name\", \"custom_entry\"))\n        assert entry.props.text == \"\"\n        assert entry.props.sensitive is False\n\n        dialog.widget.emit(\"response\", 0)\n        assert dialog.widget.props.window is None\n\n        assert config.has_option(SECTION_NAME, URI_OPTION_NAME) is False\n"
  },
  {
    "path": "tests/plugins/test_autopause.py",
    "content": "import gi\nimport pytest\n\ngi.require_version(\"Playerctl\", \"2.0\")\ngi.require_version(\"Gtk\", \"3.0\")\n\nfrom tomate.pomodoro import Events\nfrom tomate.ui.testing import create_session_payload\n\n\n@pytest.fixture\ndef plugin(bus, graph):\n    from autopause import AutoPausePlugin\n\n    instance = AutoPausePlugin()\n    instance.configure(bus, graph)\n    return instance\n\n\ndef test_stop_all_running_players(bus, plugin, mocker):\n    from gi.repository import Playerctl\n\n    playing = mocker.Mock(props=mocker.Mock(playback_status=Playerctl.PlaybackStatus.PLAYING))\n    paused = mocker.Mock(props=mocker.Mock(playback_status=Playerctl.PlaybackStatus.PAUSED))\n    players = {\n        \"playing-playing\": playing,\n        \"paused-paused\": paused,\n    }\n\n    def side_effect(instance, source):\n        return players.get(f\"{instance}-{source}\")\n\n    mocker.patch(\n        \"autopause.Playerctl.list_players\",\n        return_value=[\n            mocker.Mock(instance=\"playing\", source=\"playing\"),\n            mocker.Mock(instance=\"paused\", source=\"paused\"),\n        ],\n    )\n    mocker.patch(\"autopause.Playerctl.Player.new_for_source\", side_effect)\n\n    plugin.activate()\n\n    bus.send(Events.SESSION_END, payload=create_session_payload())\n\n    paused.pause.assert_not_called()\n    playing.pause.assert_called_once()\n"
  },
  {
    "path": "tests/plugins/test_breakscreen.py",
    "content": "import random\nfrom typing import Iterator\n\nimport gi\nimport pytest\n\ngi.require_version(\"Gtk\", \"3.0\")\n\nfrom gi.repository import Gtk\n\nfrom tomate.pomodoro import ConfigPayload, Events, SessionType, TimerPayload\nfrom tomate.ui.testing import Q, create_session_payload, run_loop_for\n\nSECTION_NAME = \"break_screen\"\nSKIP_BREAK_OPTION = \"skip_break\"\nAUTO_START_OPTION = \"auto_start\"\n\n\n@pytest.fixture\ndef plugin(bus, config, graph, session):\n    graph.providers.clear()\n    graph.register_instance(\"tomate.bus\", bus)\n    graph.register_instance(\"tomate.config\", config)\n    graph.register_instance(\"tomate.session\", session)\n\n    from breakscreen import BreakScreenPlugin\n\n    instance = BreakScreenPlugin()\n    instance.configure(bus, graph)\n    return instance\n\n\ndef none(values: Iterator) -> bool:\n    return all([value is False for value in values])\n\n\ndef label_text(countdown: str, plugin) -> bool:\n    return len(plugin.screens) > 0 and all(\n        [Q.select(screen.widget, Q.props(\"name\", \"countdown\")).get_text() == countdown for screen in plugin.screens]\n    )\n\n\nclass TestPlugin:\n    @pytest.mark.parametrize(\"session_type\", [SessionType.SHORT_BREAK, SessionType.LONG_BREAK])\n    def test_shows_when_pause_begins(self, session_type, bus, plugin):\n        plugin.activate()\n\n        payload = create_session_payload(type=session_type)\n        bus.send(Events.SESSION_START, payload=payload)\n\n        assert all([screen.widget.props.visible for screen in plugin.screens])\n        assert label_text(payload.countdown, plugin)\n\n    def test_not_show_when_pomodoro_begins(self, bus, plugin):\n        plugin.activate()\n\n        payload = create_session_payload(type=SessionType.POMODORO)\n        bus.send(Events.SESSION_START, payload=payload)\n\n        assert none([screen.widget.props.visible for screen in plugin.screens])\n\n    def test_hides_when_plugin_is_deactivated(self, bus, plugin):\n        plugin.activate()\n\n        payload = create_session_payload(type=SessionType.SHORT_BREAK)\n        bus.send(Events.SESSION_START, payload=payload)\n\n        plugin.deactivate()\n\n        assert none([screen.widget.props.visible for screen in plugin.screens])\n\n    def test_starts_break_when_auto_start_option_is_enabled(self, bus, config, plugin, session):\n        config.set(SECTION_NAME, AUTO_START_OPTION, \"true\")\n\n        plugin.activate()\n\n        payload = create_session_payload(type=SessionType.POMODORO)\n        bus.send(Events.SESSION_END, payload=payload)\n\n        run_loop_for(1)\n\n        session.start.assert_called_once()\n\n    def test_not_start_break_when_auto_start_is_disabled(self, bus, config, plugin, session):\n        config.set(SECTION_NAME, AUTO_START_OPTION, \"false\")\n\n        plugin.activate()\n\n        payload = create_session_payload(type=SessionType.POMODORO)\n        bus.send(Events.SESSION_END, payload=payload)\n\n        session.start.assert_not_called()\n\n        assert none([screen.widget.props.visible for screen in plugin.screens])\n\n    def test_hides_when_session_is_interrupted(self, bus, plugin):\n        plugin.activate()\n\n        bus.send(Events.SESSION_START, payload=create_session_payload(type=SessionType.SHORT_BREAK))\n        bus.send(Events.SESSION_INTERRUPT, payload=create_session_payload())\n\n        assert none([screen.widget.props.visible for screen in plugin.screens])\n\n    @pytest.mark.parametrize(\"session_type\", [SessionType.SHORT_BREAK, SessionType.LONG_BREAK])\n    def test_not_start_break_when_is_not_a_pomodoro(self, session_type, bus, config, plugin, session):\n        config.set(SECTION_NAME, AUTO_START_OPTION, \"True\")\n        plugin.activate()\n\n        for screen in plugin.screens:\n            screen.widget.show()\n\n        payload = create_session_payload(type=session_type)\n        bus.send(Events.SESSION_END, payload=payload)\n\n        session.start.assert_not_called()\n\n        assert none([screen.widget.props.visible for screen in plugin.screens])\n\n    def test_updates_countdown(self, bus, plugin):\n        plugin.activate()\n\n        time_left = random.randint(1, 100)\n\n        payload = TimerPayload(time_left=time_left, duration=150)\n        bus.send(Events.TIMER_UPDATE, payload=payload)\n\n        assert label_text(payload.countdown, plugin)\n\n    @pytest.mark.parametrize(\n        \"action,option,initial,value,want\",\n        [\n            (\"set\", AUTO_START_OPTION, \"false\", \"true\", True),\n            (\"remove\", AUTO_START_OPTION, \"true\", \"\", False),\n            (\"set\", SKIP_BREAK_OPTION, \"false\", \"true\", True),\n            (\"remove\", SKIP_BREAK_OPTION, \"true\", \"\", False),\n        ],\n    )\n    def test_updates_when_config_changes(self, action, option, initial, value, want, bus, config, plugin):\n        config.set(SECTION_NAME, option, initial)\n        plugin.activate()\n\n        payload = ConfigPayload(action, SECTION_NAME, option, value)\n        bus.send(Events.CONFIG_CHANGE, payload=payload)\n\n        assert all([screen.options[option] == want for screen in plugin.screens])\n\n    @pytest.mark.parametrize(\n        \"action, want\",\n        [\n            (\"set\", True),\n            (\"remove\", False),\n        ],\n    )\n    def test_hide_skip_button_when_config_changes(self, action, want, bus, plugin):\n        plugin.activate()\n\n        payload = ConfigPayload(action, SECTION_NAME, SKIP_BREAK_OPTION, \"\")\n        bus.send(Events.CONFIG_CHANGE, payload=payload)\n\n        assert all([screen.skip_button.props.visible == want for screen in plugin.screens])\n\n\nclass TestSettingsWindow:\n    def test_options_labels(self, plugin):\n        dialog = plugin.settings_window(Gtk.Window())\n\n        assert Q.select(dialog.widget, Q.props(\"label\", \"Auto start:\")) is not None\n        assert Q.select(dialog.widget, Q.props(\"label\", \"Skip break:\")) is not None\n\n    def test_with_all_options_enabled(self, config, plugin):\n        config.set(SECTION_NAME, AUTO_START_OPTION, \"true\")\n        config.set(SECTION_NAME, SKIP_BREAK_OPTION, \"true\")\n\n        dialog = plugin.settings_window(Gtk.Window())\n\n        assert Q.select(dialog.widget, Q.props(\"name\", AUTO_START_OPTION)).props.active is True\n        assert Q.select(dialog.widget, Q.props(\"name\", SKIP_BREAK_OPTION)).props.active is True\n\n    def test_with_all_options_disabled(self, config, plugin):\n        config.remove(SECTION_NAME, AUTO_START_OPTION)\n        config.remove(SECTION_NAME, SKIP_BREAK_OPTION)\n\n        dialog = plugin.settings_window(Gtk.Window())\n\n        assert Q.select(dialog.widget, Q.props(\"name\", AUTO_START_OPTION)).props.active is False\n        assert Q.select(dialog.widget, Q.props(\"name\", SKIP_BREAK_OPTION)).props.active is False\n\n    def test_change_options(self, config, plugin):\n        config.remove(SECTION_NAME, AUTO_START_OPTION)\n        config.remove(SECTION_NAME, SKIP_BREAK_OPTION)\n\n        dialog = plugin.settings_window(Gtk.Window())\n\n        Q.select(dialog.widget, Q.props(\"name\", AUTO_START_OPTION)).props.active = True\n        Q.select(dialog.widget, Q.props(\"name\", SKIP_BREAK_OPTION)).props.active = True\n\n        config.load()\n\n        assert config.get_bool(SECTION_NAME, AUTO_START_OPTION) is True\n        assert config.get_bool(SECTION_NAME, SKIP_BREAK_OPTION) is True\n"
  },
  {
    "path": "tests/plugins/test_notify.py",
    "content": "from os.path import dirname, join\nfrom unittest.mock import patch\n\nimport gi\nimport pytest\n\nfrom tomate.pomodoro import Config, Events, SessionType\nfrom tomate.ui.testing import create_session_payload\n\ngi.require_version(\"Notify\", \"0.7\")\n\nIconPath = join(dirname(dirname(__file__)), \"data\", \"icons\", \"hicolor\", \"24x24\", \"apps\", \"tomate.png\")\n\n\n@pytest.fixture\n@patch(\"gi.repository.Notify.Notification.new\")\ndef plugin(_, graph, bus):\n    graph.providers.clear()\n    graph.register_instance(\"tomate.bus\", bus)\n    graph.register_instance(\"tomate.config\", Config(bus))\n\n    from notify import NotifyPlugin\n\n    instance = NotifyPlugin()\n    instance.configure(bus, graph)\n    return instance\n\n\n@patch(\"gi.repository.Notify.init\")\ndef test_enable_notify_when_plugin_active(init, plugin):\n    plugin.activate()\n\n    init.assert_called_with(\"tomate-notify-plugin\")\n\n\n@patch(\"gi.repository.Notify.uninit\")\ndef test_disable_notify_when_plugin_deactivate(uninit, plugin):\n    plugin.deactivate()\n\n    uninit.assert_called_with()\n\n\n@pytest.mark.parametrize(\n    \"event,session,title,message\",\n    [\n        (Events.SESSION_START, SessionType.POMODORO, \"Pomodoro\", \"Get back to work!\"),\n        (Events.SESSION_START, SessionType.SHORT_BREAK, \"Short Break\", \"It's coffee time!\"),\n        (Events.SESSION_START, SessionType.LONG_BREAK, \"Long Break\", \"Step away from the machine!\"),\n        (Events.SESSION_INTERRUPT, SessionType.POMODORO, \"Session stopped manually\", \"\"),\n        (Events.SESSION_END, SessionType.POMODORO, \"The time is up!\", \"\"),\n    ],\n)\ndef test_show_notification_when_session_starts(event, session, title, message, bus, plugin):\n    plugin.activate()\n\n    payload = create_session_payload(type=session)\n    bus.send(event, payload=payload)\n\n    plugin.notification.update.assert_called_once_with(title, message, IconPath)\n    plugin.notification.show.assert_called_once()\n"
  },
  {
    "path": "tests/plugins/test_script.py",
    "content": "import subprocess\n\nimport gi\nimport pytest\n\ngi.require_version(\"Gtk\", \"3.0\")\n\nfrom gi.repository import Gtk\n\nfrom tomate.pomodoro import Events, SessionType\nfrom tomate.ui.testing import Q, create_session_payload\n\nSECTION_NAME = \"script_plugin\"\n\n\n@pytest.fixture\ndef subprocess_run(mocker, monkeypatch):\n    import script\n\n    mock = mocker.Mock(spec=subprocess.run)\n    monkeypatch.setattr(script.subprocess, \"run\", mock)\n    return mock\n\n\n@pytest.fixture\ndef plugin(bus, config, graph):\n    graph.providers.clear()\n    graph.register_instance(\"tomate.config\", config)\n    graph.register_instance(\"tomate.bus\", bus)\n\n    from script import ScriptPlugin\n\n    instance = ScriptPlugin()\n    instance.configure(bus, graph)\n    return instance\n\n\n@pytest.mark.parametrize(\n    \"event,option\",\n    [\n        (Events.SESSION_START, \"start_command\"),\n        (Events.SESSION_INTERRUPT, \"stop_command\"),\n        (Events.SESSION_END, \"finish_command\"),\n    ],\n)\ndef test_execute_command_when_event_is_trigger(event, option, bus, subprocess_run, config, plugin):\n    command = config.get(SECTION_NAME, option)\n    plugin.activate()\n\n    bus.send(event, create_session_payload())\n\n    subprocess_run.assert_called_once_with(command, shell=True, check=True)\n\n\n@pytest.mark.parametrize(\n    \"event,section,session_type\",\n    [\n        (Events.SESSION_START, \"start_command\", SessionType.POMODORO),\n        (Events.SESSION_INTERRUPT, \"stop_command\", SessionType.LONG_BREAK),\n        (Events.SESSION_END, \"finish_command\", SessionType.SHORT_BREAK),\n    ],\n)\ndef test_command_variables(event, section, session_type, bus, subprocess_run, config, plugin):\n    config.set(SECTION_NAME, section, \"$event $session\")\n    plugin.activate()\n\n    bus.send(event, create_session_payload(type=session_type))\n\n    subprocess_run.assert_called_once_with(f\"{event.name} {session_type.name}\", shell=True, check=True)\n\n\n@pytest.mark.parametrize(\n    \"event, option\",\n    [\n        (Events.SESSION_START, \"start_command\"),\n        (Events.SESSION_INTERRUPT, \"stop_command\"),\n        (Events.SESSION_END, \"finish_command\"),\n    ],\n)\ndef test_does_not_execute_commands_when_they_are_not_configured(event, option, bus, subprocess_run, config, plugin):\n    config.remove(SECTION_NAME, option)\n    plugin.activate()\n\n    assert bus.send(event, create_session_payload()) == [False]\n\n    subprocess_run.assert_not_called()\n\n\ndef test_execute_command_fail(bus, config, plugin):\n    config.set(SECTION_NAME, \"start_command\", \"fail\")\n\n    plugin.activate()\n\n    assert bus.send(Events.SESSION_START, create_session_payload()) == [False]\n\n\nclass TestSettingsWindow:\n    @pytest.mark.parametrize(\n        \"option,command\",\n        [\n            (\"start_command\", \"echo start\"),\n            (\"stop_command\", \"echo stop\"),\n            (\"finish_command\", \"echo finish\"),\n        ],\n    )\n    def test_with_custom_commands(self, option, command, plugin):\n        dialog = plugin.settings_window(Gtk.Window())\n\n        switch = Q.select(dialog.widget, Q.props(\"name\", f\"{option}_switch\"))\n        assert switch.props.active is True\n\n        entry = Q.select(dialog.widget, Q.props(\"name\", f\"{option}_entry\"))\n        assert entry.props.text == command\n\n    @pytest.mark.parametrize(\"option\", [\"start_command\", \"stop_command\", \"finish_command\"])\n    def test_without_custom_commands(self, option, config, plugin):\n        config.remove_section(SECTION_NAME)\n        config.save()\n\n        assert config.has_section(SECTION_NAME) is False\n\n        dialog = plugin.settings_window(Gtk.Window())\n\n        switch = Q.select(dialog.widget, Q.props(\"name\", f\"{option}_switch\"))\n        assert switch.props.active is False\n\n        entry = Q.select(dialog.widget, Q.props(\"name\", f\"{option}_entry\"))\n        assert entry.props.text == \"\"\n\n    @pytest.mark.parametrize(\"option\", [\"start_command\", \"stop_command\", \"finish_command\"])\n    def test_disable_command(self, option, config, plugin):\n        dialog = plugin.settings_window(Gtk.Window())\n\n        switch = Q.select(dialog.widget, Q.props(\"name\", f\"{option}_switch\"))\n        switch.props.active = False\n\n        entry = Q.select(dialog.widget, Q.props(\"name\", f\"{option}_entry\"))\n        assert entry.props.sensitive is False\n        assert entry.props.text == \"\"\n\n        dialog.widget.emit(\"response\", 0)\n        assert dialog.widget.props.window is None\n\n        config.load()\n        assert config.has_option(SECTION_NAME, option) is False\n\n    @pytest.mark.parametrize(\"option\", [\"start_command\", \"stop_command\", \"finish_command\"])\n    def test_configure_command(self, option, config, plugin):\n        config.remove(SECTION_NAME, option)\n\n        dialog = plugin.settings_window(Gtk.Window())\n\n        switch = Q.select(dialog.widget, Q.props(\"name\", f\"{option}_switch\"))\n        switch.props.active = True\n\n        entry = Q.select(dialog.widget, Q.props(\"name\", f\"{option}_entry\"))\n        assert entry.props.sensitive is True\n        entry.props.text = \"echo changed\"\n\n        dialog.widget.emit(\"response\", 0)\n        assert dialog.widget.props.window is None\n\n        config.load()\n        assert config.get(SECTION_NAME, option) == \"echo changed\"\n\n    def test_text(self, config, plugin):\n        dialog = plugin.settings_window(Gtk.Window())\n\n        expected = (\n            \"You can use the session and event names in your script using the\"\n            \" <i>$session</i> and <i>$event</i> template variables.\"\n        )\n        assert Q.select(dialog.widget, Q.props(\"label\", expected))\n\n        assert Q.select(dialog.widget, Q.props(\"label\", \"<b>Scripts</b>\"))\n"
  },
  {
    "path": "tests/plugins/test_ticking.py",
    "content": "from os.path import dirname, join\nfrom unittest.mock import patch\n\nimport gi\nimport pytest\n\nfrom tomate.ui.testing import create_session_payload\n\ngi.require_version(\"Gtk\", \"3.0\")\ngi.require_version(\"Gst\", \"1.0\")\n\nfrom tomate.pomodoro import Events, SessionType\n\nDEFAULT_ALARM = f'file://{join(dirname(dirname(__file__)), \"data\", \"tomate\", \"media\", \"clock.ogg\")}'\n\n\n@pytest.fixture\ndef plugin(bus, config, graph, session):\n    graph.providers.clear()\n    graph.register_instance(\"tomate.bus\", bus)\n    graph.register_instance(\"tomate.config\", config)\n    graph.register_instance(\"tomate.session\", session)\n\n    from ticking import TickingPlugin\n\n    instance = TickingPlugin()\n    instance.configure(bus, graph)\n    return instance\n\n\nclass TestPlugin:\n    def test_loads_configuration_when_is_activated(self, bus, config, plugin):\n        plugin.activate()\n\n        assert plugin.player.volume == 0.5\n        assert plugin.player.file == DEFAULT_ALARM\n        assert plugin.player.repeat\n\n    @patch(\"ticking.GStreamerPlayer\")\n    @pytest.mark.parametrize(\n        \"is_running,session_type,want\",\n        [\n            (True, SessionType.POMODORO, True),\n            (True, SessionType.SHORT_BREAK, False),\n            (False, SessionType.POMODORO, False),\n        ],\n    )\n    def test_starts_player_when_is_activated(\n        self, player, is_running, session_type, want, bus, config, session, plugin\n    ):\n        session.is_running.return_value = is_running\n        session.current = session_type\n\n        plugin.activate()\n\n        assert player.return_value.play.called == want\n\n    @patch(\"ticking.GStreamerPlayer\")\n    def test_starts_player_when_session_start(self, player, bus, config, plugin):\n        plugin.activate()\n\n        bus.send(Events.SESSION_START, payload=create_session_payload())\n\n        player.return_value.play.assert_called_once()\n\n    @patch(\"ticking.GStreamerPlayer\")\n    @pytest.mark.parametrize(\"event\", [Events.SESSION_END, Events.SESSION_INTERRUPT])\n    def test_stops_player_when_session_(self, player, event, bus, config, plugin):\n        plugin.activate()\n\n        bus.send(Events.SESSION_START, payload=create_session_payload())\n        bus.send(event)\n\n        player.return_value.stop.assert_called_once()\n\n    @patch(\"ticking.GStreamerPlayer\")\n    def test_stops_player_when_is_deactivate(self, player, bus, config, plugin):\n        plugin.activate()\n\n        plugin.deactivate()\n\n        player.return_value.stop.assert_called_once()\n"
  },
  {
    "path": "tests/pomodoro/test_app.py",
    "content": "import dbus\nimport pytest\nfrom dbus.mainloop.glib import DBusGMainLoop\nfrom dbusmock import DBusTestCase\nfrom wiring.scanning import scan_to_graph\n\nfrom tomate.pomodoro import Application\nfrom tomate.pomodoro.app import State\n\nDBusGMainLoop(set_as_default=True)\n\n\n@pytest.fixture\ndef app(graph, window, plugin_engine, mocker) -> Application:\n    graph.register_instance(\"tomate.ui.view\", window)\n    graph.register_instance(\"tomate.plugin\", plugin_engine)\n    graph.register_instance(\"dbus.session\", mocker.Mock())\n\n    scan_to_graph([\"tomate.pomodoro.app\"], graph)\n\n    return graph.get(\"tomate.app\")\n\n\ndef test_module(graph, app):\n    instance = graph.get(\"tomate.app\")\n\n    assert isinstance(instance, Application)\n    assert instance is app\n\n\ndef test_collects_plugins_on_start(app, plugin_engine):\n    assert plugin_engine.has_plugins() is True\n\n\nclass TestRun:\n    def test_start_window_when_app_is_not_running(self, app, window):\n        app.state = State.STOPPED\n\n        app.Run()\n\n        window.run.assert_called_once_with()\n\n    def test_shows_window_when_app_is_running(self, app, window):\n        app.state = State.STARTED\n\n        app.Run()\n\n        window.show.assert_called_once_with()\n\n\nclass TestFromGraph:\n    def setup_method(self):\n        DBusTestCase.start_session_bus()\n\n    def teardown_method(self):\n        DBusTestCase.tearDownClass()\n\n    def test_create_app_instance_when_it_is_not_registered_in_dbus(self, graph, window, plugin_engine):\n        graph.register_instance(\"tomate.ui.view\", window)\n        graph.register_instance(\"tomate.plugin\", plugin_engine)\n        scan_to_graph([\"tomate.pomodoro.app\"], graph)\n\n        instance = Application.from_graph(graph, DBusTestCase.get_dbus())\n\n        assert isinstance(instance, Application)\n\n    @pytest.fixture()\n    def mock_dbus(self):\n        mock = DBusTestCase.spawn_server(Application.BUS_NAME, Application.BUS_PATH, Application.BUS_INTERFACE)\n        yield mock\n        mock.terminate()\n        mock.wait()\n\n    def test_get_dbus_interface_when_is_registered_in_dbus(self, graph, mock_dbus):\n        instance = Application.from_graph(graph, DBusTestCase.get_dbus())\n\n        assert isinstance(instance, dbus.Interface)\n        assert instance.dbus_interface == Application.BUS_INTERFACE\n        assert instance.object_path == Application.BUS_PATH\n        assert instance.requested_bus_name == Application.BUS_NAME\n"
  },
  {
    "path": "tests/pomodoro/test_config.py",
    "content": "import os\n\nimport pytest\nfrom wiring.scanning import scan_to_graph\n\nfrom tests.conftest import TEST_DATA_DIR\nfrom tomate.pomodoro import Config, ConfigPayload, Events\n\n\n@pytest.fixture\ndef config(graph, bus):\n    graph.register_instance(\"tomate.bus\", bus)\n    scan_to_graph([\"tomate.pomodoro.config\"], graph)\n    return graph.get(\"tomate.config\")\n\n\ndef test_module(graph, config):\n    instance = graph.get(\"tomate.config\")\n\n    assert isinstance(instance, Config)\n    assert instance is config\n\n\ndef test_get_plugin_paths(config):\n    expected = os.path.join(TEST_DATA_DIR, \"tomate\", \"plugins\")\n\n    assert expected in config.plugin_paths()\n\n\ndef test_get_config_path(config):\n    assert config.config_path() == os.path.join(TEST_DATA_DIR, \"tomate\", \"tomate.conf\")\n\n\ndef test_get_media_uri_raises_error_when_media_is_not_found(config):\n    with pytest.raises(OSError) as excinfo:\n        config.media_uri(\"tomate.jpg\")\n\n    assert str(excinfo.value) == \"Resource 'tomate.jpg' not found!\"\n\n\ndef test_get_media_uri(config):\n    expected = \"file://\" + os.path.join(TEST_DATA_DIR, \"tomate\", \"media\", \"tomate.png\")\n\n    assert config.media_uri(\"tomate.png\") == expected\n\n\ndef test_get_icon_path_raises_when_icon_not_found(config):\n    with pytest.raises(OSError) as excinfo:\n        assert config.icon_path(\"foo\", 48, \"foobar\")\n\n    assert str(excinfo.value) == \"Icon 'foo' not found!\"\n\n\ndef test_get_icon_path(config):\n    expected = os.path.join(TEST_DATA_DIR, \"icons\", \"hicolor\", \"24x24\", \"apps\", \"tomate.png\")\n    assert config.icon_path(\"tomate\", 48, \"hicolor\") == expected\n\n\ndef test_icon_paths(config):\n    assert os.path.join(TEST_DATA_DIR, \"icons\") in config.icon_paths()\n\n\ndef test_get_option_as_int(config):\n    assert config.get_int(\"Timer\", \"pomodoro_duration\") == 25\n\n\ndef test_get_option_as_float(config):\n    assert config.get_float(\"ticking_plugin\", \"volume\") == 0.50\n\n\ndef test_get_option(config):\n    assert config.get(\"Timer\", \"pomodoro_duration\") == \"25\"\n\n\ndef test_get_option_with_fallback(config):\n    assert config.get(\"Timer\", \"pomodoro_pass\", fallback=\"23\") == \"23\"\n\n\ndef test_get_defaults_option(config):\n    assert config.get(\"Timer\", \"shortbreak_duration\") == \"5\"\n\n\ndef test_set_option(bus, config, mocker, tmpdir):\n    config_path = tmpdir.mkdir(\"tmp\").join(\"tomate.config\").strpath\n    config.config_path = lambda: config_path\n\n    subscriber = mocker.Mock()\n    bus.connect(Events.CONFIG_CHANGE, subscriber, weak=False)\n\n    config.set(\"section\", \"option\", \"value\")\n\n    config.load()\n    assert config.get(\"section\", \"option\") == \"value\"\n\n    payload = ConfigPayload(\"set\", \"section\", \"option\", \"value\")\n    subscriber.assert_called_once_with(Events.CONFIG_CHANGE, payload=payload)\n\n\ndef test_remove_option(bus, config, mocker, tmpdir):\n    tmp_path = tmpdir.mkdir(\"tmp\").join(\"tomate.config\")\n    config.config_path = lambda: tmp_path.strpath\n\n    config.set(\"section\", \"option\", \"value\")\n    subscriber = mocker.Mock()\n    bus.connect(Events.CONFIG_CHANGE, subscriber, weak=False)\n    config.remove(\"section\", \"option\")\n\n    config.load()\n    assert config.parser.has_option(\"section\", \"option\") is False\n\n    payload = ConfigPayload(\"remove\", \"section\", \"option\", \"\")\n    subscriber.assert_called_once_with(Events.CONFIG_CHANGE, payload=payload)\n"
  },
  {
    "path": "tests/pomodoro/test_event.py",
    "content": "from wiring.scanning import scan_to_graph\n\nfrom tomate.pomodoro import Bus, Events, Subscriber, on\n\n\nclass TestBus:\n    def test_connect_receiver(self, bus, mocker):\n        def side_effect(*_, payload):\n            return payload\n\n        receiver = mocker.Mock(side_effect=side_effect)\n        bus.connect(Events.SESSION_START, receiver, weak=False)\n\n        assert bus.send(Events.SESSION_START, payload=\"payload\") == [\"payload\"]\n\n    def test_disconnect_receiver(self, bus, mocker):\n        receiver = mocker.Mock()\n        bus.connect(Events.SESSION_START, receiver, weak=False)\n        bus.disconnect(Events.SESSION_START, receiver)\n\n        assert bus.send(Events.SESSION_START, payload=\"payload\") == []\n\n\ndef test_subscriber(bus):\n    class Subject(Subscriber):\n        @on(Events.TIMER_START, Events.SESSION_START)\n        def bar(self, **__) -> bool:\n            return True\n\n    subject = Subject()\n    subject.connect(bus)\n\n    result = bus.send(Events.TIMER_START, \"timer_start\")\n    assert len(result) == 1 and result[0] is True\n\n    result = bus.send(Events.SESSION_START)\n    assert len(result) == 1 and result[0] is True\n\n    assert bus.send(Events.WINDOW_SHOW) == []\n\n    subject.disconnect(bus)\n\n    assert bus.send(Events.TIMER_START) == []\n    assert bus.send(Events.SESSION_START) == []\n\n\ndef test_module(graph):\n    scan_to_graph([\"tomate.pomodoro.event\"], graph)\n    instance = graph.get(\"tomate.bus\")\n\n    assert isinstance(instance, Bus)\n    assert graph.get(\"tomate.bus\") is instance\n"
  },
  {
    "path": "tests/pomodoro/test_graph.py",
    "content": "from wiring import Graph\nfrom wiring.scanning import scan_to_graph\n\n\ndef test_module():\n    graph = Graph()\n\n    scan_to_graph([\"tomate.pomodoro.graph\"], graph)\n\n    assert isinstance(graph.get(Graph), Graph)\n"
  },
  {
    "path": "tests/pomodoro/test_plugin.py",
    "content": "import os\nfrom distutils.version import StrictVersion\n\nimport pytest\nfrom wiring.scanning import scan_to_graph\n\nfrom tomate.pomodoro import Events, PluginEngine, suppress_errors\n\n\n@pytest.fixture\ndef plugin_engine(bus, graph, config) -> PluginEngine:\n    return PluginEngine(bus, config, graph)\n\n\ndef test_module(bus, config, graph):\n    graph.register_instance(\"tomate.bus\", bus)\n    graph.register_instance(\"tomate.config\", config)\n    scan_to_graph([\"tomate.pomodoro.plugin\"], graph)\n\n    instance = graph.get(\"tomate.plugin\")\n\n    assert isinstance(instance, PluginEngine)\n    assert instance == graph.get(\"tomate.plugin\")\n\n\nclass TestPluginEngine:\n    def test_collect(self, bus, graph, plugin_engine):\n        assert plugin_engine.has_plugins() is False\n\n        plugin_engine.collect()\n\n        assert plugin_engine.has_plugins() is True\n\n        for plugin in plugin_engine.all():\n            assert plugin.plugin_object.bus is bus\n            assert plugin.plugin_object.graph is graph\n\n    def test_activate(self, bus, plugin_engine):\n        plugin_engine.collect()\n        plugin_a = plugin_engine.lookup(\"PluginA\")\n\n        assert plugin_a.is_activated is False\n        assert bus.is_connect(Events.WINDOW_SHOW, plugin_a.plugin_object.listener) is False\n\n        plugin_engine.activate(\"PluginA\")\n        assert plugin_a.is_activated is True\n        assert bus.is_connect(Events.WINDOW_SHOW, plugin_a.plugin_object.listener) is True\n\n    def test_deactivate(self, bus, plugin_engine):\n        plugin_engine.collect()\n        plugin_b = plugin_engine.lookup(\"PluginB\")\n\n        assert plugin_b.is_activated is True\n        assert bus.is_connect(Events.WINDOW_SHOW, plugin_b.plugin_object.listener) is True\n\n        plugin_engine.deactivate(\"PluginB\")\n        assert plugin_b.is_activated is False\n        assert bus.is_connect(Events.WINDOW_SHOW, plugin_b.plugin_object.listener) is False\n\n    def test_all(self, plugin_engine):\n        plugin_engine.collect()\n\n        got = [(p.name, p.version, p.is_activated, p.plugin_object.has_settings) for p in plugin_engine.all()]\n\n        assert got == [\n            (\"PluginA\", StrictVersion(\"1.0.0\"), False, True),\n            (\"PluginB\", StrictVersion(\"2.0.0\"), True, False),\n        ]\n\n    def test_lookup(self, plugin_engine):\n        plugin_engine.collect()\n\n        assert plugin_engine.lookup(\"Not Exist\") is None\n\n        plugin = plugin_engine.lookup(\"PluginA\")\n\n        assert plugin is not None\n\n\nclass TestRaiseException:\n    def test_does_not_raise_exception_when_debug_is_disabled(self):\n        os.unsetenv(\"TOMATE_DEBUG\")\n\n        @suppress_errors\n        def raise_exception():\n            raise Exception()\n\n        assert not raise_exception()\n\n    def test_raises_exception_when_debug_enable(self):\n        os.environ.setdefault(\"TOMATE_DEBUG\", \"1\")\n\n        @suppress_errors\n        def raise_exception():\n            raise Exception()\n\n        with pytest.raises(Exception):\n            raise_exception()\n"
  },
  {
    "path": "tests/pomodoro/test_session.py",
    "content": "import pytest\nfrom wiring.scanning import scan_to_graph\n\nfrom tomate.pomodoro import Events, Session, SessionPayload, SessionType\nfrom tomate.pomodoro.config import Config\nfrom tomate.pomodoro.session import State\nfrom tomate.ui.testing import create_session_payload, run_loop_for\n\n\n@pytest.fixture()\ndef session(graph, config, bus, mocker):\n    graph.register_instance(\"tomate.bus\", bus)\n    graph.register_instance(\"tomate.config\", config)\n    scan_to_graph([\"tomate.pomodoro.timer\", \"tomate.pomodoro.session\"], graph)\n    return graph.get(\"tomate.session\")\n\n\ndef test_module(graph, session):\n    instance = graph.get(\"tomate.session\")\n\n    assert isinstance(instance, Session)\n    assert instance is session\n\n\ndef test_sends_ready_event(bus, mocker, session):\n    subscriber = mocker.Mock()\n    bus.connect(Events.SESSION_READY, subscriber, weak=False)\n\n    session.ready()\n\n    payload = create_session_payload()\n    subscriber.assert_called_once_with(Events.SESSION_READY, payload=payload)\n\n\nclass TestSessionStart:\n    def test_not_start_when_session_is_already_running(self, session):\n        session.state = State.STARTED\n\n        assert not session.start()\n\n    @pytest.mark.parametrize(\"state\", [State.ENDED, State.STOPPED])\n    def test_starts_when_session_is_not_running(self, state, session, bus, mocker):\n        session.state = state\n\n        subscriber = mocker.Mock()\n        bus.connect(Events.SESSION_START, subscriber, weak=False)\n\n        result = session.start()\n\n        assert result is True\n        payload = SessionPayload(\n            type=SessionType.POMODORO,\n            pomodoros=0,\n            duration=25 * 60,\n        )\n        subscriber.assert_called_once_with(Events.SESSION_START, payload=payload)\n\n\nclass TestSessionStop:\n    @pytest.mark.parametrize(\"state\", [State.INITIAL, State.ENDED, State.STOPPED, State.STARTED])\n    def test_not_stop_when_session_is_not_running(self, state, session):\n        session.state = state\n\n        assert not session.stop()\n\n    def test_stops_when_session_is_running(self, session, bus, mocker):\n        subscriber = mocker.Mock()\n        bus.connect(Events.SESSION_INTERRUPT, subscriber, False)\n\n        session.ready()\n        session.start()\n        result = session.stop()\n\n        assert result is True\n        payload = SessionPayload(\n            type=SessionType.POMODORO,\n            duration=25 * 60,\n            pomodoros=0,\n        )\n        subscriber.assert_called_once_with(Events.SESSION_INTERRUPT, payload=payload)\n\n\nclass TestSessionReset:\n    @pytest.mark.parametrize(\"state\", [State.INITIAL, State.STARTED])\n    def test_not_reset_when_session_is_running(self, state, session):\n        session.state = state\n\n        assert not session.reset()\n\n    @pytest.mark.parametrize(\n        \"state,session_type,duration\",\n        [\n            (State.ENDED, SessionType.SHORT_BREAK, 5 * 60),\n            (State.STOPPED, SessionType.POMODORO, 25 * 60),\n        ],\n    )\n    def test_resets_when_session_is_not_running(self, state, session_type, duration, session, bus, mocker):\n        session.state = state\n        session.current = session_type\n        session.pomodoros = 1\n\n        subscriber = mocker.Mock()\n        bus.connect(Events.SESSION_RESET, subscriber, False)\n\n        result = session.reset()\n\n        assert result is True\n        payload = SessionPayload(\n            type=session_type,\n            pomodoros=0,\n            duration=duration,\n        )\n        subscriber.assert_called_once_with(Events.SESSION_RESET, payload=payload)\n\n\nclass TestSessionEnd:\n    @pytest.mark.parametrize(\"state\", [State.INITIAL, State.ENDED, State.STOPPED])\n    def test_ends_when_session_is_not_running(self, state, session):\n        session.state = state\n\n        assert not session._end(None, None)\n\n    def test_not_end_when_session_start_but_time_still_running(self, session):\n        session.start()\n\n        assert not session._end(None, None)\n\n    @pytest.mark.parametrize(\n        \"old_session,old_pomodoros,new_session,new_pomodoros\",\n        [\n            (SessionType.POMODORO, 0, SessionType.SHORT_BREAK, 1),\n            (SessionType.LONG_BREAK, 0, SessionType.POMODORO, 0),\n            (SessionType.SHORT_BREAK, 0, SessionType.POMODORO, 0),\n            (SessionType.POMODORO, 3, SessionType.LONG_BREAK, 4),\n        ],\n    )\n    def test_ends_when_session_is_running(\n        self,\n        old_session,\n        old_pomodoros,\n        new_session,\n        new_pomodoros,\n        config,\n        bus,\n        mocker,\n        session,\n    ):\n        session.current = old_session\n        session.pomodoros = old_pomodoros\n\n        config.set(config.DURATION_SECTION, config.DURATION_POMODORO, 0.02)\n        config.set(config.DURATION_SECTION, config.DURATION_LONG_BREAK, 0.02)\n        config.set(config.DURATION_SECTION, config.DURATION_SHORT_BREAK, 0.02)\n        config.parser.getint = config.parser.getfloat\n\n        subscriber = mocker.Mock()\n        bus.connect(Events.SESSION_END, subscriber, False)\n\n        session.ready()\n        session.start()\n        run_loop_for(2)\n\n        payload = create_session_payload(\n            type=old_session,\n            pomodoros=new_pomodoros,\n            duration=1,\n        )\n        subscriber.assert_called_once_with(Events.SESSION_END, payload=payload)\n        assert session.current is new_session\n\n    def test_changes_session_type(self, bus, config, mocker, session):\n        config.set(config.DURATION_SECTION, config.DURATION_POMODORO, 0.02)\n        config.parser.getint = config.parser.getfloat\n\n        subscriber = mocker.Mock()\n        bus.connect(Events.SESSION_CHANGE, subscriber, False)\n\n        session.ready()\n        session.start()\n        run_loop_for(2)\n\n        payload = SessionPayload(\n            type=SessionType.SHORT_BREAK,\n            duration=5 * 60,\n            pomodoros=1,\n        )\n        subscriber.assert_called_once_with(Events.SESSION_CHANGE, payload=payload)\n\n\nclass TestSessionChange:\n    @pytest.mark.parametrize(\"state\", [State.INITIAL, State.STARTED])\n    def test_not_change_when_session_is_running(self, state, session):\n        session.state = state\n\n        assert session.change(session=SessionType.LONG_BREAK) is False\n        assert session.current is SessionType.POMODORO\n\n    @pytest.mark.parametrize(\n        \"state, session_type\",\n        [\n            (State.STOPPED, SessionType.SHORT_BREAK),\n            (State.ENDED, SessionType.LONG_BREAK),\n        ],\n    )\n    def test_changes_when_session_is_not_running(self, state, session_type, bus, config, mocker, session):\n        session.state = state\n        subscriber = mocker.Mock()\n        bus.connect(Events.SESSION_CHANGE, subscriber, False)\n\n        assert session.change(session=session_type) is True\n        assert session.current is session_type\n\n        payload = create_session_payload(\n            type=session_type, duration=config.get_int(config.DURATION_SECTION, session_type.option) * 60\n        )\n        subscriber.assert_called_once_with(Events.SESSION_CHANGE, payload=payload)\n\n    @pytest.mark.parametrize(\"state\", [State.STOPPED, State.ENDED])\n    def test_changes_when_config_change_and_session_is_not_running(self, state, bus, config, mocker, session):\n        session.state = state\n        subscriber = mocker.Mock()\n        bus.connect(Events.SESSION_CHANGE, subscriber, False)\n\n        config.set(config.DURATION_SECTION, SessionType.POMODORO.option, 20)\n\n        payload = create_session_payload(duration=20 * 60)\n        subscriber.assert_called_once_with(Events.SESSION_CHANGE, payload=payload)\n\n    def test_not_change_when_config_section_is_not_timer(self, bus, config, mocker, session):\n        subscriber = mocker.Mock()\n        bus.connect(Events.SESSION_CHANGE, subscriber, False)\n\n        config.set(\"section\", \"option\", \"value\")\n\n        subscriber.assert_not_called()\n\n    def test_not_change_when_config_timer_changes_and_session_is_running(self, bus, config, mocker, session):\n        session.state = State.STARTED\n        subscriber = mocker.Mock()\n        bus.connect(Events.SESSION_CHANGE, subscriber, False)\n\n        config.set(config.DURATION_SECTION, SessionType.POMODORO.option, 24)\n\n        subscriber.assert_not_called()\n\n\n@pytest.mark.parametrize(\n    \"number,session_type\",\n    [\n        (0, SessionType.POMODORO),\n        (1, SessionType.SHORT_BREAK),\n        (2, SessionType.LONG_BREAK),\n    ],\n)\ndef test_type_of(number, session_type):\n    assert SessionType.of(number) == session_type\n\n\ndef test_type_of_unknown():\n    with pytest.raises(Exception):\n        assert SessionType.of(999)\n\n\n@pytest.mark.parametrize(\n    \"session_type, option\",\n    [\n        (SessionType.POMODORO, Config.DURATION_POMODORO),\n        (SessionType.SHORT_BREAK, Config.DURATION_SHORT_BREAK),\n        (SessionType.LONG_BREAK, Config.DURATION_LONG_BREAK),\n    ],\n)\ndef test_type_option(session_type, option):\n    assert session_type.option == option\n"
  },
  {
    "path": "tests/pomodoro/test_timer.py",
    "content": "import pytest\nfrom wiring.scanning import scan_to_graph\n\nfrom tomate.pomodoro import Events, Timer, TimerPayload\nfrom tomate.pomodoro.timer import State\nfrom tomate.ui.testing import run_loop_for\n\n\ndef test_module(bus, graph):\n    graph.register_instance(\"tomate.bus\", bus)\n    scan_to_graph([\"tomate.pomodoro.timer\"], graph)\n\n    instance = graph.get(\"tomate.timer\")\n\n    assert isinstance(instance, Timer)\n\n\nclass TestTimerStart:\n    def test_not_start_when_timer_is_already_running(self, bus):\n        timer = Timer(bus)\n        timer.state = State.STARTED\n\n        assert not timer.start(60)\n\n    @pytest.mark.parametrize(\"state\", [State.ENDED, State.STOPPED])\n    def test_starts_when_timer_not_started_yet(self, bus, mocker, state):\n        timer = Timer(bus)\n        timer.state = state\n\n        subscriber = mocker.Mock()\n        bus.connect(Events.TIMER_START, subscriber, weak=False)\n\n        result = timer.start(60)\n\n        assert result is True\n        subscriber.assert_called_once_with(Events.TIMER_START, payload=TimerPayload(time_left=60, duration=60))\n\n\nclass TestTimerStop:\n    @pytest.mark.parametrize(\"state\", [State.ENDED, State.STOPPED])\n    def test_not_stop_when_timer_is_not_running(self, bus, state):\n        timer = Timer(bus)\n        timer.state = state\n\n        assert not timer.stop()\n\n    def test_stops_when_timer_is_running(self, bus, mocker):\n        timer = Timer(bus)\n        subscriber = mocker.Mock()\n        bus.connect(Events.TIMER_STOP, subscriber, weak=False)\n\n        timer.start(60)\n        result = timer.stop()\n\n        assert result is True\n        assert timer.is_running() is False\n        subscriber.assert_called_once_with(Events.TIMER_STOP, payload=TimerPayload(time_left=0, duration=0))\n\n\nclass TestTimerEnd:\n    @pytest.mark.parametrize(\"state\", [State.ENDED, State.STOPPED])\n    def test_not_end_when_timer_is_not_running(self, bus, state):\n        timer = Timer(bus)\n        timer.state = state\n\n        assert not timer.end()\n\n    def test_ends_when_time_is_up(self, bus, mocker):\n        timer = Timer(bus)\n        changed = mocker.Mock()\n        timer._bus.connect(Events.TIMER_UPDATE, changed, weak=False)\n\n        finished = mocker.Mock()\n        bus.connect(Events.TIMER_END, finished, weak=False)\n\n        timer.start(1)\n        run_loop_for(2)\n\n        assert timer.is_running() is False\n        changed.assert_called_once_with(Events.TIMER_UPDATE, payload=TimerPayload(time_left=0, duration=1))\n        finished.assert_called_once_with(Events.TIMER_END, payload=TimerPayload(time_left=0, duration=1))\n\n\nclass TestTimerPayload:\n    @pytest.mark.parametrize(\n        \"duration,time_left,ratio\",\n        [(100, 99, 0.99), (100, 90, 0.9), (100, 50, 0.5), (100, 0, 0.0)],\n    )\n    def test_remaining_ratio(self, duration, time_left, ratio):\n        payload = TimerPayload(duration=duration, time_left=time_left)\n\n        assert payload.remaining_ratio == ratio\n\n    @pytest.mark.parametrize(\n        \"duration,time_left,ratio\",\n        [\n            (100, 100, 0.0),\n            (100, 99, 0.01),\n            (100, 98, 0.02),\n            (100, 97, 0.03),\n            (100, 96, 0.04),\n            (100, 95, 0.05),\n            (100, 94, 0.06),\n            (100, 93, 0.07),\n            (100, 92, 0.08),\n            (100, 91, 0.09),\n            (100, 90, 0.1),\n            (100, 89, 0.11),\n            (100, 50, 0.5),\n            (100, 15, 0.85),\n            (100, 10, 0.9),\n            (100, 5, 0.95),\n            (100, 0, 1.0),\n        ],\n    )\n    def test_elapsed_ratio(self, duration, time_left, ratio):\n        payload = TimerPayload(duration=duration, time_left=time_left)\n\n        assert payload.elapsed_ratio == ratio\n\n    @pytest.mark.parametrize(\n        \"duration,time_left,percent\",\n        [\n            (100, 100, 0.0),\n            (100, 99, 0.0),\n            (100, 98, 0.0),\n            (100, 97, 0.0),\n            (100, 96, 0.0),\n            (100, 95, 5.0),\n            (100, 94, 5.0),\n            (100, 93, 5.0),\n            (100, 92, 5.0),\n            (100, 91, 5.0),\n            (100, 90, 10.0),\n            (100, 89, 10.0),\n            (100, 6, 90.0),\n            (100, 5, 95.0),\n            (100, 4, 95.0),\n            (100, 3, 95.0),\n            (100, 2, 95.0),\n            (100, 1, 95.0),\n            (100, 0, 100.0),\n        ],\n    )\n    def test_elapsed_percent(self, duration, time_left, percent):\n        payload = TimerPayload(duration=duration, time_left=time_left)\n\n        assert payload.elapsed_percent == percent\n\n    @pytest.mark.parametrize(\n        \"seconds,formatted\",\n        [\n            (25 * 60, \"25:00\"),\n            (15 * 60, \"15:00\"),\n            (5 * 60, \"05:00\"),\n        ],\n    )\n    def test_payload_markup(self, seconds, formatted):\n        payload = TimerPayload(time_left=seconds, duration=0)\n\n        assert payload.countdown == formatted\n"
  },
  {
    "path": "tests/ui/dialogs/test_about.py",
    "content": "import pytest\nfrom gi.repository import Gtk\nfrom wiring.scanning import scan_to_graph\n\nfrom tomate import __version__\nfrom tomate.ui.testing import refresh_gui\n\n\n@pytest.fixture\ndef about(graph, config):\n    graph.register_instance(\"tomate.config\", config)\n    scan_to_graph([\"tomate.ui.dialogs.about\"], graph)\n\n    return graph.get(\"tomate.ui.about\")\n\n\ndef test_module(graph, about):\n    assert graph.get(\"tomate.ui.about\") is about\n\n\ndef test_dialog_info(about):\n    assert about.get_comments() == \"Tomate Pomodoro Timer (GTK+ Interface)\"\n    assert about.get_copyright() == \"2014, Elio Esteves Duarte\"\n    assert about.get_version() == __version__\n    assert about.get_website() == \"https://github.com/eliostvs/tomate-gtk\"\n    assert about.get_website_label() == \"Tomate GTK on Github\"\n    assert about.get_license_type() == Gtk.License.GPL_3_0\n    assert about.get_logo() is not None\n\n\ndef test_close_dialog(about, mocker):\n    about.hide = mocker.Mock()\n\n    about.emit(\"response\", 0)\n    refresh_gui()\n\n    about.hide.assert_called_once()\n"
  },
  {
    "path": "tests/ui/dialogs/test_preference.py",
    "content": "import pytest\nfrom gi.repository import Gtk\nfrom wiring.scanning import scan_to_graph\n\nfrom tomate.pomodoro import Config, Events\nfrom tomate.ui.dialogs import ExtensionTab, PluginGrid, PreferenceDialog, TimerTab\nfrom tomate.ui.testing import TV, Q\n\n\n@pytest.fixture\ndef preference(bus, plugin_engine, config, mocker) -> PreferenceDialog:\n    mocker.patch(\"tomate.ui.dialogs.preference.Gtk.Dialog.run\")\n    return PreferenceDialog(TimerTab(config), ExtensionTab(bus, config, plugin_engine))\n\n\ndef test_preference_module(graph, bus, config, plugin_engine):\n    graph.register_instance(\"tomate.bus\", bus)\n    graph.register_instance(\"tomate.plugin\", plugin_engine)\n    graph.register_instance(\"tomate.config\", config)\n    scan_to_graph([\"tomate.ui.dialogs.preference\"], graph)\n    instance = graph.get(\"tomate.ui.preference\")\n\n    assert isinstance(instance, PreferenceDialog)\n    assert graph.get(\"tomate.ui.preference\") is instance\n\n\ndef test_refresh_reload_plugins(preference, plugin_engine):\n    plugin_engine.collect()\n    preference.run()\n\n    plugin_list = Q.select(preference.widget, Q.props(\"name\", \"plugin.list\"))\n    assert Q.map(plugin_list, TV.model, len) == 2\n\n    for plugin in plugin_engine.all():\n        plugin_engine.remove(plugin)\n\n    preference.run()\n\n    assert Q.map(plugin_list, TV.model, len) == 0\n\n\n@pytest.mark.parametrize(\n    \"plugin,row,columns\",\n    [\n        (\n            \"PluginA\",\n            0,\n            [\"PluginA\", False, \"<b>PluginA</b> (1.0)\\n<small>Description A</small>\"],\n        ),\n        (\n            \"PluginB\",\n            1,\n            [\"PluginB\", True, \"<b>PluginB</b> (2.0)\\n<small>Description B</small>\"],\n        ),\n    ],\n)\ndef test_initial_plugin_list(plugin, row, columns, preference, plugin_engine):\n    plugin_engine.collect()\n    preference.run()\n\n    def get_columns(tree_store: Gtk.TreeStore):\n        return [tree_store[row][column] for column in (PluginGrid.NAME, PluginGrid.ACTIVE, PluginGrid.DETAIL)]\n\n    assert Q.map(Q.select(preference.widget, Q.props(\"name\", \"plugin.list\")), TV.model, get_columns) == columns\n    assert Q.select(preference.widget, Q.props(\"name\", \"plugin.settings\")).props.sensitive is False\n\n\ndef test_open_plugin_settings(preference, plugin_engine):\n    plugin_engine.collect()\n    preference.run()\n\n    Q.map(\n        Q.select(preference.widget, Q.props(\"name\", \"plugin.list\")),\n        TV.column(Q.props(\"title\", \"Active\")),\n        TV.cell_renderer(0),\n        Q.emit(\"toggled\", 0),\n    )\n\n    settings_button = Q.select(preference.widget, Q.props(\"name\", \"plugin.settings\"))\n    assert settings_button.props.sensitive is True\n\n    settings_button.emit(\"clicked\")\n    plugin_a = plugin_engine.lookup(\"PluginA\")\n    assert plugin_a.plugin_object.parent == preference.widget\n\n\ndef test_connect_and_disconnect_plugins(bus, plugin_engine, preference):\n    plugin_engine.collect()\n    preference.run()\n\n    result = bus.send(Events.WINDOW_SHOW)\n    assert len(result) == 1 and result[0] == \"plugin_b\"\n\n    def toggle_plugin(row: int):\n        Q.map(\n            Q.select(preference.widget, Q.props(\"name\", \"plugin.list\")),\n            TV.column(Q.props(\"title\", \"Active\")),\n            TV.cell_renderer(0),\n            Q.emit(\"toggled\", row),\n        )\n\n    toggle_plugin(0)\n    toggle_plugin(1)\n\n    result = bus.send(Events.WINDOW_SHOW)\n    assert len(result) == 1 and result[0] == \"plugin_a\"\n\n\n@pytest.mark.parametrize(\n    \"duration_name,option,value\",\n    [\n        (\"duration.pomodoro\", Config.DURATION_POMODORO, 24),\n        (\"duration.shortbreak\", Config.DURATION_SHORT_BREAK, 4),\n        (\"duration.longbreak\", Config.DURATION_LONG_BREAK, 14),\n    ],\n)\ndef test_save_config_when_task_duration_change(duration_name, option, value, config, preference):\n    spin_button = Q.select(preference.widget, Q.props(\"name\", duration_name))\n    assert spin_button is not None\n\n    spin_button.props.value = value\n    spin_button.emit(\"value-changed\")\n\n    assert config.get_int(Config.DURATION_SECTION, option) == value\n"
  },
  {
    "path": "tests/ui/test_shortcut.py",
    "content": "import pytest\nfrom gi.repository import Gtk\nfrom wiring.scanning import scan_to_graph\n\nfrom tomate.ui import Shortcut, ShortcutEngine\nfrom tomate.ui.testing import active_shortcut\n\n\n@pytest.fixture\ndef shortcut_engine(bus, config, graph) -> ShortcutEngine:\n    graph.register_instance(\"tomate.config\", config)\n    scan_to_graph([\"tomate.ui.shortcut\"], graph)\n    return graph.get(\"tomate.ui.shortcut\")\n\n\ndef test_module(graph, shortcut_engine):\n    instance = graph.get(\"tomate.ui.shortcut\")\n\n    assert isinstance(instance, ShortcutEngine)\n    assert instance is shortcut_engine\n\n\ndef test_label(shortcut_engine):\n    label = shortcut_engine.label(Shortcut(\"test\", \"\"))\n\n    assert label == \"Ctrl+S\"\n\n\ndef test_label_with_fallback(shortcut_engine):\n    label = shortcut_engine.label(Shortcut(\"\", \"<control>p\"))\n\n    assert label == \"Ctrl+P\"\n\n\ndef test_connect(shortcut_engine, mocker):\n    callback = mocker.Mock(return_value=True)\n    shortcut = Shortcut(\"start\", \"<control>s\")\n\n    shortcut_engine.connect(shortcut, callback)\n    assert active_shortcut(shortcut_engine, shortcut) is True\n\n    key, mod = Gtk.accelerator_parse(shortcut.value)\n    callback.assert_called_once_with(shortcut_engine.accel_group, mocker.ANY, key, mod)\n\n\ndef test_disconnect(shortcut_engine, mocker):\n    shortcut = Shortcut(\"start\", \"<control>s\")\n    shortcut_engine.connect(shortcut, mocker.Mock())\n\n    shortcut_engine.disconnect(shortcut)\n\n    assert active_shortcut(shortcut_engine, shortcut) is False\n\n\ndef test_change(shortcut_engine, mocker):\n    callback = mocker.Mock(return_value=True)\n    old_shortcut = Shortcut(\"start\", \"<control>a\")\n    new_shortcut = Shortcut(\"start\", \"<control>b\")\n\n    shortcut_engine.connect(old_shortcut, callback)\n    shortcut_engine.change(new_shortcut)\n\n    assert active_shortcut(shortcut_engine, old_shortcut) is False\n    assert active_shortcut(shortcut_engine, new_shortcut) is True\n\n    key, mod = Gtk.accelerator_parse(new_shortcut.value)\n    callback.assert_called_once_with(shortcut_engine.accel_group, mocker.ANY, key, mod)\n"
  },
  {
    "path": "tests/ui/test_systray.py",
    "content": "import pytest\nfrom gi.repository import Gtk\nfrom wiring.scanning import scan_to_graph\n\nfrom tomate.pomodoro import Events\nfrom tomate.ui import SystrayMenu\nfrom tomate.ui.testing import refresh_gui\n\n\n@pytest.fixture\ndef window():\n    return Gtk.Label()\n\n\n@pytest.fixture\ndef subject(graph, bus, window):\n    graph.register_instance(\"tomate.bus\", bus)\n    graph.register_instance(\"tomate.ui.view\", window)\n    scan_to_graph([\"tomate.ui.systray\"], graph)\n    return graph.get(\"tomate.ui.systray.menu\")\n\n\ndef test_module(graph, subject):\n    instance = graph.get(\"tomate.ui.systray.menu\")\n\n    assert isinstance(instance, SystrayMenu)\n    assert instance is subject\n\n\ndef test_hide_view_when_hide_menu_is_clicked(window, subject):\n    window.props.visible = False\n\n    subject.hide_item.emit(\"activate\")\n\n    refresh_gui()\n\n    assert window.props.visible is False\n\n\ndef test_show_window_when_hide_item_is_clicked(window, subject):\n    window.props.visible = False\n\n    subject.show_item.emit(\"activate\")\n\n    refresh_gui()\n\n    assert window.props.visible is True\n\n\n@pytest.mark.parametrize(\"event,hide,show\", [(Events.WINDOW_HIDE, False, True), (Events.WINDOW_SHOW, True, False)])\ndef test_change_items_visibility(event, hide, show, bus, subject):\n    bus.send(event)\n\n    assert subject.hide_item.props.visible is hide\n    assert subject.show_item.props.visible is show\n"
  },
  {
    "path": "tests/ui/test_window.py",
    "content": "import pytest\nfrom gi.repository import Gdk, Gtk\nfrom wiring.scanning import scan_to_graph\n\nfrom tomate.pomodoro import Events\nfrom tomate.ui import Systray, Window\nfrom tomate.ui.testing import Q, active_shortcut, create_session_payload\n\n\n@pytest.fixture\ndef window(bus, config, graph, session) -> Window:\n    graph.register_instance(\"tomate.bus\", bus)\n    graph.register_instance(\"tomate.config\", config)\n    graph.register_instance(\"tomate.session\", session)\n\n    namespaces = [\n        \"tomate.ui\",\n        \"tomate.pomodoro.plugin\",\n    ]\n    scan_to_graph(namespaces, graph)\n    return graph.get(\"tomate.ui.view\")\n\n\ndef test_module(graph, window):\n    instance = graph.get(\"tomate.ui.view\")\n\n    assert isinstance(instance, Window)\n    assert instance is window\n\n\ndef test_init(session, window):\n    session.ready.assert_called_once_with()\n\n    # session button\n    assert Q.select(window.widget, Q.props(\"name\", \"session.pomodoro\"))\n    assert Q.select(window.widget, Q.props(\"name\", \"session.short_break\"))\n    assert Q.select(window.widget, Q.props(\"name\", \"session.long_break\"))\n\n    # headerbar\n    assert Q.select(window.widget, Q.props(\"name\", \"session.start\"))\n    assert Q.select(window.widget, Q.props(\"name\", \"session.reset\"))\n    assert Q.select(window.widget, Q.props(\"name\", \"session.stop\"))\n\n    # countdown\n    assert Q.select(window.widget, Q.props(\"label\", \"00:00\"))\n\n\ndef test_shortcuts(shortcut_engine, window):\n    from tomate.ui.widgets import HeaderBar\n\n    assert active_shortcut(shortcut_engine, HeaderBar.START_SHORTCUT, window=window.widget) is True\n\n\ndef test_run(mocker, window):\n    gtk_main = mocker.patch(\"tomate.ui.window.Gtk.main\")\n    show_all = mocker.patch(\"tomate.ui.window.Gtk.Window.show_all\")\n\n    window.run()\n\n    gtk_main.assert_called_once_with()\n    show_all.assert_called_once_with()\n\n\nclass TestWindowHide:\n    def test_iconify_when_tray_icon_plugin_is_not_registered(self, window, bus, mocker):\n        subscriber = mocker.Mock()\n        bus.connect(Events.WINDOW_HIDE, subscriber, weak=False)\n\n        result = window.hide()\n\n        assert result is Gtk.true\n        subscriber.assert_called_once_with(Events.WINDOW_HIDE, payload=None)\n\n    def test_deletes_when_tray_icon_plugin_is_registered(self, bus, graph, mocker, window):\n        graph.register_factory(Systray, mocker.Mock)\n        subscriber = mocker.Mock()\n        bus.connect(Events.WINDOW_HIDE, subscriber, weak=False)\n        window.widget.set_visible(True)\n\n        result = window.hide()\n\n        assert result\n        assert window.widget.get_visible() is False\n        subscriber.assert_called_once_with(Events.WINDOW_HIDE, payload=None)\n\n\nclass TestWindowQuit:\n    def test_quits_when_timer_is_not_running(self, mocker, session, window):\n        main_quit = mocker.patch(\"tomate.ui.window.Gtk.main_quit\")\n        session.is_running.return_value = False\n\n        window.widget.emit(\"delete-event\", Gdk.Event.new(Gdk.EventType.DELETE))\n\n        main_quit.assert_called_once_with()\n\n    def test_hides_when_timer_is_running(self, bus, mocker, session, window):\n        session.is_running.return_value = True\n        subscriber = mocker.Mock()\n        bus.connect(Events.WINDOW_HIDE, subscriber, weak=False)\n\n        window.widget.emit(\"delete-event\", Gdk.Event.new(Gdk.EventType.DELETE))\n\n        subscriber.assert_called_once_with(Events.WINDOW_HIDE, payload=None)\n\n\ndef test_shows_window_when_session_end(bus, mocker, window):\n    window.widget.props.visible = False\n    subscriber = mocker.Mock()\n    bus.connect(Events.WINDOW_SHOW, subscriber, weak=False)\n\n    payload = create_session_payload()\n    bus.send(Events.SESSION_END, payload=payload)\n\n    assert window.widget.props.visible is True\n    subscriber.assert_called_once_with(Events.WINDOW_SHOW, payload=None)\n"
  },
  {
    "path": "tests/ui/widgets/test_countdown.py",
    "content": "import random\n\nimport pytest\nfrom wiring.scanning import scan_to_graph\n\nfrom tomate.pomodoro import Events, TimerPayload\nfrom tomate.ui.testing import create_session_payload\nfrom tomate.ui.widgets import Countdown\n\n\n@pytest.fixture\ndef countdown(bus, graph) -> Countdown:\n    graph.register_instance(\"tomate.bus\", bus)\n    scan_to_graph([\"tomate.ui.widgets.countdown\"], graph)\n    return graph.get(\"tomate.ui.countdown\")\n\n\ndef test_module(countdown, graph):\n    instance = graph.get(\"tomate.ui.countdown\")\n\n    assert isinstance(instance, Countdown)\n    assert instance is countdown\n\n\n@pytest.mark.parametrize(\n    \"event, payload\",\n    [\n        (Events.SESSION_READY, create_session_payload(duration=random.randint(1, 100))),\n        (Events.SESSION_INTERRUPT, create_session_payload(duration=random.randint(1, 100))),\n        (Events.SESSION_CHANGE, create_session_payload(duration=random.randint(1, 100))),\n        (Events.TIMER_UPDATE, TimerPayload(time_left=random.randint(1, 100), duration=0)),\n    ],\n)\ndef test_updates_countdown_when_session_state_changes(event, payload, bus, countdown):\n    bus.send(event, payload=payload)\n\n    assert payload.countdown in countdown.widget.get_text()\n"
  },
  {
    "path": "tests/ui/widgets/test_headerbar.py",
    "content": "import pytest\nfrom gi.repository import Gtk\nfrom wiring.scanning import scan_to_graph\n\nfrom tomate.pomodoro import Events\nfrom tomate.ui.testing import Q, active_shortcut, create_session_payload, refresh_gui\nfrom tomate.ui.widgets import HeaderBar, HeaderBarMenu\n\n\nclass TestHeaderBar:\n    @pytest.fixture\n    def menu(self, mocker):\n        return mocker.Mock(spec=HeaderBarMenu, widget=Gtk.Menu())\n\n    @pytest.fixture\n    def headerbar(self, graph, menu, shortcut_engine, session, bus, mocker) -> HeaderBar:\n        graph.register_instance(\"tomate.bus\", bus)\n        graph.register_instance(\"tomate.session\", session)\n        graph.register_factory(\"tomate.ui.about\", mocker.Mock)\n        graph.register_factory(\"tomate.ui.preference\", mocker.Mock)\n        graph.register_instance(\"tomate.ui.menu\", menu)\n        graph.register_instance(\"tomate.ui.shortcut\", shortcut_engine)\n\n        # gtk shortcuts binds leave beyond the scope\n        shortcut_engine.disconnect(HeaderBar.START_SHORTCUT)\n        shortcut_engine.disconnect(HeaderBar.STOP_SHORTCUT)\n        shortcut_engine.disconnect(HeaderBar.RESET_SHORTCUT)\n\n        namespaces = [\"tomate.ui.widgets.headerbar\"]\n\n        scan_to_graph(namespaces, graph)\n\n        return graph.get(\"tomate.ui.headerbar\")\n\n    def test_module(self, graph, headerbar):\n        instance = graph.get(\"tomate.ui.headerbar\")\n\n        assert isinstance(instance, HeaderBar)\n        assert instance is headerbar\n\n    @pytest.mark.parametrize(\n        \"shortcut,action\",\n        [\n            (HeaderBar.START_SHORTCUT, \"start\"),\n            (HeaderBar.STOP_SHORTCUT, \"stop\"),\n            (HeaderBar.RESET_SHORTCUT, \"reset\"),\n        ],\n    )\n    def test_shortcuts(self, shortcut, action, headerbar, menu, session, shortcut_engine):\n        assert active_shortcut(shortcut_engine, shortcut)\n\n        getattr(session, action).assert_called_once_with()\n\n    @pytest.mark.parametrize(\n        \"button_name,action\",\n        [\n            (HeaderBar.START_SHORTCUT.name, \"start\"),\n            (HeaderBar.STOP_SHORTCUT.name, \"stop\"),\n            (HeaderBar.RESET_SHORTCUT.name, \"reset\"),\n        ],\n    )\n    def test_change_session(self, button_name, action, session, headerbar):\n        button = Q.select(headerbar.widget, Q.props(\"name\", button_name))\n\n        button.emit(\"clicked\")\n        refresh_gui()\n\n        getattr(session, action).assert_called_once_with()\n\n    @pytest.mark.parametrize(\n        \"button_name,tooltip\",\n        [\n            (HeaderBar.START_SHORTCUT.name, \"Starts the session (Ctrl+S)\"),\n            (HeaderBar.STOP_SHORTCUT.name, \"Stops the session (Ctrl+P)\"),\n            (HeaderBar.RESET_SHORTCUT.name, \"Clear session count (Ctrl+R)\"),\n            (HeaderBarMenu.PREFERENCE_SHORTCUT.name, \"Open preferences (Ctrl+,)\"),\n        ],\n    )\n    def test_buttons_tooltip(self, button_name, tooltip, headerbar):\n        button = Q.select(headerbar.widget, Q.props(\"name\", button_name))\n        assert tooltip == button.props.tooltip_text\n\n    def test_enable_only_the_stop_button_when_session_starts(self, bus, headerbar):\n        bus.send(Events.SESSION_START)\n\n        assert Q.select(headerbar.widget, Q.props(\"name\", HeaderBar.START_SHORTCUT.name)).props.visible is False\n        assert Q.select(headerbar.widget, Q.props(\"name\", HeaderBar.STOP_SHORTCUT.name)).props.visible is True\n        assert Q.select(headerbar.widget, Q.props(\"name\", HeaderBar.RESET_SHORTCUT.name)).props.sensitive is False\n\n    def test_disables_reset_button_when_session_is_reset(self, headerbar, bus, session):\n        reset_button = Q.select(headerbar.widget, Q.props(\"name\", headerbar.RESET_SHORTCUT.name))\n        reset_button.props.sensitive = True\n\n        bus.send(Events.SESSION_RESET)\n\n        assert reset_button.props.sensitive is False\n        assert headerbar.widget.props.title == \"No session yet\"\n\n    @pytest.mark.parametrize(\n        \"event,reset,title,payload\",\n        [\n            (Events.SESSION_INTERRUPT, False, \"No session yet\", create_session_payload()),\n            (Events.SESSION_END, True, \"Session 1\", create_session_payload(pomodoros=1)),\n        ],\n    )\n    def test_buttons_visibility_and_title_in_the_first_session(self, event, title, reset, headerbar, payload, bus):\n        bus.send(event, payload=payload)\n\n        assert Q.select(headerbar.widget, Q.props(\"name\", headerbar.START_SHORTCUT.name)).props.visible is True\n        assert Q.select(headerbar.widget, Q.props(\"name\", headerbar.STOP_SHORTCUT.name)).props.visible is False\n        assert Q.select(headerbar.widget, Q.props(\"name\", headerbar.RESET_SHORTCUT.name)).props.sensitive is reset\n        assert headerbar.widget.props.title == title\n\n\nclass TestHeaderBarMenu:\n    @pytest.fixture\n    def preference(self, mocker):\n        return mocker.Mock(widget=mocker.Mock(spec=Gtk.Dialog))\n\n    @pytest.fixture()\n    def about(self, mocker):\n        return mocker.Mock(widget=mocker.Mock(spec=Gtk.Dialog))\n\n    @pytest.fixture\n    def menu(self, bus, about, preference, shortcut_engine) -> HeaderBarMenu:\n        shortcut_engine.disconnect(HeaderBarMenu.PREFERENCE_SHORTCUT)\n\n        return HeaderBarMenu(bus, about, preference, shortcut_engine)\n\n    def test_module(self, about, bus, preference, graph, shortcut_engine):\n        graph.register_instance(\"tomate.bus\", bus)\n        graph.register_instance(\"tomate.ui.about\", about)\n        graph.register_instance(\"tomate.ui.preference\", preference)\n        graph.register_instance(\"tomate.ui.shortcut\", shortcut_engine)\n\n        namespaces = [\"tomate.ui.widgets.headerbar\"]\n        scan_to_graph(namespaces, graph)\n\n        instance = graph.get(\"tomate.ui.headerbar.menu\")\n\n        assert isinstance(instance, HeaderBarMenu)\n        assert instance is graph.get(\"tomate.ui.headerbar.menu\")\n\n    @pytest.mark.parametrize(\n        \"widget,label,mock_name\",\n        [\n            (\"header.menu.preference\", \"Preferences\", \"preference\"),\n            (\"header.menu.about\", \"About\", \"about\"),\n        ],\n    )\n    def test_menu_items(self, widget, label, mock_name, menu, about, preference):\n        menu_item = Q.select(menu.widget, Q.props(\"name\", widget))\n        assert menu_item.props.label == label\n\n        menu_item.emit(\"activate\")\n        refresh_gui()\n\n        dialog = locals()[mock_name].widget\n        dialog.run.assert_called_once_with()\n\n    def test_shortcut(self, menu, shortcut_engine, preference):\n        assert active_shortcut(shortcut_engine, HeaderBarMenu.PREFERENCE_SHORTCUT) is True\n\n        preference.widget.run.assert_called_once_with()\n"
  },
  {
    "path": "tests/ui/widgets/test_session_button.py",
    "content": "import pytest\nfrom wiring.scanning import scan_to_graph\n\nfrom tomate.pomodoro import Events, SessionType\nfrom tomate.ui.testing import Q, active_shortcut, create_session_payload, refresh_gui\nfrom tomate.ui.widgets import SessionButton\n\n\n@pytest.fixture\ndef session_button(bus, graph, session, shortcut_engine) -> SessionButton:\n    graph.register_instance(\"tomate.bus\", bus)\n    graph.register_instance(\"tomate.session\", session)\n    graph.register_instance(\"tomate.ui.shortcut\", shortcut_engine)\n    scan_to_graph([\"tomate.ui.widgets.session_button\"], graph)\n\n    # clean key binds between tests\n    shortcut_engine.disconnect(SessionButton.POMODORO_SHORTCUT)\n    shortcut_engine.disconnect(SessionButton.SHORT_BREAK_SHORTCUT)\n    shortcut_engine.disconnect(SessionButton.LONG_BREAK_SHORTCUT)\n\n    return graph.get(\"tomate.ui.taskbutton\")\n\n\ndef test_module(graph, session_button):\n    instance = graph.get(\"tomate.ui.taskbutton\")\n\n    assert isinstance(instance, SessionButton)\n    assert instance is session_button\n\n\n@pytest.mark.parametrize(\n    \"button_name,label,tooltip_text\",\n    [\n        (SessionButton.POMODORO_SHORTCUT.name, \"Pomodoro\", \"Pomodoro (Ctrl+1)\"),\n        (SessionButton.SHORT_BREAK_SHORTCUT.name, \"Short Break\", \"Short Break (Ctrl+2)\"),\n        (SessionButton.LONG_BREAK_SHORTCUT.name, \"Long Break\", \"Long Break (Ctrl+3)\"),\n    ],\n)\ndef test_buttons_content(button_name, label, tooltip_text, session_button):\n    button = Q.select(session_button.widget, Q.props(\"name\", button_name))\n\n    assert button.props.tooltip_text == tooltip_text\n\n    assert Q.select(button, Q.props(\"label\", label))\n\n\ndef test_disables_buttons_when_session_starts(bus, session_button):\n    bus.send(Events.SESSION_START)\n\n    assert session_button.widget.props.sensitive is False\n\n\n@pytest.mark.parametrize(\n    \"event,payload,session_type\",\n    [\n        (Events.SESSION_INTERRUPT, create_session_payload(type=SessionType.LONG_BREAK), SessionType.LONG_BREAK),\n        (Events.SESSION_READY, create_session_payload(), SessionType.POMODORO),\n    ],\n)\ndef test_selects_button_when_session_stops_and_begins(event, payload, session_type, bus, session_button, session):\n    session_button.widget.props.sensitive = False\n\n    bus.send(event, payload=payload)\n\n    assert session_button.widget.props.sensitive is True\n    assert session_button.widget.get_selected() is session_type.value\n\n\n@pytest.mark.parametrize(\"session_type\", [SessionType.POMODORO, SessionType.SHORT_BREAK, SessionType.LONG_BREAK])\ndef test_changes_session_when_button_is_clicked(session_type, session_button, session):\n    session_button.widget.emit(\"mode_changed\", session_type.value)\n\n    refresh_gui()\n\n    session.change.assert_called_once_with(session_type)\n\n\n@pytest.mark.parametrize(\n    \"shortcut,session_type\",\n    [\n        (SessionButton.POMODORO_SHORTCUT, SessionType.POMODORO),\n        (SessionButton.SHORT_BREAK_SHORTCUT, SessionType.SHORT_BREAK),\n        (SessionButton.LONG_BREAK_SHORTCUT, SessionType.LONG_BREAK),\n    ],\n)\ndef test_shortcuts(shortcut, session_type, session_button, shortcut_engine, session):\n    assert active_shortcut(shortcut_engine, shortcut) is True\n\n    session.change.assert_called_once_with(session_type)\n\n\ndef test_selects_button_when_session_changes(bus, session_button, session):\n    bus.send(Events.SESSION_CHANGE, payload=create_session_payload(type=SessionType.SHORT_BREAK))\n\n    assert session_button.widget.get_selected() is SessionType.SHORT_BREAK.value\n"
  },
  {
    "path": "tomate/__init__.py",
    "content": "__version__ = \"0.25.2\"\n"
  },
  {
    "path": "tomate/__main__.py",
    "content": "from .main import main\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "tomate/audio/__init__.py",
    "content": "from .player import GStreamerPlayer\n\n__all__ = [\"GStreamerPlayer\"]\n"
  },
  {
    "path": "tomate/audio/player.py",
    "content": "import logging\n\nimport gi\n\ngi.require_version(\"Gst\", \"1.0\")\ngi.require_version(\"Gtk\", \"3.0\")\n\nfrom gi.repository import Gst\n\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger(__name__)\n\n\nclass GStreamerPlayer:\n    def __init__(self, repeat=False):\n        Gst.init(None)\n        self.repeat = repeat\n        self._file = None\n        self._is_about_to_finished = False\n\n        self._playbin = Gst.ElementFactory.make(\"playbin\", \"player\")\n        self._volume_filter = Gst.ElementFactory.make(\"volume\", \"volume\")\n        self._playbin.props.audio_filter = self._volume_filter\n        self._playbin.bus.add_signal_watch()\n        self._playbin.bus.connect(\"message\", self._on_bus_callback)\n        self._playbin.connect(\"about-to-finish\", self._on_about_to_finish)\n        self._playbin.volume = 1.0\n        self._volume_filter.volume = 0\n\n    @property\n    def file(self) -> str:\n        return self._file\n\n    @file.setter\n    def file(self, filepath: str) -> None:\n        _, state, pending_state = self._playbin.get_state(Gst.CLOCK_TIME_NONE)\n        self._file = filepath\n\n        logger.debug(f\"action=set_file filepath={filepath} state={state} pending_state={pending_state}\")\n\n        if not self._file:\n            self.stop()\n            return\n\n        if pending_state != Gst.State.VOID_PENDING:\n            state = pending_state\n\n        if state == Gst.State.PLAYING or state == Gst.State.PAUSED:\n            self._is_about_to_finished = False\n            self._playbin.set_state(Gst.State.READY)\n            self._playbin.props.uri = self._file\n            self._playbin.set_state(state)\n\n    @property\n    def volume(self) -> float:\n        return self._volume_filter.props.volume\n\n    @volume.setter\n    def volume(self, volume: float) -> None:\n        logger.debug(f\"action=set_volume volume={volume}\")\n        self._volume_filter.props.volume = max(0.0, min(1.0, volume))\n\n    def play(self) -> None:\n        logger.debug(\"action=play\")\n        self._playbin.props.uri = self._file\n        self._playbin.set_state(Gst.State.PLAYING)\n\n    def stop(self) -> None:\n        logger.debug(\"action=stop\")\n        self._playbin.set_state(Gst.State.NULL)\n\n    def _on_bus_callback(self, _, message):\n        if message.type == Gst.MessageType.EOS:\n            if self._is_about_to_finished:\n                self._is_about_to_finished = False\n            else:\n                self._finished()\n\n        elif message.type == Gst.MessageType.ERROR:\n            logger.error(\"action=audio_failed message='%s-%s'\", *message.parse_error())\n            self.stop()\n\n    def _on_about_to_finish(self, _) -> None:\n        logger.debug(\"action=about_to_finish\")\n        self._is_about_to_finished = True\n        self._finished()\n\n    def _finished(self) -> None:\n        current_uri = self._playbin.props.current_uri\n\n        logger.debug(f\"action=finished repeat={self.repeat} current_uri={current_uri}\")\n\n        if current_uri and self.repeat:\n            self._playbin.props.uri = current_uri\n"
  },
  {
    "path": "tomate/main.py",
    "content": "import argparse\nimport locale\nimport logging\nfrom locale import gettext as _\n\nimport gi\n\ngi.require_version(\"Gdk\", \"3.0\")\ngi.require_version(\"Gtk\", \"3.0\")\n\nfrom gi.repository import Gdk\nfrom wiring.scanning import scan_to_graph\n\nfrom tomate.pomodoro.app import Application\nfrom tomate.pomodoro.graph import graph\n\nlocale.textdomain(\"tomate\")\nlogger = logging.getLogger(__name__)\n\n\ndef main():\n    try:\n        options = parse_options()\n        setup_logging(options)\n\n        scan_to_graph([\"tomate\"], graph)\n        app = Application.from_graph(graph)\n\n        app.Run()\n        if app.IsRunning():\n            Gdk.notify_startup_complete()\n\n    except Exception as ex:\n        logger.error(ex, exc_info=True)\n        raise ex\n\n\ndef setup_logging(options):\n    level = logging.DEBUG if options.verbose else logging.INFO\n    fmt = \"%(levelname)s:%(asctime)s:%(name)s:%(message)s\"\n    logging.basicConfig(level=level, format=fmt)\n\n\ndef parse_options():\n    parser = argparse.ArgumentParser(prog=\"tomate-gtk\")\n\n    parser.add_argument(\n        \"-v\",\n        \"--verbose\",\n        default=False,\n        action=\"store_true\",\n        help=_(\"Show debug messages\"),\n    )\n\n    return parser.parse_args()\n"
  },
  {
    "path": "tomate/pomodoro/__init__.py",
    "content": "from .app import Application\nfrom .config import Config\nfrom .config import Payload as ConfigPayload\nfrom .event import Bus, Events, Subscriber, on\nfrom .graph import graph\nfrom .plugin import Plugin, PluginEngine, suppress_errors\nfrom .session import Payload as SessionPayload\nfrom .session import Session\nfrom .session import Type as SessionType\nfrom .timer import Payload as TimerPayload\nfrom .timer import Timer, format_seconds\n\n__all__ = [\n    \"Application\",\n    \"Bus\",\n    \"Config\",\n    \"ConfigPayload\",\n    \"Events\",\n    \"Plugin\",\n    \"PluginEngine\",\n    \"Session\",\n    \"SessionPayload\",\n    \"SessionType\",\n    \"Subscriber\",\n    \"Timer\",\n    \"TimerPayload\",\n    \"format_seconds\",\n    \"graph\",\n    \"on\",\n    \"suppress_errors\",\n]\n"
  },
  {
    "path": "tomate/pomodoro/app.py",
    "content": "import enum\n\nimport dbus.service\nfrom dbus.mainloop.glib import DBusGMainLoop\nfrom wiring import SingletonScope, inject\nfrom wiring.scanning import register\n\nfrom .plugin import PluginEngine\n\n\nclass State(enum.Enum):\n    STOPPED = 1\n    STARTED = 2\n\n\n@register.factory(\"tomate.app\", scope=SingletonScope)\nclass Application(dbus.service.Object):\n    BUS_NAME = \"com.github.Tomate\"\n    BUS_PATH = \"/com/github/Tomate\"\n    BUS_INTERFACE = \"com.github.Tomate\"\n    SPEC = \"tomate.app\"\n\n    @inject(bus=\"dbus.session\", window=\"tomate.ui.view\", plugins=\"tomate.plugin\")\n    def __init__(self, bus, window, plugins: PluginEngine):\n        dbus.service.Object.__init__(self, bus, self.BUS_PATH)\n        self.state = State.STOPPED\n        self._window = window\n        plugins.collect()\n\n    @dbus.service.method(BUS_INTERFACE, out_signature=\"b\")\n    def IsRunning(self):\n        return self.state == State.STARTED\n\n    @dbus.service.method(BUS_INTERFACE, out_signature=\"b\")\n    def Run(self):\n        if self.IsRunning():\n            self._window.show()\n        else:\n            self.state = State.STARTED\n            self._window.run()\n\n        return True\n\n    @classmethod\n    def from_graph(cls, graph, bus=dbus.SessionBus(mainloop=DBusGMainLoop())):\n        request = bus.request_name(cls.BUS_NAME, dbus.bus.NAME_FLAG_DO_NOT_QUEUE)\n\n        if request != dbus.bus.REQUEST_NAME_REPLY_EXISTS:\n            graph.register_instance(\"dbus.session\", bus)\n            instance = graph.get(cls.SPEC)\n        else:\n            bus_object = bus.get_object(cls.BUS_NAME, cls.BUS_PATH)\n            instance = dbus.Interface(bus_object, cls.BUS_INTERFACE)\n\n        return instance\n"
  },
  {
    "path": "tomate/pomodoro/config.py",
    "content": "import logging\nimport os\nfrom collections import namedtuple\nfrom configparser import RawConfigParser\nfrom typing import List, Union\n\nfrom wiring import SingletonScope, inject\nfrom wiring.scanning import register\nfrom xdg import BaseDirectory, IconTheme\n\nfrom .event import Bus, Events\n\nlogger = logging.getLogger(__name__)\n\nPayload = namedtuple(\"ConfigPayload\", \"action section option value\")\n\n\n@register.factory(\"tomate.config\", scope=SingletonScope)\nclass Config:\n    APP_NAME = \"tomate\"\n    SHORTCUT_SECTION = \"shortcuts\"\n    DURATION_SECTION = \"timer\"\n    DURATION_LONG_BREAK = \"longbreak_duration\"\n    DURATION_POMODORO = \"pomodoro_duration\"\n    DURATION_SHORT_BREAK = \"shortbreak_duration\"\n    DEFAULTS = {\n        DURATION_POMODORO: \"25\",\n        DURATION_SHORT_BREAK: \"5\",\n        DURATION_LONG_BREAK: \"15\",\n        \"long_break_interval\": \"4\",\n    }\n\n    @inject(bus=\"tomate.bus\")\n    def __init__(self, bus: Bus, parser=RawConfigParser(defaults=DEFAULTS, strict=True)):\n        self.parser = parser\n        self._bus = bus\n        self.load()\n\n    def __getattr__(self, attr):\n        return getattr(self.parser, attr)\n\n    def load(self) -> None:\n        logger.debug(\"action=load uri=%s\", self.config_path())\n\n        self.parser.read(self.config_path())\n\n    def save(self) -> None:\n        logger.debug(\"action=write uri=%s\", self.config_path())\n\n        with open(self.config_path(), \"w\") as f:\n            self.parser.write(f)\n\n    def config_path(self) -> str:\n        BaseDirectory.save_config_path(self.APP_NAME)\n        return os.path.join(BaseDirectory.xdg_config_home, self.APP_NAME, self.APP_NAME + \".conf\")\n\n    def media_uri(self, *resources: str) -> str:\n        return \"file://\" + self._resource_path(self.APP_NAME, \"media\", *resources)\n\n    def plugin_paths(self) -> List[str]:\n        return remove_duplicates(self._load_data_paths(self.APP_NAME, \"plugins\"))\n\n    def icon_paths(self) -> List[str]:\n        return remove_duplicates(self._load_data_paths(\"icons\"))\n\n    def _resource_path(self, *resources) -> str:\n        for resource in self._load_data_paths(*resources):\n            if os.path.exists(resource):\n                return resource\n\n        raise EnvironmentError(\"Resource '%s' not found!\" % resources[-1])\n\n    def _load_data_paths(self, *resources) -> List[str]:\n        return [path for path in BaseDirectory.load_data_paths(*resources)]\n\n    def icon_path(self, iconname, size=None, theme=None) -> str:\n        icon_path = IconTheme.getIconPath(iconname, size, theme, extensions=[\"png\", \"svg\", \"xpm\"])\n\n        if icon_path is not None:\n            return icon_path\n\n        raise EnvironmentError(\"Icon '%s' not found!\" % iconname)\n\n    def get_int(self, section: str, option: str, fallback=None) -> int:\n        return self.get(section, option, fallback, method=\"getint\")\n\n    def get_bool(self, section: str, option: str, fallback=None) -> bool:\n        return self.get(section, option, fallback, method=\"getboolean\")\n\n    def get_float(self, section: str, option: str, fallback=None) -> int:\n        return self.get(section, option, fallback, method=\"getfloat\")\n\n    def get(self, section: str, option: str, fallback=None, method=\"get\") -> Union[str, int, bool]:\n        section = self.normalize(section)\n        option = self.normalize(option)\n        if not self.parser.has_section(section):\n            self.parser.add_section(section)\n\n        logger.debug(\"action=get section=%s option=%s\", section, option)\n\n        return getattr(self.parser, method)(section, option, fallback=fallback)\n\n    def set(self, section: str, option: str, value) -> None:\n        logger.debug(\"action=set section=%s option=%s value=%s\", section, option, value)\n\n        section = self.normalize(section)\n        option = self.normalize(option)\n        if not self.parser.has_section(section):\n            self.parser.add_section(section)\n        self.parser.set(section, option, value)\n        self.save()\n\n        payload = Payload(action=\"set\", section=section, option=option, value=value)\n        self._bus.send(Events.CONFIG_CHANGE, payload=payload)\n\n    def remove(self, section, option) -> None:\n        logger.debug(\"action=remove section=%s option=%s\", section, option)\n\n        section = self.normalize(section)\n        option = self.normalize(option)\n        self.parser.remove_option(section, option)\n        self.save()\n\n        payload = Payload(action=\"remove\", section=section, option=option, value=\"\")\n        self._bus.send(Events.CONFIG_CHANGE, payload=payload)\n\n    @staticmethod\n    def normalize(name: str) -> str:\n        return name.replace(\" \", \"_\").lower()\n\n\ndef remove_duplicates(original: List[str]) -> List[str]:\n    return list(set(original))\n"
  },
  {
    "path": "tomate/pomodoro/event.py",
    "content": "import enum\nimport functools\nimport logging\nfrom typing import Any, Callable, List, Tuple\n\nimport blinker\nfrom wiring import SingletonScope\nfrom wiring.scanning import register\n\nlogger = logging.getLogger(__name__)\n\n\n@enum.unique\nclass Events(enum.Enum):\n    TIMER_START = 0\n    TIMER_UPDATE = 1\n    TIMER_STOP = 2\n    TIMER_END = 3\n\n    SESSION_READY = 4\n    SESSION_START = 5\n    SESSION_INTERRUPT = 6\n    SESSION_CHANGE = 7\n    SESSION_END = 8\n    SESSION_RESET = 9\n\n    WINDOW_SHOW = 10\n    WINDOW_HIDE = 11\n\n    CONFIG_CHANGE = 12\n\n\nReceiver = Callable[[Events, Any], Any]\n\n\n@register.factory(\"tomate.bus\", scope=SingletonScope)\nclass Bus:\n    def __init__(self):\n        self._bus = blinker.NamedSignal(\"tomate\")\n\n    def connect(self, event: Events, receiver: Receiver, weak: bool = True):\n        self._bus.connect(receiver, sender=event, weak=weak)\n\n    def is_connect(self, event: Events, receiver: Receiver) -> bool:\n        return receiver in self._bus.receivers_for(event)\n\n    def send(self, event: Events, payload: Any = None) -> List[Any]:\n        # ignore the receiver in the result\n        return [result[1] for result in self._bus.send(event, payload=payload)]\n\n    def disconnect(self, event: Events, receiver: Receiver):\n        self._bus.disconnect(receiver, sender=event)\n\n\ndef on(*events: Events):\n    def wrapper(method):\n        method._events = events\n\n        @functools.wraps(method)\n        def wrapped(*args, **kwargs):\n            # ignore the event type, Events, in the receiver callback\n            return method(*(arg for arg in args if not isinstance(arg, Events)), **kwargs)\n\n        return wrapped\n\n    return wrapper\n\n\nclass Subscriber:\n    def connect(self, bus: Bus) -> None:\n        for method, events in self.__methods_with_events():\n            for event in events:\n                logger.debug(\n                    \"action=connect event=%s method=%s.%s\",\n                    event,\n                    self.__class__.__name__,\n                    method.__name__,\n                )\n                bus.connect(event, method)\n\n    def disconnect(self, bus: Bus):\n        for method, events in self.__methods_with_events():\n            for event in events:\n                logger.debug(\n                    \"action=disconnect event=%s method=%s.%s\",\n                    event,\n                    self.__class__.__name__,\n                    method.__name__,\n                )\n                bus.disconnect(event, method)\n\n    def __methods_with_events(self) -> List[Tuple[Any, List[Events]]]:\n        return [\n            (getattr(self, attr), getattr(getattr(self, attr), \"_events\"))\n            for attr in dir(self)\n            if hasattr(getattr(self, attr), \"_events\")\n        ]\n"
  },
  {
    "path": "tomate/pomodoro/fsm.py",
    "content": "import logging\n\nimport wrapt\n\nlogger = logging.getLogger(__name__)\n\n\nclass fsm:\n    def __init__(self, target, **kwargs):\n        self.target = target\n        self.source = kwargs.pop(\"source\", \"*\")\n        self.attr = kwargs.pop(\"attr\", \"state\")\n        self.condition = kwargs.pop(\"condition\", None)\n        self.exit_action = kwargs.pop(\"exit\", None)\n\n    def is_valid_transition(self, instance) -> bool:\n        return self.source == \"*\" or getattr(instance, self.attr) in self.source\n\n    def is_valid_condition(self, instance) -> bool:\n        if not self.condition:\n            return True\n\n        return self.condition(instance)\n\n    def change_state(self, instance) -> None:\n        current_target = getattr(instance, self.attr, None)\n\n        logger.debug(\n            \"action=change attribute=%s.%s from=%s to=%s\",\n            instance.__class__.__name__,\n            self.attr,\n            current_target,\n            self.target,\n        )\n\n        if self.target != \"self\" and current_target != self.target:\n            setattr(instance, self.attr, self.target)\n\n    def call_exit_action(self, instance) -> None:\n        if self.exit_action is not None:\n            self.exit_action(instance)\n\n    @wrapt.decorator\n    def __call__(self, wrapped, instance, args, kwargs):\n        # when there is a decorator over the @fsm the instance will be None so we need to get it from the first param\n        if instance is None:\n            instance = args[0]\n\n        logger.debug(\n            \"action=before method=%s.%s\",\n            instance.__class__.__name__,\n            wrapped.__name__,\n        )\n\n        if self.is_valid_transition(instance) and self.is_valid_condition(instance):\n            result = wrapped(*args, **kwargs)\n            self.change_state(instance)\n            self.call_exit_action(instance)\n\n            logger.debug(\n                \"action=after method=%s.%s called=true\",\n                instance.__class__.__name__,\n                wrapped.__name__,\n            )\n\n            return result\n\n        logger.debug(\n            \"action=after method=%s.%s called=false transition=%s\",\n            instance.__class__.__name__,\n            wrapped.__name__,\n            self.is_valid_transition(instance),\n        )\n\n        return False\n"
  },
  {
    "path": "tomate/pomodoro/graph.py",
    "content": "from wiring import Graph\nfrom wiring.scanning import register\n\ngraph = Graph()\nregister.instance(Graph)(graph)\n"
  },
  {
    "path": "tomate/pomodoro/plugin.py",
    "content": "import logging\nimport os\nfrom typing import List, Optional, Union\n\nimport wrapt\nfrom gi.repository import Gtk\nfrom wiring import Graph, SingletonScope, inject\nfrom wiring.scanning import register\nfrom yapsy.ConfigurablePluginManager import ConfigurablePluginManager\nfrom yapsy.IPlugin import IPlugin\nfrom yapsy.PluginInfo import PluginInfo\nfrom yapsy.VersionedPluginManager import VersionedPluginManager\n\nfrom .config import Config\nfrom .event import Bus, Subscriber\n\nlogger = logging.getLogger(__name__)\n\n\nclass Plugin(IPlugin, Subscriber):\n    has_settings = False\n\n    def __init__(self):\n        super().__init__()\n        self.bus = None\n        self.graph = None\n\n    def configure(self, bus: Bus, graph: Graph) -> None:\n        self.bus = bus\n        self.graph = graph\n\n    def activate(self) -> None:\n        super().activate()\n        self.connect(self.bus)\n\n    def deactivate(self) -> None:\n        self.disconnect(self.bus)\n        super().deactivate()\n\n    def settings_window(self, parent) -> Union[Gtk.Dialog, None]:\n        return None\n\n\n@register.factory(\"tomate.plugin\", scope=SingletonScope)\nclass PluginEngine:\n    @inject(bus=\"tomate.bus\", config=\"tomate.config\", graph=Graph)\n    def __init__(self, bus: Bus, config: Config, graph: Graph):\n        self._bus = bus\n        self._graph = graph\n\n        logger.debug(\"action=init paths=%s\", config.plugin_paths())\n        self._plugin_manager = ConfigurablePluginManager(decorated_manager=VersionedPluginManager())\n        self._plugin_manager.setPluginPlaces(config.plugin_paths())\n        self._plugin_manager.setPluginInfoExtension(\"plugin\")\n        self._plugin_manager.setConfigParser(config.parser, config.save)\n\n    def collect(self) -> None:\n        logger.debug(\"action=collect\")\n        self._plugin_manager.locatePlugins()\n        self._plugin_manager.loadPlugins(callback_after=self._configure_plugin)\n\n    def _configure_plugin(self, plugin: PluginInfo) -> None:\n        if plugin.error is None:\n            plugin.plugin_object.configure(self._bus, self._graph)\n\n    def deactivate(self, name: str) -> None:\n        self._plugin_manager.deactivatePluginByName(name)\n\n    def activate(self, name: str) -> None:\n        self._plugin_manager.activatePluginByName(name)\n\n    def all(self) -> List[PluginInfo]:\n        logger.debug(\"action=all\")\n        return sorted(self._plugin_manager.getAllPlugins(), key=lambda info: info.name)\n\n    def lookup(self, name: str, category=\"Default\") -> Optional[PluginInfo]:\n        logger.debug(\"action=lookup name=%s category=%s\", name, category)\n        return self._plugin_manager.getPluginByName(name, category)\n\n    def has_plugins(self) -> bool:\n        has = len(self.all()) > 0\n        logger.debug(\"action=has_plugin has=%s\", has)\n        return has\n\n    def remove(self, plugin: object, category=\"Default\") -> None:\n        self._plugin_manager.removePluginFromCategory(plugin, category)\n\n\n@wrapt.decorator\ndef suppress_errors(wrapped, _, args, kwargs):\n    try:\n        return wrapped(*args, **kwargs)\n    except Exception as ex:\n        if in_debug_mode():\n            raise ex\n\n        log = logging.getLogger(__name__)\n        log.error(ex, exc_info=True)\n\n    return None\n\n\ndef in_debug_mode():\n    return \"TOMATE_DEBUG\" in os.environ.keys()\n"
  },
  {
    "path": "tomate/pomodoro/session.py",
    "content": "from __future__ import annotations\n\nimport enum\nimport logging\nfrom collections import namedtuple\n\nfrom wiring import SingletonScope, inject\nfrom wiring.scanning import register\n\nfrom .config import Config\nfrom .config import Payload as ConfigPayload\nfrom .event import Bus, Events, Subscriber, on\nfrom .fsm import fsm\nfrom .timer import SECONDS_IN_A_MINUTE\nfrom .timer import Payload as TimerPayload\nfrom .timer import Timer, format_seconds\n\nlogger = logging.getLogger(__name__)\n\n\nclass Payload(namedtuple(\"SessionPayload\", [\"type\", \"pomodoros\", \"duration\"])):\n    @property\n    def countdown(self) -> str:\n        return format_seconds(self.duration)\n\n\nclass Type(enum.Enum):\n    POMODORO = 0\n    SHORT_BREAK = 1\n    LONG_BREAK = 2\n\n    @classmethod\n    def of(cls, index: int) -> Type:\n        for number, attr in enumerate(cls):\n            if number == index:\n                return attr\n\n        raise Exception(f\"invalid index: {index}\")\n\n    @property\n    def option(self) -> str:\n        return \"{}_duration\".format(self.name.replace(\"_\", \"\").lower())\n\n\n@enum.unique\nclass State(enum.Enum):\n    INITIAL = 0\n    STOPPED = 1\n    STARTED = 2\n    ENDED = 3\n\n\n@register.factory(\"tomate.session\", scope=SingletonScope)\nclass Session(Subscriber):\n    @inject(\n        bus=\"tomate.bus\",\n        config=\"tomate.config\",\n        timer=\"tomate.timer\",\n    )\n    def __init__(self, bus: Bus, config: Config, timer: Timer):\n        self._config = config\n        self._timer = timer\n        self._bus = bus\n        self.state = State.INITIAL\n        self.current = Type.POMODORO\n        self.pomodoros = 0\n        self.connect(bus)\n\n    @fsm(source=[State.INITIAL], target=State.STOPPED, exit=lambda self: self._trigger(Events.SESSION_READY))\n    def ready(self) -> None:\n        pass\n\n    @fsm(\n        source=[State.STOPPED, State.ENDED], target=State.STARTED, exit=lambda self: self._trigger(Events.SESSION_START)\n    )\n    def start(self) -> bool:\n        logger.debug(\"action=start\")\n        self._timer.start(self.duration)\n        return True\n\n    def is_running(self) -> bool:\n        return self._timer.is_running()\n\n    @fsm(\n        source=[State.STARTED],\n        target=State.STOPPED,\n        condition=is_running,\n        exit=lambda self: self._trigger(Events.SESSION_INTERRUPT),\n    )\n    def stop(self) -> bool:\n        logger.debug(\"action=stop\")\n        self._timer.stop()\n        return True\n\n    @fsm(source=[State.STOPPED, State.ENDED], target=\"self\", exit=lambda self: self._trigger(Events.SESSION_RESET))\n    def reset(self) -> bool:\n        logger.debug(\"action=reset\")\n        self.pomodoros = 0\n        return True\n\n    @on(Events.CONFIG_CHANGE)\n    def _on_config_change(self, payload: ConfigPayload) -> bool:\n        if payload.section != \"timer\":\n            return False\n\n        return self.change(self.current)\n\n    @fsm(source=[State.STOPPED, State.ENDED], target=\"self\", exit=lambda self: self._trigger(Events.SESSION_CHANGE))\n    def change(self, session: Type) -> bool:\n        logger.debug(\"action=change current=%s next=%s\", self.current, session)\n        self.current = session\n        return True\n\n    @property\n    def duration(self) -> int:\n        minutes = self._config.get_int(self._config.DURATION_SECTION, self.current.option)\n        return int(minutes * SECONDS_IN_A_MINUTE)\n\n    def timer_is_up(self) -> bool:\n        return not self._timer.is_running()\n\n    @on(Events.TIMER_END)\n    @fsm(\n        source=[State.STARTED],\n        target=State.ENDED,\n        condition=timer_is_up,\n        exit=lambda self: self._trigger(Events.SESSION_CHANGE),\n    )\n    def _end(self, payload: TimerPayload) -> bool:\n        payload = self._create_payload(duration=payload.duration)\n\n        if self.current == Type.POMODORO:\n            self.pomodoros += 1\n            self.current = self._choose_break()\n        else:\n            self.current = Type.POMODORO\n\n        logger.debug(\"action=end previous=%s current=%s\", payload.type, self.current)\n\n        self.state = State.ENDED\n        self._bus.send(Events.SESSION_END, payload=payload._replace(pomodoros=self.pomodoros))\n\n        return True\n\n    def _choose_break(self):\n        return Type.LONG_BREAK if self._is_long_break() else Type.SHORT_BREAK\n\n    def _is_long_break(self) -> bool:\n        long_break_interval = self._config.get_int(self._config.DURATION_SECTION, \"long_break_interval\")\n        return not self.pomodoros % long_break_interval\n\n    def _trigger(self, event: Events) -> None:\n        self._bus.send(event, payload=self._create_payload())\n\n    def _create_payload(self, **kwargs) -> Payload:\n        defaults = {\n            \"duration\": self.duration,\n            \"pomodoros\": self.pomodoros,\n            \"type\": self.current,\n        }\n        defaults.update(kwargs)\n        return Payload(**defaults)\n"
  },
  {
    "path": "tomate/pomodoro/timer.py",
    "content": "import enum\nimport logging\nfrom collections import namedtuple\n\nfrom gi.repository import GLib\nfrom wiring import SingletonScope, inject\nfrom wiring.scanning import register\n\nfrom .event import Bus, Events\nfrom .fsm import fsm\n\nlogger = logging.getLogger(__name__)\nSECONDS_IN_A_MINUTE = 60\n\n\ndef format_seconds(seconds: int) -> str:\n    minutes, seconds = divmod(seconds, SECONDS_IN_A_MINUTE)\n    return \"{0:0>2}:{1:0>2}\".format(minutes, seconds)\n\n\nclass Payload(namedtuple(\"TimerPayload\", [\"time_left\", \"duration\"])):\n    @property\n    def remaining_ratio(self) -> float:\n        try:\n            return self.time_left / self.duration\n        except ZeroDivisionError:\n            return 0.0\n\n    @property\n    def elapsed_ratio(self) -> float:\n        return round(1.0 - self.remaining_ratio, 2)\n\n    @property\n    def elapsed_percent(self):\n        \"\"\"\n        Returns the percentage in 5% steps\n        \"\"\"\n        percent = self.elapsed_ratio * 100\n        return percent - percent % 5\n\n    @property\n    def countdown(self) -> str:\n        return format_seconds(self.time_left)\n\n\n# Based on Tomatoro create by Pierre Quillery.\n# https://github.com/dandelionmood/Tomatoro\n# Thanks Pierre!\n\n\nclass State(enum.Enum):\n    STOPPED = 1\n    STARTED = 2\n    ENDED = 3\n\n\n@register.factory(\"tomate.timer\", scope=SingletonScope)\nclass Timer:\n    ONE_SECOND = 1\n\n    @inject(bus=\"tomate.bus\")\n    def __init__(self, bus: Bus):\n        self.duration = self.time_left = 0\n        self.state = State.STOPPED\n        self._bus = bus\n\n    @fsm(target=State.STARTED, source=[State.ENDED, State.STOPPED], exit=lambda self: self._trigger(Events.TIMER_START))\n    def start(self, seconds: int) -> bool:\n        logger.debug(\"action=start\")\n        self.duration = self.time_left = seconds\n        GLib.timeout_add_seconds(Timer.ONE_SECOND, self._update, priority=GLib.PRIORITY_HIGH)\n        return True\n\n    @fsm(target=State.STOPPED, source=[State.STARTED], exit=lambda self: self._trigger(Events.TIMER_STOP))\n    def stop(self) -> bool:\n        logger.debug(\"action=reset\")\n        self._reset()\n        return True\n\n    def _is_up(self) -> bool:\n        return self.time_left <= 0\n\n    def is_running(self) -> bool:\n        return self.state == State.STARTED\n\n    @fsm(\n        target=State.ENDED, source=[State.STARTED], condition=_is_up, exit=lambda self: self._trigger(Events.TIMER_END)\n    )\n    def end(self) -> bool:\n        logger.debug(\"action=end\")\n        return True\n\n    def _update(self) -> bool:\n        logger.debug(\"action=update time_left=%d duration=%d\", self.time_left, self.duration)\n\n        if self.state != State.STARTED:\n            return False\n\n        if self._is_up():\n            return self.end()\n\n        self.time_left -= 1\n        self._trigger(Events.TIMER_UPDATE)\n        return True\n\n    def _reset(self) -> None:\n        self.duration = self.time_left = 0\n\n    def _trigger(self, event) -> None:\n        self._bus.send(event, payload=Payload(time_left=self.time_left, duration=self.duration))\n"
  },
  {
    "path": "tomate/ui/__init__.py",
    "content": "from .shortcut import Shortcut, ShortcutEngine\nfrom .systray import Menu as SystrayMenu\nfrom .systray import Systray\nfrom .window import Window\n\n__all__ = [\"Shortcut\", \"ShortcutEngine\", \"Systray\", \"SystrayMenu\", \"Window\"]\n"
  },
  {
    "path": "tomate/ui/dialogs/__init__.py",
    "content": "from .about import AboutDialog\nfrom .preference import ExtensionTab, PluginGrid, PreferenceDialog, TimerTab\n\n__all__ = [\"AboutDialog\", \"ExtensionTab\", \"PreferenceDialog\", \"TimerTab\", \"PluginGrid\"]\n"
  },
  {
    "path": "tomate/ui/dialogs/about.py",
    "content": "from gi.repository import GdkPixbuf, Gtk\nfrom wiring import SingletonScope, inject\nfrom wiring.scanning import register\n\n\n@register.factory(\"tomate.ui.about\", scope=SingletonScope)\nclass AboutDialog(Gtk.AboutDialog):\n    @inject(config=\"tomate.config\")\n    def __init__(self, config):\n        Gtk.AboutDialog.__init__(\n            self,\n            comments=\"Tomate Pomodoro Timer (GTK+ Interface)\",\n            copyright=\"2014, Elio Esteves Duarte\",\n            license=\"GPL-3\",\n            license_type=Gtk.License.GPL_3_0,\n            logo=GdkPixbuf.Pixbuf.new_from_file(config.icon_path(\"tomate\", 48)),\n            modal=True,\n            program_name=\"Tomate Gtk\",\n            title=\"Tomate Gtk\",\n            version=\"0.25.2\",\n            website=\"https://github.com/eliostvs/tomate-gtk\",\n            website_label=\"Tomate GTK on Github\",\n        )\n\n        self.props.authors = [\"Elio Esteves Duarte\"]\n        self.connect(\"response\", lambda widget, _: widget.hide())\n\n    @property\n    def widget(self):\n        return self\n"
  },
  {
    "path": "tomate/ui/dialogs/preference.py",
    "content": "import locale\nimport logging\nfrom locale import gettext as _\n\nfrom gi.repository import GdkPixbuf, Gtk, Pango\nfrom wiring import SingletonScope, inject\nfrom wiring.scanning import register\n\nfrom tomate.pomodoro import Bus, Config, PluginEngine\n\nlocale.textdomain(\"tomate\")\nlogger = logging.getLogger(__name__)\n\n\n@register.factory(\"tomate.ui.preference\", scope=SingletonScope)\nclass PreferenceDialog(Gtk.Dialog):\n    @inject(\n        timer_tab=\"tomate.ui.preference.timer\",\n        extension_tab=\"tomate.ui.preference.extension\",\n    )\n    def __init__(self, timer_tab, extension_tab):\n        stack = Gtk.Stack()\n        stack.add_titled(timer_tab.widget, \"timer\", _(\"Timer\"))\n        stack.add_titled(extension_tab.widget, \"extension\", _(\"Extensions\"))\n\n        switcher = Gtk.StackSwitcher(halign=Gtk.Align.CENTER)\n        switcher.props.stack = stack\n\n        content_area = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12, margin_bottom=12)\n        content_area.pack_start(switcher, False, False, 0)\n        content_area.pack_start(stack, False, False, 0)\n        content_area.show_all()\n\n        super().__init__(\n            title=_(\"Preferences\"),\n            border_width=12,\n            resizable=False,\n            window_position=Gtk.WindowPosition.CENTER_ON_PARENT,\n            flags=Gtk.DialogFlags.MODAL,\n        )\n        self.add_button(_(\"Close\"), Gtk.ResponseType.CLOSE)\n        self.connect(\"response\", lambda widget, response: widget.hide())\n        self.set_size_request(350, -1)\n        self.get_content_area().add(content_area)\n\n        stack.set_visible_child_name(\"timer\")\n\n        self._extension_tab = extension_tab\n        self._extension_tab.set_toplevel(self)\n\n    @property\n    def widget(self):\n        return self\n\n    def run(self):\n        logger.debug(\"action=run\")\n        self._extension_tab.refresh()\n        return super().run()\n\n\n@register.factory(\"tomate.ui.preference.timer\", scope=SingletonScope)\nclass TimerTab:\n    @inject(config=\"tomate.config\")\n    def __init__(self, config: Config):\n        self._config = config\n\n        section = self._create_section(_(\"Duration\"))\n        self.widget = Gtk.Grid(column_spacing=12, row_spacing=6)\n        self.widget.attach(section, 0, 0, 1, 1)\n\n        # Pomodoro Duration\n        label, button = self._create_option(\"duration.pomodoro\", _(\"Pomodoro\"), Config.DURATION_POMODORO)\n        self.widget.attach(label, 0, 1, 1, 1)\n        self.widget.attach_next_to(button, label, Gtk.PositionType.RIGHT, 3, 1)\n        self.pomodoro = button\n\n        # Short Break Duration\n        label, button = self._create_option(\"duration.shortbreak\", _(\"Short break\"), Config.DURATION_SHORT_BREAK)\n        self.widget.attach(label, 0, 2, 1, 1)\n        self.widget.attach_next_to(button, label, Gtk.PositionType.RIGHT, 3, 1)\n        self.shortbreak = button\n\n        # Long Break Duration\n        label, button = self._create_option(\"duration.longbreak\", _(\"Long Break\"), Config.DURATION_LONG_BREAK)\n        self.widget.attach(label, 0, 3, 1, 1)\n        self.widget.attach_next_to(button, label, Gtk.PositionType.RIGHT, 3, 1)\n        self.longbreak = button\n\n    def _create_section(self, name):\n        section = Gtk.Label.new()\n        section.set_markup(\"<b>{0}</b>\".format(name))\n        section.props.halign = Gtk.Align.START\n        return section\n\n    def _create_option(self, name: str, label: str, option: str):\n        label = Gtk.Label.new(label + \":\")\n        label.set_properties(margin_left=12, hexpand=True, halign=Gtk.Align.END)\n\n        button = Gtk.SpinButton.new_with_range(1, 99, 1)\n        button.set_properties(\n            hexpand=True, halign=Gtk.Align.START, name=name, value=self._config.get_int(\"Timer\", option)\n        )\n        button.connect(\"value-changed\", self._on_change, option)\n\n        return label, button\n\n    def _on_change(self, widget, option):\n        value = str(widget.get_value_as_int())\n        self._config.set(\"Timer\", option, value)\n\n\n@register.factory(\"tomate.ui.preference.extension\", scope=SingletonScope)\nclass ExtensionTab:\n    @inject(bus=\"tomate.bus\", config=\"tomate.config\", plugin_engine=\"tomate.plugin\")\n    def __init__(self, bus: Bus, config: Config, plugin_engine: PluginEngine):\n        self._plugins = plugin_engine\n        self._config = config\n        self._bus = bus\n        self.toplevel = None\n\n        self.plugin_model = Gtk.ListStore(*PluginGrid.MODEL)\n\n        self.plugin_list = Gtk.TreeView(headers_visible=False, model=self.plugin_model, name=\"plugin.list\")\n        self.plugin_list.get_selection().connect(\"changed\", self._on_plugin_changed)\n        self.plugin_list.get_selection().set_mode(Gtk.SelectionMode.BROWSE)\n\n        renderer = Gtk.CellRendererToggle()\n        renderer.connect(\"toggled\", self._on_plugin_toggle)\n        column = Gtk.TreeViewColumn(\"Active\", renderer, active=PluginGrid.ACTIVE)\n        self.plugin_list.append_column(column)\n\n        renderer = Gtk.CellRendererPixbuf()\n        column = Gtk.TreeViewColumn(\"Icon\", renderer, pixbuf=PluginGrid.ICON)\n        self.plugin_list.append_column(column)\n\n        renderer = Gtk.CellRendererText(wrap_mode=Pango.WrapMode.WORD, wrap_width=250)\n        column = Gtk.TreeViewColumn(\"Detail\", renderer, markup=PluginGrid.DETAIL)\n        self.plugin_list.append_column(column)\n\n        plugin_list_container = Gtk.ScrolledWindow(shadow_type=Gtk.ShadowType.IN)\n        plugin_list_container.add(self.plugin_list)\n\n        self.settings_button = Gtk.Button.new_from_icon_name(\"preferences-system\", Gtk.IconSize.MENU)\n        self.settings_button.set_properties(name=\"plugin.settings\", sensitive=False)\n        self.settings_button.connect(\"clicked\", self._on_plugin_settings_clicked)\n\n        settings_button_container = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)\n        settings_button_container.pack_end(self.settings_button, False, False, 0)\n\n        self.widget = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)\n        self.widget.pack_start(plugin_list_container, True, True, 0)\n        self.widget.pack_start(settings_button_container, False, False, 0)\n\n        self.widget.show_all()\n\n    def _on_plugin_changed(self, selection):\n        model, selected = selection.get_selected()\n\n        if selected is not None:\n            grid_plugin = PluginGrid.from_iter(model, selected)\n            self.settings_button.props.sensitive = grid_plugin.is_enable & grid_plugin.has_settings\n\n    def _on_plugin_toggle(self, _, path):\n        plugin = PluginGrid.from_path(self.plugin_model, path)\n        plugin.toggle()\n\n        logger.debug(\"action=toggle plugin=%s enable=%s\", plugin.name, plugin.is_enable)\n\n        if plugin.is_enable:\n            self._activate(plugin)\n        else:\n            self._deactivate(plugin)\n\n    def _on_plugin_settings_clicked(self, _):\n        model, selected = self.plugin_list.get_selection().get_selected()\n        grid_plugin = PluginGrid.from_iter(model, selected)\n        logger.debug(\"action=open_plugin_settings plugin=%s\", grid_plugin.name)\n        grid_plugin.open_settings(self.toplevel)\n\n    def _activate(self, plugin):\n        self._plugins.activate(plugin.name)\n        self.settings_button.props.sensitive = plugin.has_settings\n\n    def _deactivate(self, plugin):\n        self._plugins.deactivate(plugin.name)\n        self.settings_button.props.sensitive = False\n\n    def set_toplevel(self, widget: Gtk.Widget) -> None:\n        self.toplevel = widget\n\n    def refresh(self):\n        logger.debug(\"action=refresh_plugins has_plugins=%s\", self._plugins.has_plugins())\n\n        self._clear()\n\n        for plugin in self._plugins.all():\n            self._add(plugin)\n\n        if self._plugins.has_plugins():\n            self._select_first()\n\n    def _add(self, plugin):\n        logger.debug(\"action=add_plugin plugin=%s\", plugin.name)\n        self.plugin_model.append(PluginGrid.create_row(plugin, self._config))\n\n    def _select_first(self):\n        self.plugin_list.get_selection().select_iter(self.plugin_model.get_iter_first())\n\n    def _clear(self):\n        logger.debug(\"action=clear_plugin_list\")\n        self.plugin_model.clear()\n\n\nclass PluginGrid(object):\n    NAME = 0\n    ACTIVE = 1\n    ICON = 2\n    DETAIL = 3\n    INSTANCE = 4\n    MODEL = [\n        str,\n        bool,\n        GdkPixbuf.Pixbuf,\n        str,\n        object,\n    ]  # name active icon detail instance\n\n    def __init__(self, row):\n        self._row = row\n\n    @property\n    def name(self):\n        return self._row[self.NAME]\n\n    @property\n    def is_enable(self):\n        return self._row[self.ACTIVE]\n\n    def toggle(self):\n        self._row[self.ACTIVE] = not self._row[self.ACTIVE]\n\n    @property\n    def instance(self):\n        return self._row[self.INSTANCE]\n\n    @property\n    def has_settings(self):\n        return getattr(self._row[self.INSTANCE], \"has_settings\", False)\n\n    def open_settings(self, toplevel):\n        self.instance.settings_window(toplevel).run()\n\n    @staticmethod\n    def create_row(plugin, config):\n        return [\n            plugin.name,\n            plugin.plugin_object.is_activated,\n            PluginGrid.pixbuf(plugin, config),\n            PluginGrid.description(plugin),\n            plugin.plugin_object,\n        ]\n\n    @staticmethod\n    def pixbuf(plugin, config):\n        icon_name = getattr(plugin, \"icon\", \"tomate-plugin\")\n        icon_path = config.icon_path(icon_name, 16)\n        return GdkPixbuf.Pixbuf.new_from_file(icon_path)\n\n    @staticmethod\n    def description(plugin):\n        return \"<b>{name}</b> ({version})\" \"\\n<small>{description}</small>\".format(\n            name=plugin.name, version=plugin.version, description=plugin.description\n        )\n\n    @classmethod\n    def from_iter(cls, tree_store, tree_iter):\n        return cls(tree_store[tree_iter])\n\n    @classmethod\n    def from_path(cls, tree_store, tree_path):\n        tree_iter = tree_store.get_iter(tree_path)\n        return cls(tree_store[tree_iter])\n"
  },
  {
    "path": "tomate/ui/shortcut.py",
    "content": "import logging\nfrom collections import namedtuple\nfrom typing import Any, Callable, Tuple\n\nfrom gi.repository import Gdk, Gtk\nfrom wiring import SingletonScope, inject\nfrom wiring.scanning import register\n\nlogger = logging.getLogger(__name__)\n\n\nclass Shortcut(namedtuple(\"Shortcut\", [\"name\", \"value\"])):\n    def __str__(self) -> str:\n        return \"name={} value={}\".format(self.name, self.value)\n\n    @property\n    def accel_path(self) -> str:\n        return \"<tomate>/Global/{}\".format(self.name)\n\n\n@register.factory(\"tomate.ui.shortcut\", scope=SingletonScope)\nclass ShortcutEngine:\n    @inject(config=\"tomate.config\")\n    def __init__(self, config, accel_group=Gtk.AccelGroup()):\n        self._config = config\n        self.accel_group = accel_group\n\n    def init(self, window: Gtk.Window) -> None:\n        logger.debug(\"action=init\")\n        window.add_accel_group(self.accel_group)\n\n    def change(self, shortcut: Shortcut) -> None:\n        logger.debug(\"action=change %s\", shortcut)\n        Gtk.AccelMap.change_entry(shortcut.accel_path, *Gtk.accelerator_parse(shortcut.value), True)\n\n    def connect(self, shortcut: Shortcut, callback: Callable[[], Any]) -> None:\n        logger.debug(\"action=connect %s\", shortcut)\n        Gtk.AccelMap.add_entry(shortcut.accel_path, *self._parse(shortcut))\n        self.accel_group.connect_by_path(shortcut.accel_path, callback)\n\n    def disconnect(self, shortcut: Shortcut) -> None:\n        logger.debug(\"action=disconnect %s\")\n        self.accel_group.disconnect_key(*self._parse(shortcut))\n\n    def label(self, shortcut: Shortcut) -> str:\n        return Gtk.accelerator_get_label(*self._parse(shortcut))\n\n    def _parse(self, shortcut: Shortcut) -> Tuple[int, Gdk.ModifierType]:\n        accelerator = self._config.get(self._config.SHORTCUT_SECTION, shortcut.name, fallback=shortcut.value)\n        return Gtk.accelerator_parse(accelerator)\n"
  },
  {
    "path": "tomate/ui/systray.py",
    "content": "from locale import gettext as _\nfrom typing import Callable, Tuple\n\nfrom gi.repository import Gtk\nfrom wiring import SingletonScope, inject\nfrom wiring.scanning import register\n\nfrom tomate.pomodoro import Bus, Events, Subscriber, on\n\n\nclass Systray:\n    def show(*args, **kwargs):\n        pass\n\n    def hide(*args, **kwargs):\n        pass\n\n\n@register.factory(\"tomate.ui.systray.menu\", scope=SingletonScope)\nclass Menu(Subscriber):\n    @inject(bus=\"tomate.bus\", window=\"tomate.ui.view\")\n    def __init__(self, bus: Bus, window):\n        self.connect(bus)\n        self.widget, self.show_item, self.hide_item = self._create_menu(window)\n\n    def _create_menu(self, window) -> Tuple[Gtk.Menu, Gtk.MenuItem, Gtk.MenuItem]:\n        menu = Gtk.Menu(halign=Gtk.Align.CENTER)\n        menu.add(self._create_menu_item(\"Show\", lambda _: window.show(), visible=False, no_show_all=True))\n        menu.add(self._create_menu_item(\"Hide\", lambda _: window.hide(), visible=True))\n        menu.show_all()\n        return menu, *menu.get_children()\n\n    def _create_menu_item(self, label: str, activate: Callable[[], None], **props) -> Gtk.MenuItem:\n        menu_item = Gtk.MenuItem.new_with_label(_(label))\n        menu_item.set_properties(**props)\n        menu_item.connect(\"activate\", activate)\n        return menu_item\n\n    @on(Events.WINDOW_SHOW)\n    def _on_window_show(self, **__):\n        self.hide_item.props.visible = True\n        self.show_item.props.visible = False\n\n    @on(Events.WINDOW_HIDE)\n    def _on_window_hide(self, **__):\n        self.hide_item.props.visible = False\n        self.show_item.props.visible = True\n"
  },
  {
    "path": "tomate/ui/testing.py",
    "content": "import time\nfrom collections import deque\nfrom functools import reduce\nfrom typing import Any, Callable, List, Optional\n\nfrom gi.repository import GLib, Gtk\n\nfrom tomate.pomodoro import SessionPayload, SessionType\nfrom tomate.ui import Shortcut, ShortcutEngine\n\n\ndef active_shortcut(shortcut_engine: ShortcutEngine, shortcut: Shortcut, window: Optional[Gtk.Window] = None) -> bool:\n    if window is None:\n        window = Gtk.Window()\n\n    shortcut_engine.init(window)\n    key, mod = Gtk.accelerator_parse(shortcut.value)\n    return Gtk.accel_groups_activate(window, key, mod)\n\n\ndef create_session_payload(**kwargs) -> SessionPayload:\n    defaults = {\n        \"duration\": 25 * 60,\n        \"pomodoros\": 0,\n        \"type\": SessionType.POMODORO,\n    }\n    defaults.update(kwargs)\n    return SessionPayload(**defaults)\n\n\ndef run_loop_for(seconds: int = 1) -> None:\n    GLib.timeout_add_seconds(seconds, Gtk.main_quit)\n    Gtk.main()\n\n\ndef refresh_gui(delay: int = 0) -> None:\n    while Gtk.events_pending():\n        Gtk.main_iteration_do(False)\n    time.sleep(delay)\n\n\nclass GtkWidgetNotFound(Exception):\n    pass\n\n\nFilter = Callable[[Any], bool]\n\n\nclass Q:\n    @staticmethod\n    def props(name: str, value: Any) -> Filter:\n        def select(w: Gtk.Widget) -> bool:\n            if hasattr(w.props, name):\n                return getattr(w.props, name) == value\n            return False\n\n        return select\n\n    @staticmethod\n    def combine(*fns: Filter) -> Filter:\n        def select(w: Gtk.Widget) -> bool:\n            for fn in fns:\n                if not fn(w):\n                    return False\n                return True\n\n        return select\n\n    @staticmethod\n    def select(root: Gtk.Widget, *fns: Filter) -> Gtk.Widget:\n        fn = Q.combine(*fns)\n        queue = deque([root])\n        while queue:\n            widget = queue.popleft()\n            if fn(widget):\n                return widget\n\n            if hasattr(widget, \"get_children\"):\n                for child in widget.get_children():\n                    queue.append(child)\n\n        raise GtkWidgetNotFound()\n\n    @staticmethod\n    def emit(method: str, *args) -> Callable[[Gtk.Widget], None]:\n        def effect(w: Gtk.Widget) -> None:\n            w.emit(method, *args)\n\n        return effect\n\n    @staticmethod\n    def map(widget: Gtk.Widget, *fns: Callable[[Any], Any]):\n        return reduce(lambda prev, fn: fn(prev), fns, widget)\n\n\nclass TV:\n    @staticmethod\n    def model(tree_view: Gtk.TreeView) -> Gtk.TreeStore:\n        return tree_view.get_model()\n\n    @staticmethod\n    def column(fn: Filter) -> Callable[[Gtk.TreeView], List[Gtk.TreeViewColumn]]:\n        def select(tree_view: Gtk.TreeView) -> List[Gtk.TreeViewColumn]:\n            return [column for column in tree_view.get_columns() if fn(column)][0]\n\n        return select\n\n    @staticmethod\n    def cell_renderer(position: int) -> Callable[[Gtk.TreeViewColumn], Gtk.CellRenderer]:\n        def select(tree_column: Gtk.TreeViewColumn) -> Gtk.CellRenderer:\n            return tree_column.get_cells()[position]\n\n        return select\n"
  },
  {
    "path": "tomate/ui/widgets/__init__.py",
    "content": "from .countdown import Countdown\nfrom .headerbar import HeaderBar\nfrom .headerbar import Menu as HeaderBarMenu\nfrom .mode_button import ModeButton\nfrom .session_button import SessionButton\n\n__all__ = [\n    \"Countdown\",\n    \"HeaderBar\",\n    \"HeaderBarMenu\",\n    \"ModeButton\",\n    \"SessionButton\",\n]\n"
  },
  {
    "path": "tomate/ui/widgets/countdown.py",
    "content": "import logging\nfrom typing import Union\n\nfrom gi.repository import Gtk\nfrom wiring import SingletonScope, inject\nfrom wiring.scanning import register\n\nfrom tomate.pomodoro import Bus, Events, SessionPayload, Subscriber, TimerPayload, on\n\nlogger = logging.getLogger(__name__)\n\n\n@register.factory(\"tomate.ui.countdown\", scope=SingletonScope)\nclass Countdown(Subscriber):\n    @inject(bus=\"tomate.bus\")\n    def __init__(self, bus: Bus):\n        self.widget = Gtk.Label(margin_top=30, margin_bottom=10, margin_right=10, margin_left=10, label=\"00:00\")\n        self.connect(bus)\n\n    @on(Events.TIMER_UPDATE, Events.SESSION_READY, Events.SESSION_INTERRUPT, Events.SESSION_CHANGE)\n    def _update_countdown(self, payload: Union[SessionPayload, TimerPayload]) -> None:\n        logger.debug(\"action=update countdown=%s\", payload.countdown)\n        self.widget.set_markup(self.timer_markup(payload.countdown))\n\n    @staticmethod\n    def timer_markup(time_left: str) -> str:\n        return '<span face=\"sans-serif\" font=\"45\">{}</span>'.format(time_left)\n"
  },
  {
    "path": "tomate/ui/widgets/headerbar.py",
    "content": "import locale\nimport logging\nfrom locale import gettext as _\n\nfrom gi.repository import Gtk\nfrom wiring import SingletonScope, inject\nfrom wiring.scanning import register\n\nfrom tomate.pomodoro import Bus, Events, Session, SessionPayload, Subscriber, on\nfrom tomate.ui import Shortcut, ShortcutEngine\n\nlocale.textdomain(\"tomate\")\nlogger = logging.getLogger(__name__)\n\n\n@register.factory(\"tomate.ui.headerbar.menu\", scope=SingletonScope)\nclass Menu(Subscriber):\n    PREFERENCE_SHORTCUT = Shortcut(\"session.settings\", \"<control>comma\")\n\n    @inject(\n        bus=\"tomate.bus\",\n        about=\"tomate.ui.about\",\n        preference=\"tomate.ui.preference\",\n        shortcuts=\"tomate.ui.shortcut\",\n    )\n    def __init__(self, bus: Bus, about, preference, shortcuts: ShortcutEngine):\n        self.connect(bus)\n\n        self.widget = Gtk.Menu(halign=Gtk.Align.CENTER)\n        self.widget.add(self._create_menu_item(\"header.menu.preference\", _(\"Preferences\"), preference.widget))\n        self.widget.add(self._create_menu_item(\"header.menu.about\", _(\"About\"), about.widget))\n        self.widget.show_all()\n\n        shortcuts.connect(Menu.PREFERENCE_SHORTCUT, lambda *_: preference.widget.run())\n\n    def _create_menu_item(self, name: str, label: str, dialog: Gtk.Dialog) -> Gtk.MenuItem:\n        menu_item = Gtk.MenuItem.new_with_label(label)\n        menu_item.props.name = name\n        menu_item.connect(\"activate\", lambda *_: dialog.run())\n        return menu_item\n\n\n@register.factory(\"tomate.ui.headerbar\", scope=SingletonScope)\nclass HeaderBar(Subscriber):\n    START_SHORTCUT = Shortcut(\"session.start\", \"<control>s\")\n    STOP_SHORTCUT = Shortcut(\"session.stop\", \"<control>p\")\n    RESET_SHORTCUT = Shortcut(\"session.reset\", \"<control>r\")\n\n    @inject(\n        bus=\"tomate.bus\",\n        menu=\"tomate.ui.headerbar.menu\",\n        session=\"tomate.session\",\n        shortcuts=\"tomate.ui.shortcut\",\n    )\n    def __init__(self, bus: Bus, menu: Menu, session: Session, shortcuts: ShortcutEngine):\n        self.connect(bus)\n        self._shortcuts = shortcuts\n        self.widget = self._create_headerbar()\n\n        self._start_button = self._add_button(\n            \"media-playback-start\",\n            \"Starts the session\",\n            HeaderBar.START_SHORTCUT,\n            lambda *_: session.start(),\n        )\n\n        self._stop_button = self._add_button(\n            \"media-playback-stop\",\n            \"Stops the session\",\n            HeaderBar.STOP_SHORTCUT,\n            lambda *_: session.stop(),\n            no_show_all=True,\n            visible=False,\n        )\n\n        self._reset_button = self._add_button(\n            \"edit-clear\",\n            \"Clear session count\",\n            HeaderBar.RESET_SHORTCUT,\n            lambda *_: session.reset(),\n            sensitive=False,\n        )\n\n        self._add_preference_button(menu, shortcuts)\n\n    def _create_headerbar(self):\n        return Gtk.HeaderBar(\n            show_close_button=True,\n            title=_(\"No session yet\"),\n            decoration_layout=\":close\",\n        )\n\n    def _add_button(self, icon: str, tooltip_text: str, shortcut: Shortcut, on_clicked, **props) -> Gtk.Button:\n        image = Gtk.Image.new_from_icon_name(icon, Gtk.IconSize.BUTTON)\n        image.show()\n\n        button = Gtk.Button(\n            tooltip_text=_(\"{} ({})\".format(tooltip_text, self._shortcuts.label(shortcut))), name=shortcut.name, **props\n        )\n        button.add(image)\n        button.connect(\"clicked\", on_clicked)\n\n        self.widget.pack_start(button)\n        self._shortcuts.connect(shortcut, on_clicked)\n\n        return button\n\n    def _add_preference_button(self, menu, shortcuts) -> None:\n        icon = Gtk.Image.new_from_icon_name(\"preferences-system\", Gtk.IconSize.BUTTON)\n        button = Gtk.MenuButton(\n            name=Menu.PREFERENCE_SHORTCUT.name,\n            popup=menu.widget,\n            tooltip_text=_(\"Open preferences ({})\".format(shortcuts.label(Menu.PREFERENCE_SHORTCUT))),\n        )\n        button.add(icon)\n        self.widget.pack_end(button)\n\n    @on(Events.SESSION_START)\n    def _on_session_start(self, **__):\n        logger.debug(\"action=enable_stop\")\n        self._start_button.props.visible = False\n        self._stop_button.props.visible = True\n        self._reset_button.props.sensitive = False\n\n    @on(Events.SESSION_INTERRUPT, Events.SESSION_END)\n    def _on_session_stop(self, payload: SessionPayload) -> None:\n        logger.debug(\"action=enable_start pomodoros=%d\", payload.pomodoros)\n        self._start_button.props.visible = True\n        self._stop_button.props.visible = False\n        self._reset_button.props.sensitive = bool(payload.pomodoros)\n        self._update_title(payload.pomodoros)\n\n    @on(Events.SESSION_RESET)\n    def _on_session_reset(self, **__):\n        logger.debug(\"action=disable_reset\")\n        self._reset_button.props.sensitive = False\n        self._update_title(0)\n\n    def _update_title(self, pomodoros: int) -> None:\n        self.widget.props.title = _(\"Session {}\".format(pomodoros)) if pomodoros else _(\"No session yet\")\n"
  },
  {
    "path": "tomate/ui/widgets/mode_button.py",
    "content": "from typing import Any, Dict\n\nfrom gi.repository import GObject, Gtk\n\n\nclass ModeButtonItem(Gtk.ToggleButton):\n    def __init__(self, index: int, **props: Dict[str, Any]):\n        Gtk.ToggleButton.__init__(self, can_focus=False, **props)\n        self.index = index\n\n\nclass ModeButton(Gtk.Box):\n    __gsignals__ = {\"mode_changed\": (GObject.SignalFlags.RUN_FIRST, None, (int,))}\n\n    def __init__(self, **kwargs):\n        Gtk.Box.__init__(self, **kwargs)\n\n        self.__items = {}\n        self.__selected = None\n\n        style = self.get_style_context()\n        style.add_class(Gtk.STYLE_CLASS_LINKED)\n        style.add_class(\"raised\")\n\n    def get_selected(self):\n        return self.__selected\n\n    def append_text(self, text: str, **props: Dict[str, Any]):\n        button = ModeButtonItem(len(self.__items), **props)\n        button.add(Gtk.Label.new(text))\n        button.connect(\"button_press_event\", self.on_button_press_event)\n        button.show_all()\n\n        self.__items[button.index] = button\n        self.add(button)\n        self.set_selected(button.index)\n\n    def on_button_press_event(self, widget, event=None):\n        return self.set_selected(widget.index)\n\n    def set_selected(self, index):\n        if self.get_sensitive() and index in self.__items.keys():\n            try:\n                old_item = self.__items[self.__selected]\n                old_item.set_active(False)\n            except KeyError:\n                pass\n\n            new_item = self.__items[index]\n            new_item.set_active(True)\n\n            self.__selected = index\n\n            self.emit(\"mode_changed\", self.__selected)\n\n            return True\n"
  },
  {
    "path": "tomate/ui/widgets/session_button.py",
    "content": "import locale\nimport logging\nfrom locale import gettext as _\nfrom typing import Callable\n\nfrom wiring import SingletonScope, inject\nfrom wiring.scanning import register\n\nfrom tomate.pomodoro import (\n    Bus,\n    Events,\n    Session,\n    SessionPayload,\n    SessionType,\n    Subscriber,\n    on,\n)\nfrom tomate.ui import Shortcut, ShortcutEngine\n\nfrom .mode_button import ModeButton\n\nlocale.textdomain(\"tomate\")\nlogger = logging.getLogger(__name__)\n\n\n@register.factory(\"tomate.ui.taskbutton\", scope=SingletonScope)\nclass SessionButton(Subscriber):\n    POMODORO_SHORTCUT = Shortcut(\"session.pomodoro\", \"<control>1\")\n    SHORT_BREAK_SHORTCUT = Shortcut(\"session.short_break\", \"<control>2\")\n    LONG_BREAK_SHORTCUT = Shortcut(\"session.long_break\", \"<control>3\")\n\n    @inject(\n        bus=\"tomate.bus\",\n        session=\"tomate.session\",\n        shortcuts=\"tomate.ui.shortcut\",\n    )\n    def __init__(self, bus: Bus, session: Session, shortcuts: ShortcutEngine):\n        self.connect(bus)\n        self._session = session\n        self._shortcuts = shortcuts\n\n        self.widget = self._create_mode_button()\n        self._add_button(SessionButton.POMODORO_SHORTCUT, \"Pomodoro\", SessionType.POMODORO)\n        self._add_button(SessionButton.SHORT_BREAK_SHORTCUT, \"Short Break\", SessionType.SHORT_BREAK)\n        self._add_button(SessionButton.LONG_BREAK_SHORTCUT, \"Long Break\", SessionType.LONG_BREAK)\n        self.widget.connect(\"mode_changed\", self._clicked)\n\n    def _create_mode_button(self) -> ModeButton:\n        return ModeButton(\n            can_focus=False,\n            homogeneous=True,\n            margin_bottom=12,\n            margin_left=12,\n            margin_right=12,\n            sensitive=True,\n        )\n\n    def _add_button(self, shortcut: Shortcut, label: str, session_type: SessionType) -> None:\n        self.widget.append_text(\n            _(label),\n            tooltip_text=_(\"{} ({})\".format(label, self._shortcuts.label(shortcut))),\n            name=shortcut.name,\n        )\n        self._shortcuts.connect(shortcut, self._select(session_type))\n\n    def _select(self, session_type: SessionType) -> Callable[[], bool]:\n        def callback(*_) -> bool:\n            logger.debug(\"action=change session=%s\", session_type)\n            self.widget.set_selected(session_type.value)\n            return True\n\n        return callback\n\n    def _clicked(self, _, number):\n        session_type = SessionType.of(number)\n        logger.debug(\"action=mode_changed session=%s\", session_type)\n        self._session.change(session_type)\n\n    @on(Events.SESSION_CHANGE)\n    def _change(self, payload=SessionPayload) -> None:\n        logger.debug(\"action=change current=%d next=%d\", self.widget.get_selected(), payload.type.value)\n        if self.widget.get_selected() != payload.type.value:\n            self._enable(payload)\n\n    @on(Events.SESSION_START)\n    def _disable(self, **__):\n        logger.debug(\"action=disable\")\n        self.widget.props.sensitive = False\n\n    @on(Events.SESSION_READY, Events.SESSION_INTERRUPT)\n    def _enable(self, payload: SessionPayload):\n        logger.debug(\"action=enable session=%s\", payload.type)\n        self.widget.props.sensitive = True\n        self.widget.set_selected(payload.type.value)\n"
  },
  {
    "path": "tomate/ui/window.py",
    "content": "import logging\nimport time\n\nfrom gi.repository import GdkPixbuf, Gtk\nfrom wiring import Graph, SingletonScope, inject\nfrom wiring.scanning import register\n\nfrom tomate.pomodoro import Bus, Config, Events, Session, Subscriber, on\n\nfrom .shortcut import ShortcutEngine\nfrom .systray import Systray\nfrom .widgets import Countdown, HeaderBar, SessionButton\n\nlogger = logging.getLogger(__name__)\n\n\n@register.factory(\"tomate.ui.view\", scope=SingletonScope)\nclass Window(Subscriber):\n    @inject(\n        bus=\"tomate.bus\",\n        config=\"tomate.config\",\n        countdown=\"tomate.ui.countdown\",\n        graph=Graph,\n        headerbar=\"tomate.ui.headerbar\",\n        session=\"tomate.session\",\n        session_button=\"tomate.ui.taskbutton\",\n        shortcuts=\"tomate.ui.shortcut\",\n    )\n    def __init__(\n        self,\n        bus: Bus,\n        config: Config,\n        countdown: Countdown,\n        graph: Graph,\n        headerbar: HeaderBar,\n        session: Session,\n        session_button: SessionButton,\n        shortcuts: ShortcutEngine,\n    ):\n        self._session = session\n        self._bus = bus\n        self._graph = graph\n        self.connect(bus)\n\n        content = self._create_content(countdown, session_button)\n        self.widget = self._create_window(config, headerbar, content)\n\n        shortcuts.init(self.widget)\n        session.ready()\n\n    def _create_window(self, config: Config, headerbar: HeaderBar, box: Gtk.Box) -> Gtk.Window:\n        window = Gtk.Window(\n            title=\"Tomate\",\n            icon=GdkPixbuf.Pixbuf.new_from_file(config.icon_path(\"tomate\", 22)),\n            window_position=Gtk.WindowPosition.CENTER,\n            resizable=False,\n        )\n        window.set_size_request(350, -1)\n        window.set_titlebar(headerbar.widget)\n        window.connect(\"delete-event\", self.quit)\n        window.add(box)\n        return window\n\n    def _create_content(self, countdown: Countdown, session_button: SessionButton) -> Gtk.Box:\n        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)\n        box.pack_start(countdown.widget, False, False, 0)\n        box.pack_start(session_button.widget, False, False, 0)\n        return box\n\n    def run(self) -> None:\n        logger.debug(\"action=run\")\n        self.widget.show_all()\n        Gtk.main()\n\n    def quit(self, *_) -> None:\n        if self._session.is_running():\n            return self.hide()\n        else:\n            logger.debug(\"action=quit\")\n            Gtk.main_quit()\n\n    def hide(self):\n        self._bus.send(Events.WINDOW_HIDE)\n\n        if Systray in self._graph.providers:\n            logger.debug(\"action=hide strategy=tray\")\n            return self.widget.hide_on_delete()\n        else:\n            logger.debug(\"action=hide strategy=minimize\")\n            self.widget.iconify()\n            return Gtk.true\n\n    @on(Events.SESSION_END)\n    def show(self, **__) -> None:\n        logger.debug(\"action=show\")\n        self._bus.send(Events.WINDOW_SHOW)\n        self.widget.present_with_time(time.time())\n"
  }
]