├── AUTHORS ├── CHANGELOG.md ├── LICENSE ├── README.md ├── setup.py ├── termdown.gif └── termdown.py /AUTHORS: -------------------------------------------------------------------------------- 1 | Torsten Rehn 2 | Peter Hofmann 3 | Bennett Piater 4 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 1.18.0 2 | ====== 3 | 4 | 2021-11-10 5 | 6 | * added `--end` and E hotkey 7 | * added `--no-figlet-y-offset` 8 | * added support for `espeak-ng` 9 | * changed paused text color to blue 10 | * fixed high CPU usage with `--time` 11 | * fixed delayed countdown after repeatedly pausing and unpausing 12 | 13 | 14 | 1.17.0 15 | ====== 16 | 17 | 2020-04-10 18 | 19 | * removed support for Python 2 20 | * added - hotkey 21 | 22 | 23 | 1.16.0 24 | ====== 25 | 26 | 2019-07-25 27 | 28 | * added + hotkey 29 | * now works on Windows 30 | 31 | 32 | 1.15.0 33 | ====== 34 | 35 | 2019-06-17 36 | 37 | * added `--exec-cmd` 38 | 39 | 40 | 1.14.1 41 | ====== 42 | 43 | 2018-07-20 44 | 45 | * fixed `--no-seconds` not playing nice with `--time` and `--alt-format` 46 | 47 | 48 | 1.14.0 49 | ====== 50 | 51 | 2018-07-15 52 | 53 | * added `--time` and `--time-format` 54 | * added `--no-bell` 55 | 56 | 57 | 1.13.0 58 | ====== 59 | 60 | 2018-03-18 61 | 62 | * added voice announciations at fixed intervals 63 | * added `--voice-prefix` 64 | * per-second voice announciations now start at `--critical` 65 | 66 | 67 | 1.12.2 68 | ====== 69 | 70 | 2018-02-26 71 | 72 | * fixed lap times being recorded incorrectly while paused 73 | 74 | 75 | 1.12.1 76 | ====== 77 | 78 | 2017-09-21 79 | 80 | * fixed espeak output messing up ncurses 81 | * fixed title not being included in non-figlet fallback text 82 | 83 | 84 | 1.12.0 85 | ====== 86 | 87 | 2016-09-30 88 | 89 | * added `--outfile` 90 | * fixed exception in very small terminals 91 | * fixed cursor-related exception in some terminals 92 | 93 | 94 | 1.11.0 95 | ====== 96 | 97 | 2016-06-26 98 | 99 | * added laps 100 | * added support for espeak 101 | * fixed window title not updating in some terminals 102 | 103 | 104 | 1.10.0 105 | ====== 106 | 107 | 2016-03-29 108 | 109 | * show remaining time in window title 110 | * automatically fall back to --no-figlet if terminal is too small 111 | * fixed Figlet rendering not being adjusted to terminal size 112 | 113 | 114 | 1.9.0 115 | ===== 116 | 117 | 2015-10-24 118 | 119 | * now returns exit code 1 on CTRL+C 120 | * fixed drawing area being smaller than it could be 121 | 122 | 123 | 1.8.0 124 | ===== 125 | 126 | 2015-02-15 127 | 128 | * added ``--title`` 129 | * added ``--alt-format`` 130 | * fixed using dates in other timezones 131 | 132 | 133 | 1.7.2 134 | ===== 135 | 136 | 2015-01-15 137 | 138 | * ``--blink`` and ``--text`` can now be combined 139 | * ``termdown --blink 0`` will now blink instead of exiting 140 | 141 | 142 | 1.7.1 143 | ===== 144 | 145 | 2014-11-08 146 | 147 | * stopwatch mode now prints elapsed time to stderr instead of stdout 148 | 149 | 150 | 1.7.0 151 | ===== 152 | 153 | 2014-11-03 154 | 155 | * added --critical 156 | * hotkeys are now case-insensitive 157 | * stopwatch mode will print elapsed time on exit 158 | * draw counter in green while paused 159 | 160 | 161 | 1.6.0 162 | ===== 163 | 164 | 2014-10-21 165 | 166 | * added hotkeys 167 | * added --no-figlet 168 | 169 | 170 | 1.5.0 171 | ===== 172 | 173 | 2014-08-05 174 | 175 | * --no-seconds 176 | * fixed import error in setup.py 177 | 178 | 179 | 1.4.0 180 | ===== 181 | 182 | 2014-07-24 183 | 184 | * deal with non-ASCII characters 185 | 186 | 187 | 1.3.0 188 | ===== 189 | 190 | 2014-06-09 191 | 192 | * stopwatch mode 193 | * fixed formatting of 61 second display 194 | 195 | 196 | 1.2.0 197 | ===== 198 | 199 | 2014-06-08 200 | 201 | * support for Python 3 202 | * --version 203 | 204 | 205 | 1.1 206 | === 207 | 208 | 2014-06-06 209 | 210 | * --quit-after 211 | * --voice 212 | * packaging changes to better suit virtualenv 213 | 214 | 215 | 1.0 216 | === 217 | 218 | 2014-06-02 219 | 220 | * countdowns \o/ 221 | * blinking 222 | * text after countdown 223 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![termdown demo](/termdown.gif?raw=true) 2 | 3 | ``` 4 | Usage: termdown [OPTIONS] [TIME] 5 | 6 | Starts a countdown to TIME. Example values for TIME: 7 | 10, '1h 5m 30s', '12:00', '2020-01-01', '2020-01-01 14:00 UTC'. 8 | 9 | If TIME is not given, termdown will operate in stopwatch mode 10 | and count forward. 11 | 12 | Hotkeys: 13 | E Show end time (countdown mode only) 14 | L Lap (stopwatch mode only) 15 | R Reset 16 | SPACE Pause (will delay absolute TIME) 17 | + Plus (will add 10 seconds) 18 | - Minus (will subtract 10 seconds) 19 | Q Quit 20 | 21 | Options: 22 | -a, --alt-format Use colon-separated time format 23 | -b, --blink Flash terminal at end of countdown 24 | -B, --no-bell Don't ring terminal bell at end of countdown 25 | -c, --critical N Draw final N seconds in red and announce them 26 | individually with --voice or --exec-cmd 27 | (defaults to 3) 28 | 29 | -e, --end Display target datetime of unpaused countdown 30 | -f, --font FONT Choose from 31 | http://www.figlet.org/examples.html 32 | 33 | -p, --voice-prefix TEXT Add TEXT to the beginning of --voice and 34 | --exec annunciations (except per-second ones) 35 | 36 | -q, --quit-after N Quit N seconds after countdown (use with -b or 37 | -t) or terminate stopwatch after N seconds 38 | 39 | -s, --no-seconds Don't show seconds (except for last minute of 40 | countdown and first minute of stopwatch) 41 | 42 | -t, --text TEXT Text to display at end of countdown 43 | -T, --title TEXT Text to display on top of countdown/stopwatch 44 | -W, --no-window-title Don't update terminal title with 45 | remaining/elapsed time 46 | 47 | -v, --voice VOICE Spoken countdown (at fixed intervals with per- 48 | second annunciations starting at --critical; 49 | requires `espeak` on Linux or `say` on macOS; 50 | choose VOICE from `say -v '?'` or `espeak 51 | --voices`) 52 | 53 | -o, --outfile PATH File to write current remaining/elapsed time 54 | to 55 | 56 | --exec-cmd CMD Runs CMD every second. '{0}' and '{1}' in CMD 57 | will be replaced with the remaining/elapsed 58 | number of seconds and a more sparse 59 | annunciation as in --voice, respectively. For 60 | example, to get a callout at five seconds 61 | only, use: --exec-cmd "if [ '{0}' == '5' ]; 62 | then say -v Alex {1}; fi" 63 | 64 | --no-figlet Don't use ASCII art for display 65 | --no-figlet-y-offset INTEGER Vertical offset within the terminal (only for 66 | --no-figlet) 67 | 68 | --no-text-magic Don't try to replace non-ASCII characters (use 69 | with -t) 70 | 71 | --version Show version and exit 72 | -z, --time Show current time instead of 73 | countdown/stopwatch 74 | 75 | -Z, --time-format TEXT Format for --time/--end (defaults to 76 | "%H:%M:%S", ignores --no-seconds) 77 | 78 | -D, --date-format TEXT Format for --end (defaults to "%Y-%m-%d") 79 | --help Show this message and exit. 80 | ``` 81 | 82 | ``` 83 | pip install termdown 84 | ``` 85 | 86 | ------------------------------------------------------------------------ 87 | 88 | ![PyPI version](http://img.shields.io/pypi/v/termdown.svg)   ![Python 3.x](http://img.shields.io/badge/Python-3.x-green.svg)   ![PyPI license](http://img.shields.io/badge/License-GPLv3-red.svg) 89 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | try: 2 | from setuptools import setup 3 | except ImportError: 4 | from distutils.core import setup 5 | 6 | setup( 7 | name="termdown", 8 | version="1.18.0", 9 | description="Countdown timer for your terminal", 10 | author="Torsten Rehn", 11 | author_email="torsten@rehn.email", 12 | license="GPLv3", 13 | url="https://github.com/trehn/termdown", 14 | keywords=[ 15 | "console", 16 | "countdown", 17 | "curses", 18 | "stopwatch", 19 | "terminal", 20 | "timer", 21 | ], 22 | classifiers=[ 23 | "Development Status :: 5 - Production/Stable", 24 | "Environment :: Console :: Curses", 25 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 26 | "Natural Language :: English", 27 | "Operating System :: MacOS :: MacOS X", 28 | "Operating System :: POSIX", 29 | "Operating System :: Unix", 30 | "Programming Language :: Python :: 3", 31 | "Topic :: Utilities", 32 | ], 33 | install_requires=[ 34 | "click >= 2.0", 35 | "pyfiglet >= 0.7", 36 | "python-dateutil", 37 | "windows-curses ; platform_system=='Windows'", 38 | ], 39 | py_modules=['termdown'], 40 | entry_points={ 41 | 'console_scripts': [ 42 | "termdown=termdown:main", 43 | ], 44 | }, 45 | ) 46 | -------------------------------------------------------------------------------- /termdown.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trehn/termdown/66eb1b03be530cc859357071a77bc003f1514f34/termdown.gif -------------------------------------------------------------------------------- /termdown.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | VERSION = "1.18.0" 3 | 4 | import curses 5 | from datetime import datetime, timedelta 6 | from functools import wraps 7 | from math import ceil 8 | from queue import Empty, Queue 9 | import re 10 | import os 11 | from os.path import abspath, dirname 12 | from subprocess import DEVNULL, Popen, STDOUT 13 | from sys import exit, stderr, stdout 14 | from threading import Event, Lock, Thread 15 | from time import sleep 16 | import unicodedata 17 | 18 | import click 19 | from dateutil import tz 20 | from dateutil.parser import parse 21 | from pyfiglet import CharNotPrinted, Figlet 22 | 23 | 24 | DEFAULT_FONT = "univers" 25 | DEFAULT_TIME_FORMAT = "%H:%M:%S" # --no-seconds expects this to end with :%S 26 | DEFAULT_DATE_FORMAT = "%Y-%m-%d" 27 | TIMEDELTA_REGEX = re.compile(r'((?P\d+)y ?)?' 28 | r'((?P\d+)d ?)?' 29 | r'((?P\d+)h ?)?' 30 | r'((?P\d+)m ?)?' 31 | r'((?P\d+)s ?)?') 32 | INPUT_PAUSE = 1 33 | INPUT_RESET = 2 34 | INPUT_EXIT = 3 35 | INPUT_LAP = 4 36 | INPUT_PLUS = 5 37 | INPUT_MINUS = 6 38 | INPUT_END = 7 39 | 40 | 41 | def setup(stdscr): 42 | # curses 43 | curses.use_default_colors() 44 | curses.init_pair(1, curses.COLOR_RED, -1) 45 | curses.init_pair(2, curses.COLOR_RED, curses.COLOR_RED) 46 | curses.init_pair(3, curses.COLOR_BLUE, -1) 47 | curses.init_pair(4, -1, curses.COLOR_RED) 48 | try: 49 | curses.curs_set(False) 50 | except curses.error: 51 | # fails on some terminals 52 | pass 53 | stdscr.timeout(0) 54 | 55 | # prepare input thread mechanisms 56 | curses_lock = Lock() 57 | input_queue = Queue() 58 | quit_event = Event() 59 | return (curses_lock, input_queue, quit_event) 60 | 61 | 62 | def draw_text(stdscr, text, color=0, fallback=None, title=None, no_figlet_y_offset=-1, end=None): 63 | """ 64 | Draws text in the given color. Duh. 65 | """ 66 | if fallback is None: 67 | fallback = text 68 | y, x = stdscr.getmaxyx() 69 | effective_y = (y if no_figlet_y_offset < 0 else 1) 70 | y_delta = (0 if no_figlet_y_offset < 0 else no_figlet_y_offset) 71 | if title: 72 | title = pad_to_size(title, x, 1) 73 | if "\n" in title.rstrip("\n"): 74 | # hack to get more spacing between title and body for figlet 75 | title += "\n" * 5 76 | text = title + "\n" + pad_to_size(text, x, len(text.split("\n"))) 77 | if end: 78 | end = pad_to_size(end, x, 1) 79 | text = pad_to_size(text, x, len(text.split("\n"))) + "\n" + end 80 | lines = pad_to_size(text, x, effective_y).rstrip("\n").split("\n") 81 | 82 | try: 83 | for i, line in enumerate(lines): 84 | stdscr.insstr(i + y_delta, 0, line, curses.color_pair(color)) 85 | except: 86 | lines = pad_to_size(fallback, x, effective_y).rstrip("\n").split("\n") 87 | try: 88 | for i, line in enumerate(lines[:]): 89 | stdscr.insstr(i + y_delta, 0, line, curses.color_pair(color)) 90 | except: 91 | pass 92 | stdscr.refresh() 93 | 94 | 95 | def format_seconds(seconds, hide_seconds=False): 96 | """ 97 | Returns a human-readable string representation of the given amount 98 | of seconds. 99 | """ 100 | if seconds <= 60: 101 | return str(seconds) 102 | output = "" 103 | for period, period_seconds in ( 104 | ('y', 31557600), 105 | ('d', 86400), 106 | ('h', 3600), 107 | ('m', 60), 108 | ('s', 1), 109 | ): 110 | if seconds >= period_seconds and not (hide_seconds and period == 's'): 111 | output += str(int(seconds / period_seconds)) 112 | output += period 113 | output += " " 114 | seconds = seconds % period_seconds 115 | return output.strip() 116 | 117 | 118 | def format_seconds_alt(seconds, start, hide_seconds=False): 119 | # make sure we always show at least 00:00:00 120 | start = max(start, 86400) 121 | output = "" 122 | total_seconds = seconds 123 | for period_seconds in ( 124 | 31557600, 125 | 86400, 126 | 3600, 127 | 60, 128 | 1, 129 | ): 130 | if hide_seconds and period_seconds == 1 and total_seconds > 60: 131 | break 132 | actual_period_value = int(seconds / period_seconds) 133 | if actual_period_value > 0: 134 | output += str(actual_period_value).zfill(2) + ":" 135 | elif start > period_seconds or total_seconds > period_seconds: 136 | output += "00:" 137 | seconds = seconds % period_seconds 138 | return output.rstrip(":") 139 | 140 | 141 | def format_target(target, time_format, date_format): 142 | """ 143 | Returns a human-readable string representation of the countdown's target 144 | datetime 145 | """ 146 | if datetime.now().date() != target.date(): 147 | fmt = "{} {}".format(date_format, time_format) 148 | else: 149 | fmt = time_format 150 | return target.strftime(fmt) 151 | 152 | 153 | def graceful_ctrlc(func): 154 | """ 155 | Makes the decorated function exit with code 1 on CTRL+C. 156 | """ 157 | @wraps(func) 158 | def wrapper(*args, **kwargs): 159 | try: 160 | return func(*args, **kwargs) 161 | except KeyboardInterrupt: 162 | exit(1) 163 | return wrapper 164 | 165 | 166 | NORMALIZE_TEXT_MAP = { 167 | "ä": "ae", 168 | "Ä": "Ae", 169 | "ö": "oe", 170 | "Ö": "Oe", 171 | "ü": "ue", 172 | "Ü": "Ue", 173 | "ß": "ss", 174 | } 175 | 176 | 177 | def normalize_text(input_str): 178 | for char, replacement in NORMALIZE_TEXT_MAP.items(): 179 | input_str = input_str.replace(char, replacement) 180 | return "".join( 181 | [c for c in unicodedata.normalize('NFD', input_str) if 182 | unicodedata.category(c) != 'Mn'] 183 | ) 184 | 185 | 186 | def pad_to_size(text, x, y): 187 | """ 188 | Adds whitespace to text to center it within a frame of the given 189 | dimensions. 190 | """ 191 | input_lines = text.rstrip().split("\n") 192 | longest_input_line = max(map(len, input_lines)) 193 | number_of_input_lines = len(input_lines) 194 | x = max(x, longest_input_line) 195 | y = max(y, number_of_input_lines) 196 | output = "" 197 | 198 | padding_top = int((y - number_of_input_lines) / 2) 199 | padding_bottom = y - number_of_input_lines - padding_top 200 | padding_left = int((x - longest_input_line) / 2) 201 | 202 | output += padding_top * (" " * x + "\n") 203 | for line in input_lines: 204 | output += padding_left * " " + line + " " * (x - padding_left - len(line)) + "\n" 205 | output += padding_bottom * (" " * x + "\n") 206 | 207 | return output 208 | 209 | 210 | def parse_timestr(timestr): 211 | """ 212 | Parse a string describing a point in time. 213 | """ 214 | timedelta_secs = parse_timedelta(timestr) 215 | sync_start = datetime.now() 216 | 217 | if timedelta_secs: 218 | target = datetime.now() + timedelta(seconds=timedelta_secs) 219 | elif timestr.isdigit(): 220 | target = datetime.now() + timedelta(seconds=int(timestr)) 221 | else: 222 | try: 223 | target = parse(timestr) 224 | except: 225 | # unfortunately, dateutil doesn't raise the best exceptions 226 | raise ValueError("Unable to parse '{}'".format(timestr)) 227 | 228 | # When I do "termdown 10" (the two cases above), I want a 229 | # countdown for the next 10 seconds. Okay. But when I do 230 | # "termdown 23:52", I want a countdown that ends at that exact 231 | # moment -- the countdown is related to real time. Thus, I want 232 | # my frames to be drawn at full seconds, so I enforce 233 | # microsecond=0. 234 | sync_start = sync_start.replace(microsecond=0) 235 | try: 236 | # try to convert target to naive local timezone 237 | target = target.astimezone(tz=tz.tzlocal()).replace(tzinfo=None) 238 | except ValueError: 239 | # parse() already returned a naive datetime, all is well 240 | pass 241 | return (sync_start, target) 242 | 243 | 244 | def parse_timedelta(deltastr): 245 | """ 246 | Parse a string describing a period of time. 247 | """ 248 | matches = TIMEDELTA_REGEX.match(deltastr) 249 | if not matches: 250 | return None 251 | components = {} 252 | for name, value in matches.groupdict().items(): 253 | if value: 254 | components[name] = int(value) 255 | for period, hours in (('days', 24), ('years', 8766)): 256 | if period in components: 257 | components['hours'] = components.get('hours', 0) + \ 258 | components[period] * hours 259 | del components[period] 260 | return int(timedelta(**components).total_seconds()) 261 | 262 | 263 | def print_version(ctx, param, value): 264 | if not value or ctx.resilient_parsing: 265 | return 266 | click.echo(VERSION) 267 | ctx.exit() 268 | 269 | 270 | def verify_outfile(ctx, param, value): 271 | if value: 272 | if os.path.exists(value): 273 | raise click.BadParameter("File already exists: {}".format(value)) 274 | if not os.access(dirname(abspath(value)), os.W_OK): 275 | raise click.BadParameter("Unable to write file: {}".format(value)) 276 | return value 277 | 278 | 279 | @graceful_ctrlc 280 | def countdown( 281 | stdscr, 282 | alt_format=False, 283 | font=DEFAULT_FONT, 284 | blink=False, 285 | critical=3, 286 | quit_after=None, 287 | text=None, 288 | timespec=None, 289 | title=None, 290 | end=None, 291 | voice=None, 292 | voice_prefix=None, 293 | exec_cmd=None, 294 | outfile=None, 295 | no_bell=False, 296 | no_seconds=False, 297 | no_text_magic=True, 298 | no_figlet=False, 299 | no_figlet_y_offset=-1, 300 | no_window_title=False, 301 | time=False, 302 | time_format=None, 303 | date_format=None, 304 | **kwargs 305 | ): 306 | try: 307 | sync_start, target = parse_timestr(timespec) 308 | except ValueError: 309 | raise click.BadParameter("Unable to parse TIME value '{}'".format(timespec)) 310 | if exec_cmd and voice: # prevent passing both --exec-cmd and --voice 311 | raise click.BadParameter("--exec-cmd and --voice are mutually exclusive") 312 | curses_lock, input_queue, quit_event = setup(stdscr) 313 | figlet = Figlet(font=font) 314 | if not no_figlet: 315 | no_figlet_y_offset = -1 316 | 317 | voice_cmd = None 318 | if voice: 319 | for cmd in ("/usr/bin/say", "/usr/bin/espeak", "/usr/bin/espeak-ng"): 320 | if os.path.exists(cmd): 321 | voice_cmd = cmd 322 | break 323 | if voice or exec_cmd: 324 | voice_prefix = voice_prefix or "" 325 | 326 | input_thread = Thread( 327 | args=(stdscr, input_queue, quit_event, curses_lock), 328 | target=input_thread_body, 329 | ) 330 | input_thread.start() 331 | 332 | seconds_total = seconds_left = int(ceil((target - datetime.now()).total_seconds())) 333 | 334 | try: 335 | while seconds_left > 0 or blink or text: 336 | figlet.width = stdscr.getmaxyx()[1] 337 | if time: 338 | countdown_text = datetime.now().strftime(time_format) 339 | elif alt_format: 340 | countdown_text = format_seconds_alt( 341 | seconds_left, seconds_total, hide_seconds=no_seconds) 342 | else: 343 | countdown_text = format_seconds(seconds_left, hide_seconds=no_seconds) 344 | if seconds_left > 0: 345 | with curses_lock: 346 | if not no_window_title: 347 | os.write(stdout.fileno(), "\033]2;{0}\007".format(countdown_text).encode()) 348 | if outfile: 349 | with open(outfile, 'w') as f: 350 | f.write("{}\n{}\n".format(countdown_text, seconds_left)) 351 | stdscr.erase() 352 | end_text = format_target( 353 | target, 354 | time_format=time_format, 355 | date_format=date_format, 356 | ) if end else None 357 | fallback = countdown_text 358 | if title: 359 | fallback = title + "\n" + fallback 360 | if end: 361 | fallback = fallback + "\n" + end_text 362 | try: 363 | draw_text( 364 | stdscr, 365 | countdown_text if no_figlet else figlet.renderText(countdown_text), 366 | color=1 if seconds_left <= critical else 0, 367 | fallback=fallback, 368 | title=title if no_figlet or not title else figlet.renderText(title), 369 | end=end_text, 370 | no_figlet_y_offset=no_figlet_y_offset, 371 | ) 372 | except CharNotPrinted: 373 | draw_text(stdscr, "E") 374 | annunciation = None 375 | if seconds_left <= critical: 376 | annunciation = str(seconds_left) 377 | elif seconds_left in (5, 10, 20, 30, 60): 378 | annunciation = "{} {} seconds".format(voice_prefix, seconds_left) 379 | elif seconds_left in (300, 600, 1800): 380 | annunciation = "{} {} minutes".format(voice_prefix, int(seconds_left / 60)) 381 | elif seconds_left == 3600: 382 | annunciation = "{} one hour".format(voice_prefix) 383 | if annunciation or exec_cmd: 384 | if exec_cmd: 385 | Popen( 386 | exec_cmd.format(seconds_left, annunciation or ""), 387 | stdout=DEVNULL, 388 | stderr=STDOUT, 389 | shell=True, 390 | ) 391 | 392 | if voice_cmd: 393 | Popen( 394 | [voice_cmd, "-v", voice, annunciation.strip()], 395 | stdout=DEVNULL, 396 | stderr=STDOUT, 397 | ) 398 | 399 | # We want to sleep until this point of time has been 400 | # reached: 401 | sleep_target = sync_start + timedelta(seconds=1) 402 | if time: 403 | sleep_target = sleep_target.replace(microsecond=0) 404 | 405 | # If sync_start has microsecond=0, it might happen that we 406 | # need to skip one frame (the very first one). This occurs 407 | # when the program has been startet at, say, 408 | # "2014-05-29 20:27:57.930651". Now suppose rendering the 409 | # frame took about 0.2 seconds. The real time now is 410 | # "2014-05-29 20:27:58.130000" and sleep_target is 411 | # "2014-05-29 20:27:58.000000" which is in the past! We're 412 | # already too late. We could either skip that frame 413 | # completely or we can draw it right now. I chose to do the 414 | # latter: Only sleep if haven't already missed our target. 415 | now = datetime.now() 416 | if sleep_target > now and seconds_left > 0: 417 | try: 418 | input_action = input_queue.get(True, (sleep_target - now).total_seconds()) 419 | except Empty: 420 | input_action = None 421 | if input_action == INPUT_PAUSE: 422 | pause_start = datetime.now() 423 | with curses_lock: 424 | stdscr.erase() 425 | try: 426 | draw_text( 427 | stdscr, 428 | countdown_text if no_figlet else figlet.renderText(countdown_text), 429 | color=3, 430 | fallback=countdown_text, 431 | title=title if no_figlet or not title else figlet.renderText(title), 432 | no_figlet_y_offset=no_figlet_y_offset, 433 | ) 434 | except CharNotPrinted: 435 | draw_text(stdscr, "E") 436 | input_action = input_queue.get() 437 | time_paused = datetime.now() - pause_start 438 | sync_start += time_paused 439 | target += time_paused 440 | if input_action == INPUT_EXIT: # no elif here! input_action may have changed 441 | break 442 | elif input_action == INPUT_PAUSE: 443 | continue 444 | elif input_action == INPUT_RESET: 445 | sync_start, target = parse_timestr(timespec) 446 | seconds_left = int(ceil((target - datetime.now()).total_seconds())) 447 | continue 448 | elif input_action == INPUT_PLUS: 449 | target += timedelta(seconds=10) 450 | elif input_action == INPUT_MINUS: 451 | target -= timedelta(seconds=10) 452 | elif input_action == INPUT_LAP: 453 | continue 454 | elif input_action == INPUT_END: 455 | end = not end 456 | continue 457 | sync_start = sleep_target 458 | 459 | seconds_left = int(ceil((target - datetime.now()).total_seconds())) 460 | 461 | if seconds_left <= 0: 462 | # we could write this entire block outside the parent while 463 | # but that would leave us unable to reset everything 464 | 465 | if not no_bell: 466 | with curses_lock: 467 | curses.beep() 468 | 469 | if text and not no_text_magic: 470 | text = normalize_text(text) 471 | 472 | if outfile: 473 | with open(outfile, 'w') as f: 474 | f.write("{}\n{}\n".format(text if text else "DONE", 0)) 475 | 476 | rendered_text = text 477 | 478 | if text and not no_figlet: 479 | try: 480 | rendered_text = figlet.renderText(text) 481 | except CharNotPrinted: 482 | rendered_text = "" 483 | 484 | if blink or text: 485 | base_color = 1 if blink else 0 486 | blink_reset = False 487 | flip = True 488 | slept = 0 489 | extra_sleep = 0 490 | while True: 491 | with curses_lock: 492 | os.write(stdout.fileno(), "\033]2;{0}\007".format("/" if flip else "\\").encode()) 493 | if text: 494 | draw_text( 495 | stdscr, 496 | rendered_text, 497 | color=base_color if flip else 4, 498 | fallback=text, 499 | no_figlet_y_offset=no_figlet_y_offset, 500 | ) 501 | else: 502 | draw_text(stdscr, "", color=base_color if flip else 4) 503 | if blink: 504 | flip = not flip 505 | try: 506 | sleep_start = datetime.now() 507 | input_action = input_queue.get(True, 0.5 + extra_sleep) 508 | except Empty: 509 | input_action = None 510 | finally: 511 | extra_sleep = 0 512 | sleep_end = datetime.now() 513 | if input_action == INPUT_PAUSE: 514 | pause_start = datetime.now() 515 | input_action = input_queue.get() 516 | extra_sleep = (sleep_end - sleep_start).total_seconds() 517 | if input_action == INPUT_EXIT: 518 | # no elif here! input_action may have changed 519 | return 520 | elif input_action == INPUT_RESET: 521 | sync_start, target = parse_timestr(timespec) 522 | seconds_left = int(ceil((target - datetime.now()).total_seconds())) 523 | blink_reset = True 524 | break 525 | slept += (sleep_end - sleep_start).total_seconds() 526 | if quit_after and slept >= float(quit_after): 527 | return 528 | if blink_reset: 529 | continue 530 | finally: 531 | with curses_lock: 532 | if not no_window_title: 533 | os.write(stdout.fileno(), "\033]2;\007".encode()) 534 | if outfile: 535 | os.remove(outfile) 536 | quit_event.set() 537 | input_thread.join() 538 | 539 | 540 | @graceful_ctrlc 541 | def stopwatch( 542 | stdscr, 543 | alt_format=False, 544 | critical=3, 545 | exec_cmd=None, 546 | font=DEFAULT_FONT, 547 | no_figlet=False, 548 | no_figlet_y_offset=-1, 549 | no_seconds=False, 550 | quit_after=None, 551 | title=None, 552 | outfile=None, 553 | no_window_title=False, 554 | time=False, 555 | time_format=None, 556 | voice_prefix=None, 557 | **kwargs 558 | ): 559 | curses_lock, input_queue, quit_event = setup(stdscr) 560 | figlet = Figlet(font=font) 561 | 562 | if not no_figlet: 563 | no_figlet_y_offset = -1 564 | if title and not no_figlet: 565 | try: 566 | title = figlet.renderText(title) 567 | except CharNotPrinted: 568 | title = "" 569 | 570 | input_thread = Thread( 571 | args=(stdscr, input_queue, quit_event, curses_lock), 572 | target=input_thread_body, 573 | ) 574 | input_thread.start() 575 | 576 | try: 577 | sync_start = datetime.now() 578 | pause_start = None 579 | seconds_elapsed = 0 580 | laps = [] 581 | while quit_after is None or seconds_elapsed < int(quit_after): 582 | figlet.width = stdscr.getmaxyx()[1] 583 | if time: 584 | stopwatch_text = datetime.now().strftime(time_format) 585 | elif alt_format: 586 | stopwatch_text = format_seconds_alt(seconds_elapsed, 0, hide_seconds=no_seconds) 587 | else: 588 | stopwatch_text = format_seconds(seconds_elapsed, hide_seconds=no_seconds) 589 | with curses_lock: 590 | if not no_window_title: 591 | os.write(stdout.fileno(), "\033]2;{0}\007".format(stopwatch_text).encode()) 592 | if outfile: 593 | with open(outfile, 'w') as f: 594 | f.write("{}\n{}\n".format(stopwatch_text, seconds_elapsed)) 595 | stdscr.erase() 596 | try: 597 | draw_text( 598 | stdscr, 599 | stopwatch_text if no_figlet else figlet.renderText(stopwatch_text), 600 | fallback=stopwatch_text, 601 | title=title, 602 | no_figlet_y_offset=no_figlet_y_offset, 603 | ) 604 | except CharNotPrinted: 605 | draw_text(stdscr, "E") 606 | if exec_cmd: 607 | voice_prefix = voice_prefix or "" 608 | annunciation = "" 609 | if seconds_elapsed <= critical and seconds_elapsed > 0: 610 | annunciation = str(seconds_elapsed) 611 | elif seconds_elapsed in (5, 10, 20, 30, 40, 50, 60): 612 | annunciation = "{} {} seconds".format(voice_prefix, seconds_elapsed) 613 | elif seconds_elapsed in (120, 180, 300, 600, 1800): 614 | annunciation = "{} {} minutes".format(voice_prefix, int(seconds_elapsed / 60)) 615 | elif seconds_elapsed == 3600: 616 | annunciation = "{} one hour".format(voice_prefix) 617 | elif seconds_elapsed % 3600 == 0 and seconds_elapsed > 0: 618 | annunciation = "{} {} hours".format(voice_prefix, int(seconds_elapsed / 3600)) 619 | Popen( 620 | exec_cmd.format(seconds_elapsed, annunciation), 621 | stdout=DEVNULL, 622 | stderr=STDOUT, 623 | shell=True, 624 | ) 625 | sleep_target = sync_start + timedelta(seconds=seconds_elapsed + 1) 626 | if time: 627 | sleep_target = sleep_target.replace(microsecond=0) 628 | now = datetime.now() 629 | if sleep_target > now: 630 | try: 631 | input_action = input_queue.get(True, (sleep_target - now).total_seconds()) 632 | except Empty: 633 | input_action = None 634 | if input_action == INPUT_PAUSE: 635 | pause_start = datetime.now() 636 | with curses_lock: 637 | if not no_window_title: 638 | os.write(stdout.fileno(), "\033]2;{0}\007".format(stopwatch_text).encode()) 639 | if outfile: 640 | with open(outfile, 'w') as f: 641 | f.write("{}\n{}\n".format(stopwatch_text, seconds_elapsed)) 642 | stdscr.erase() 643 | try: 644 | draw_text( 645 | stdscr, 646 | stopwatch_text if no_figlet else figlet.renderText(stopwatch_text), 647 | color=3, 648 | fallback=stopwatch_text, 649 | title=title, 650 | no_figlet_y_offset=no_figlet_y_offset, 651 | ) 652 | except CharNotPrinted: 653 | draw_text(stdscr, "E") 654 | input_action = input_queue.get() 655 | if input_action == INPUT_PAUSE: 656 | sync_start += (datetime.now() - pause_start) 657 | pause_start = None 658 | if input_action == INPUT_EXIT: # no elif here! input_action may have changed 659 | if pause_start: 660 | sync_start += (datetime.now() - pause_start) 661 | pause_start = None 662 | break 663 | elif input_action == INPUT_RESET: 664 | sync_start = datetime.now() 665 | laps = [] 666 | seconds_elapsed = 0 667 | elif input_action == INPUT_PLUS: 668 | sync_start -= timedelta(seconds=10) 669 | elif input_action == INPUT_MINUS: 670 | sync_start += timedelta(seconds=10) 671 | elif input_action == INPUT_LAP: 672 | if pause_start: 673 | sync_start += (datetime.now() - pause_start) 674 | pause_start = None 675 | laps.append((datetime.now() - sync_start).total_seconds()) 676 | sync_start = datetime.now() 677 | seconds_elapsed = 0 678 | if time: 679 | seconds_elapsed = ceil((datetime.now() - sync_start).total_seconds()) 680 | else: 681 | seconds_elapsed = int((datetime.now() - sync_start).total_seconds()) 682 | finally: 683 | with curses_lock: 684 | if not no_window_title: 685 | os.write(stdout.fileno(), "\033]2;\007".encode()) 686 | if outfile: 687 | os.remove(outfile) 688 | quit_event.set() 689 | input_thread.join() 690 | return (datetime.now() - sync_start).total_seconds(), laps 691 | 692 | 693 | def input_thread_body(stdscr, input_queue, quit_event, curses_lock): 694 | while not quit_event.is_set(): 695 | try: 696 | with curses_lock: 697 | key = stdscr.getkey() 698 | except: 699 | key = None 700 | if key in ("q", "Q"): 701 | input_queue.put(INPUT_EXIT) 702 | elif key == " ": 703 | input_queue.put(INPUT_PAUSE) 704 | elif key in ("e", "E"): 705 | input_queue.put(INPUT_END) 706 | elif key in ("r", "R"): 707 | input_queue.put(INPUT_RESET) 708 | elif key in ("l", "L"): 709 | input_queue.put(INPUT_LAP) 710 | elif key == "+": 711 | input_queue.put(INPUT_PLUS) 712 | elif key == "-": 713 | input_queue.put(INPUT_MINUS) 714 | sleep(0.01) 715 | 716 | 717 | @click.command() 718 | @click.option("-a", "--alt-format", default=False, is_flag=True, 719 | help="Use colon-separated time format") 720 | @click.option("-b", "--blink", default=False, is_flag=True, 721 | help="Flash terminal at end of countdown") 722 | @click.option("-B", "--no-bell", default=False, is_flag=True, 723 | help="Don't ring terminal bell at end of countdown") 724 | @click.option("-c", "--critical", default=3, metavar="N", 725 | help="Draw final N seconds in red and announce them individually with --voice " 726 | "or --exec-cmd (defaults to 3)") 727 | @click.option("-e", "--end", default=False, is_flag=True, 728 | help="Display target datetime of unpaused countdown") 729 | @click.option("-f", "--font", default=DEFAULT_FONT, metavar="FONT", 730 | help="Choose from http://www.figlet.org/examples.html") 731 | @click.option("-p", "--voice-prefix", metavar="TEXT", 732 | help="Add TEXT to the beginning of --voice and --exec annunciations " 733 | "(except per-second ones)") 734 | @click.option("-q", "--quit-after", metavar="N", 735 | help="Quit N seconds after countdown (use with -b or -t) " 736 | "or terminate stopwatch after N seconds") 737 | @click.option("-s", "--no-seconds", default=False, is_flag=True, 738 | help="Don't show seconds (except for last minute of countdown " 739 | "and first minute of stopwatch)") 740 | @click.option("-t", "--text", 741 | help="Text to display at end of countdown") 742 | @click.option("-T", "--title", 743 | help="Text to display on top of countdown/stopwatch") 744 | @click.option("-W", "--no-window-title", default=False, is_flag=True, 745 | help="Don't update terminal title with remaining/elapsed time") 746 | @click.option("-v", "--voice", metavar="VOICE", 747 | help="Spoken countdown " 748 | "(at fixed intervals with per-second annunciations starting at --critical; " 749 | "requires `espeak` on Linux or `say` on macOS; " 750 | "choose VOICE from `say -v '?'` or `espeak --voices`)") 751 | @click.option("-o", "--outfile", metavar="PATH", callback=verify_outfile, 752 | help="File to write current remaining/elapsed time to") 753 | @click.option("--exec-cmd", metavar="CMD", 754 | help="Runs CMD every second. '{0}' and '{1}' in CMD will be replaced with the " 755 | "remaining/elapsed number of seconds and a more sparse annunciation as in " 756 | "--voice, respectively. For example, to get a callout at five seconds only, " 757 | "use: --exec-cmd \"if [ '{0}' == '5' ]; then say -v Alex {1}; fi\"") 758 | @click.option("--no-figlet", default=False, is_flag=True, 759 | help="Don't use ASCII art for display") 760 | @click.option("--no-figlet-y-offset", default=-1, 761 | help="Vertical offset within the terminal (only for --no-figlet)") 762 | @click.option("--no-text-magic", default=False, is_flag=True, 763 | help="Don't try to replace non-ASCII characters (use with -t)") 764 | @click.option("--version", is_flag=True, callback=print_version, 765 | expose_value=False, is_eager=True, 766 | help="Show version and exit") 767 | @click.option("-z", "--time", default=False, is_flag=True, 768 | help="Show current time instead of countdown/stopwatch") 769 | @click.option("-Z", "--time-format", default=None, 770 | help="Format for --time/--end (defaults to \"{}\", " 771 | "ignores --no-seconds)".format(DEFAULT_TIME_FORMAT)) 772 | @click.option("-D", "--date-format", default=None, 773 | help="Format for --end (defaults to \"{}\")".format(DEFAULT_DATE_FORMAT)) 774 | @click.argument('timespec', metavar="[TIME]", required=False) 775 | def main(**kwargs): 776 | """ 777 | \b 778 | Starts a countdown to TIME. Example values for TIME: 779 | 10, '1h 5m 30s', '12:00', '2020-01-01', '2020-01-01 14:00 UTC'. 780 | \b 781 | If TIME is not given, termdown will operate in stopwatch mode 782 | and count forward. 783 | \b 784 | Hotkeys: 785 | \tE\tShow end time (countdown mode only) 786 | \tL\tLap (stopwatch mode only) 787 | \tR\tReset 788 | \tSPACE\tPause (will delay absolute TIME) 789 | \t+\tPlus (will add 10 seconds) 790 | \t-\tMinus (will subtract 10 seconds) 791 | \tQ\tQuit 792 | """ 793 | if kwargs['time_format'] is None: 794 | kwargs['time_format'] = \ 795 | DEFAULT_TIME_FORMAT[:-3] if kwargs['no_seconds'] else DEFAULT_TIME_FORMAT 796 | if kwargs['date_format'] is None: 797 | kwargs['date_format'] = DEFAULT_DATE_FORMAT 798 | 799 | if kwargs['timespec']: 800 | curses.wrapper(countdown, **kwargs) 801 | else: 802 | seconds_elapsed, laps = curses.wrapper(stopwatch, **kwargs) 803 | 804 | for lap_index, lap_time in enumerate(laps): 805 | stderr.write("{:.3f}\t{}\tlap {}\n".format( 806 | lap_time, 807 | format_seconds(int(lap_time)), 808 | lap_index + 1, 809 | )) 810 | 811 | if laps: 812 | stderr.write("{:.3f}\t{}\tlap {}\n".format( 813 | seconds_elapsed, 814 | format_seconds(int(seconds_elapsed)), 815 | len(laps) + 1, 816 | )) 817 | laps.append(seconds_elapsed) 818 | total_seconds = sum(laps) 819 | average_seconds = total_seconds / len(laps) 820 | stderr.write("{:.3f}\t{}\tlap avg\n".format( 821 | average_seconds, 822 | format_seconds(int(average_seconds)), 823 | )) 824 | stderr.write("{:.3f}\t{}\ttotal\n".format( 825 | total_seconds, 826 | format_seconds(int(total_seconds)), 827 | )) 828 | else: 829 | stderr.write("{:.3f}\t{}\ttotal\n".format( 830 | seconds_elapsed, 831 | format_seconds(int(seconds_elapsed)), 832 | )) 833 | stderr.flush() 834 | 835 | 836 | if __name__ == '__main__': 837 | main() 838 | --------------------------------------------------------------------------------