├── .gitignore ├── .gitlab-ci.yml ├── LICENSE ├── MANIFEST.in ├── README.md ├── doc ├── css-themes.png ├── declarative-form.jpg ├── flow-layout.gif └── tag-bar.gif ├── examples ├── analytics-app.py ├── css_editor.py ├── declarative-form.py ├── error-reporting.py ├── message-box.py ├── row-table.py └── tag-bar.py ├── guibedos ├── __init__.py ├── analytics │ ├── __init__.py │ ├── __main__.py │ ├── constants.py │ ├── elasticsearch_.py │ ├── json_.py │ ├── runner.py │ └── subprocess_async.py ├── blender27.py ├── blender29.py ├── constants.py ├── css │ ├── __init__.py │ ├── css.py │ └── editor │ │ ├── __init__.py │ │ ├── color.py │ │ ├── css_text_edit.py │ │ ├── editor.py │ │ ├── highlighter.py │ │ └── variables.py ├── declarative_form │ ├── __init__.py │ ├── constants.py │ ├── form.py │ ├── groupbox.py │ ├── handler.py │ ├── maker.py │ ├── properties │ │ ├── __init__.py │ │ ├── base_property.py │ │ ├── bool_.py │ │ ├── datetime.py │ │ ├── enum.py │ │ ├── filepath.py │ │ ├── integer.py │ │ ├── label.py │ │ ├── list_.py │ │ └── text.py │ └── widgets │ │ ├── __init__.py │ │ ├── checkbox.py │ │ ├── combobox.py │ │ ├── datetimeedit.py │ │ ├── filepath_widget.py │ │ ├── label_widget.py │ │ ├── lineedit.py │ │ ├── listwidget.py │ │ └── spinbox.py ├── error_reporting │ ├── __init__.py │ └── highlighter.py ├── helpers.py ├── messagebox │ ├── __init__.py │ ├── _widget.py │ └── before.py ├── resources │ ├── dark-blue.qss │ ├── dark-green.qss │ ├── dark-orange.qss │ ├── images │ │ ├── Hmovetoolbar_dark.png │ │ ├── Hmovetoolbar_light.png │ │ ├── Hsepartoolbar_dark.png │ │ ├── Hsepartoolbar_light.png │ │ ├── Vmovetoolbar_dark.png │ │ ├── Vmovetoolbar_light.png │ │ ├── Vsepartoolbar_dark.png │ │ ├── Vsepartoolbar_light.png │ │ ├── background_mdi.png │ │ ├── branch_closed_dark.png │ │ ├── branch_closed_darker.png │ │ ├── branch_end.png │ │ ├── branch_more.png │ │ ├── branch_open_dark.png │ │ ├── branch_open_darker.png │ │ ├── branch_vline.png │ │ ├── checkbox_indeterminate_light.png │ │ ├── checkbox_light.png │ │ ├── close_dark.png │ │ ├── close_light.png │ │ ├── down_arrow_dark.png │ │ ├── down_arrow_darker.png │ │ ├── down_arrow_disabled_dark.png │ │ ├── down_arrow_disabled_light.png │ │ ├── down_arrow_light.png │ │ ├── down_arrow_lighter.png │ │ ├── left_arrow_dark.png │ │ ├── left_arrow_darker.png │ │ ├── left_arrow_disabled_dark.png │ │ ├── left_arrow_disabled_light.png │ │ ├── left_arrow_light.png │ │ ├── left_arrow_lighter.png │ │ ├── more_dark.png │ │ ├── more_light.png │ │ ├── radiobutton_light.png │ │ ├── right_arrow_dark.png │ │ ├── right_arrow_darker.png │ │ ├── right_arrow_disabled_dark.png │ │ ├── right_arrow_disabled_light.png │ │ ├── right_arrow_light.png │ │ ├── right_arrow_lighter.png │ │ ├── sizegrip_dark.png │ │ ├── sizegrip_light.png │ │ ├── splitter_horizontal_dark.png │ │ ├── splitter_horizontal_light.png │ │ ├── splitter_vertical_dark.png │ │ ├── splitter_vertical_light.png │ │ ├── transparent.png │ │ ├── undock_dark.png │ │ ├── undock_light.png │ │ ├── up-down_arrow_dark.png │ │ ├── up-down_arrow_darker.png │ │ ├── up-down_arrow_disabled_dark.png │ │ ├── up-down_arrow_disabled_light.png │ │ ├── up-down_arrow_light.png │ │ ├── up-down_arrow_lighter.png │ │ ├── up_arrow_dark.png │ │ ├── up_arrow_darker.png │ │ ├── up_arrow_disabled_dark.png │ │ ├── up_arrow_disabled_light.png │ │ ├── up_arrow_light.png │ │ └── up_arrow_lighter.png │ ├── light-blue.qss │ ├── light-green.qss │ └── light-orange.qss ├── table │ ├── __init__.py │ ├── row.py │ ├── row_background_processor.py │ ├── row_model_all.py │ ├── row_table_model.py │ ├── row_table_view.py │ └── row_table_widget.py ├── threading.py ├── use_case.py └── widgets │ ├── __init__.py │ ├── counters.py │ ├── flow_layout.py │ └── tag_bar.py ├── setup.py └── tests ├── __init__.py ├── _analytics_script.py └── tests_analytics.py /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .run 3 | __pycache__ 4 | *.py[cod] 5 | 6 | Thumbs.db 7 | -------------------------------------------------------------------------------- /.gitlab-ci.yml: -------------------------------------------------------------------------------- 1 | stages: 2 | - deploy 3 | - docgen 4 | 5 | variables: 6 | PYTHONPATH: "R:/deploy/cube/packages" 7 | 8 | isilon: 9 | stage: deploy 10 | tags: [deploy-windows] 11 | script: 12 | - C:/cube/python3/python.exe c:/cube/scripts/mount-r.py 13 | - C:/cube/python3/python.exe -m releaselucet --staging --pip --drive ISILON 14 | 15 | stornext: 16 | stage: deploy 17 | tags: [deploy-windows] 18 | script: 19 | - C:/cube/python3/python.exe c:/cube/scripts/mount-r.py 20 | - C:/cube/python3/python.exe -m releaselucet --staging --pip --drive STORNEXT 21 | 22 | lyon: 23 | stage: deploy 24 | tags: [deploy-windows] 25 | script: 26 | - C:/cube/python3/python.exe c:/cube/scripts/mount-r.py 27 | - C:/cube/python3/python.exe -m releaselucet --staging --pip --drive LYON 28 | 29 | lyonbuffer: 30 | stage: deploy 31 | tags: [deploy-windows] 32 | script: 33 | - C:/cube/python3/python.exe c:/cube/scripts/mount-r.py 34 | - C:/cube/python3/python.exe -m releaselucet --pip --drive LYONBUFFER 35 | 36 | docgen: 37 | stage: docgen 38 | tags: [docgenyco] 39 | only: 40 | refs: 41 | - master 42 | variables: 43 | - $CI_PROJECT_NAMESPACE == "cube" 44 | script: 45 | - python -m docgenyco $CI_REPOSITORY_URL /home/documentation/production/devdoc/ "Developper documentation" 46 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. http://fsf.org/ 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 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | graft guibedos/resources 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GUI Bedos 2 | 3 | PySide widgets and helpers 4 | 5 | This project is used alongside [Qt.py](https://github.com/mottosso/Qt.py). 6 | 7 | If you don't plan on using Qt.py, you must use PyQt5/PySide2 (`from Qt import QtWidgets`) 8 | 9 | # CSS 10 | 11 | It is common to apply a custom CSS stylesheet to a QApplication. 12 | 13 | This module allows to load 6 different themes, borrowed from the [FreeCAD project](https://github.com/FreeCAD/FreeCAD/tree/master/src/Gui/Stylesheets) 14 | 15 | Stylesheets and icons are provided 16 | 17 | Available themes are 18 | 19 | - `dark-blue` 20 | - `dark-green` 21 | - `dark-orange` 22 | - `light-blue` 23 | - `light-green` 24 | - `light-orange` 25 | 26 | ````python 27 | from Qt.QtWidgets import QApplication, QPushButton 28 | from guibedos import css 29 | 30 | app = QApplication([]) 31 | css.set_theme(app, 'dark-blue') 32 | 33 | button = QPushButton('Hello you') 34 | button.show() 35 | 36 | app.exec_() 37 | ```` 38 | 39 | ![CSS Themes](doc/css-themes.png) 40 | 41 | ## Custom stylesheets 42 | 43 | You can add your custom stylesheets to the chosen theme by passing a list of stylesheets to the `set_theme()` method. 44 | 45 | ````python 46 | custom_stylesheet_file_path = os.path.join( 47 | os.path.abspath((os.path.dirname(__file__))), 48 | 'resources', 49 | 'stylesheet.css' 50 | ).replace('\\', '/') 51 | 52 | custom_stylesheet = open(custom_stylesheet_file_path).read() 53 | 54 | css.set_theme(app, 'dark-blue', [custom_stylesheet]) 55 | ```` 56 | 57 | # Widgets 58 | 59 | ## FlowLayout 60 | 61 | The "flow" layout is not available in native Qt. 62 | 63 | Allows to layout in 2D a 1D array of widgets 64 | 65 | _This widget was borrowed then adapted from [PySide Examples](https://github.com/PySide/Examples/blob/master/examples/layouts/flowlayout.py)_ 66 | 67 | ````python 68 | from Qt.QtWidgets import QPushButton 69 | from guibedos.widgets import FlowLayout 70 | 71 | layout = FlowLayout() 72 | layout.addWidget(QPushButton('one')) 73 | layout.addWidget(QPushButton('two')) 74 | layout.addWidget(QPushButton('three')) 75 | layout.addWidget(QPushButton('four')) 76 | ```` 77 | 78 | ![Flow Layout](doc/flow-layout.gif) 79 | 80 | ## TagBar 81 | 82 | An augmented QLineEdit with buttons, allowing to edit a list of "tags" 83 | 84 | - Text + Button selection with `SHIFT` + `ARROW` 85 | - Copy/Paste 86 | - Clic on button removes it 87 | 88 | ![TagBar](doc/tag-bar.gif) 89 | 90 | _See `examples/tag-bar.py` in this repository_ 91 | 92 | ## DeclarativeForm 93 | 94 | The `DeclarativeForm` allows to generate widgets from a data structure of properties 95 | 96 | Useful for asking the user a series of info without the hassle of manually creating the widgets 97 | 98 | ![DelarativeForm](doc/declarative-form.jpg) 99 | 100 | _See `examples/declarative-form.py` in this repository_ 101 | 102 | ````python 103 | from guibedos import declarative_form as df 104 | 105 | property_ = df.Group('personal_info', caption="Personnal Information", properties=( 106 | df.Text('name', caption='Name', default='Jean'), 107 | df.Text('surname', caption='Surname', default='Bauchefort'), 108 | df.Text('password', caption='Password') 109 | )) 110 | ```` 111 | 112 | Calling `data()` on the widget returns a data structure reflecting property's structure, filled with user-entered values 113 | 114 | ````json 115 | { 116 | "personal_info": { 117 | "name": "Jean", 118 | "surname": "Bauchefort", 119 | "password": "" 120 | } 121 | } 122 | ```` 123 | 124 | ### helpers 125 | 126 | #### Hourglass 127 | 128 | Context manager that freezes the widget and display a hourglass cursor 129 | 130 | ````python 131 | import guibedos.helpers 132 | 133 | class MyWidget(QtWidgets.QWidget): 134 | 135 | def __init__(self, parent=None): 136 | QWidgets.QWidget.__init_(self, parent) 137 | 138 | def lengthy_stuff(): 139 | with guibedos.helpers.Hourglass(self): 140 | # do a lot of stuff 141 | ```` 142 | 143 | #### Update Combo 144 | 145 | Updates a QComboBox items and tries to select previously selected item 146 | 147 | If previously selected item was present, no QSignal is emitted 148 | 149 | ````python 150 | import guibedos.helpers 151 | 152 | guibedos.helpers.update_combo(some_qcombobox, ['some', 'items']) 153 | ```` 154 | 155 | ## Blender 156 | 157 | The module `blender` exposes a way to show QWidgets alongside Blender. 158 | 159 | You will need a custom-compiled PySide build (compiled with the same compiler as Blender) 160 | 161 | This modules groups and docks all widgets into a QMainWindow, and ensures that the QApplication is updated within 162 | blender's main loop. 163 | 164 | **Do not use `QApplication.exec_()`, as it is a synchronous call, and will freeze blender** 165 | 166 | ````python 167 | import guibedos.blender 168 | from some import SomeWidget 169 | 170 | class SomeOperator(bpy.types.Operator): 171 | """ 172 | Does something useful, with PySide 173 | """ 174 | bl_idname = "cube.some" 175 | bl_label = "Some" 176 | 177 | def execute(self, context): 178 | self.report({'OPERATOR'}, 'bpy.ops.cube.some()') 179 | 180 | window = guibedos.blender.new_widget(SomeWidget) 181 | guibedos.blender.dock_to_main_window(window) 182 | 183 | return {'FINISHED'} 184 | 185 | def invoke(self, context, event): 186 | return self.execute(context) 187 | ```` 188 | 189 | ## Notes 190 | 191 | - CSS stylesheets and icons are borrowed from FreeCAD, more info 192 | [here](https://github.com/FreeCAD/FreeCAD/tree/master/src/Gui/Stylesheets) 193 | 194 | - Some parts of this project are borrowed from GPLv2 licensed projects. If so, it is stated in the file 195 | -------------------------------------------------------------------------------- /doc/css-themes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/doc/css-themes.png -------------------------------------------------------------------------------- /doc/declarative-form.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/doc/declarative-form.jpg -------------------------------------------------------------------------------- /doc/flow-layout.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/doc/flow-layout.gif -------------------------------------------------------------------------------- /doc/tag-bar.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/doc/tag-bar.gif -------------------------------------------------------------------------------- /examples/analytics-app.py: -------------------------------------------------------------------------------- 1 | """ 2 | This demonstrates the use of GUI Bedos analytics 3 | 4 | ``` 5 | python -m guidebos.analytics --name AnalyticsDemo --json analytics-demos.json analytics-app.py 6 | ``` 7 | """ 8 | import logging 9 | from Qt import QtWidgets 10 | from guibedos.use_case import use_case 11 | 12 | 13 | logging.basicConfig(level=logging.INFO) 14 | 15 | 16 | class Window(QtWidgets.QWidget): 17 | 18 | def __init__(self, parent=None): 19 | QtWidgets.QWidget.__init__(self, parent) 20 | 21 | self.button_peace = QtWidgets.QPushButton('Ensure world peace') 22 | self.button_peace.clicked.connect(self.peace_clicked) 23 | 24 | self.button_immortal = QtWidgets.QPushButton('Become immortal') 25 | self.button_immortal.clicked.connect(self.immortal_clicked) 26 | 27 | self.button_fly = QtWidgets.QPushButton('Learn to fly') 28 | self.button_fly.clicked.connect(self.fly_clicked) 29 | 30 | layout = QtWidgets.QGridLayout(self) 31 | layout.addWidget(self.button_peace) 32 | layout.addWidget(self.button_immortal) 33 | layout.addWidget(self.button_fly) 34 | 35 | @use_case('Ensure world peace') 36 | def peace_clicked(self): 37 | print("The world is now a peaceful place") 38 | 39 | @use_case('Become immortal') 40 | def immortal_clicked(self): 41 | print("You are now immortal") 42 | 43 | @use_case('Learn to fly') 44 | def fly_clicked(self): 45 | raise RuntimeError("No one can fly") 46 | 47 | 48 | if __name__ == '__main__': 49 | app = QtWidgets.QApplication([]) 50 | 51 | window = Window() 52 | window.resize(800, 150) 53 | window.show() 54 | 55 | app.exec_() 56 | -------------------------------------------------------------------------------- /examples/css_editor.py: -------------------------------------------------------------------------------- 1 | """ 2 | This demonstrates the use of GUI Bedos CSS Editor 3 | """ 4 | import logging 5 | from Qt import QtWidgets 6 | from guibedos.css.editor import CSSEditor 7 | 8 | 9 | logging.basicConfig(level=logging.INFO) 10 | 11 | 12 | class Window(QtWidgets.QWidget): 13 | 14 | def __init__(self, parent=None): 15 | QtWidgets.QWidget.__init__(self, parent) 16 | 17 | self.button_peace = QtWidgets.QPushButton('Ensure world peace') 18 | self.button_peace.clicked.connect(self.peace_clicked) 19 | 20 | self.button_immortal = QtWidgets.QPushButton('Become immortal') 21 | self.button_immortal.clicked.connect(self.immortal_clicked) 22 | 23 | self.button_fly = QtWidgets.QPushButton('Learn to fly') 24 | self.button_fly.clicked.connect(self.fly_clicked) 25 | 26 | layout = QtWidgets.QGridLayout(self) 27 | layout.addWidget(self.button_peace) 28 | layout.addWidget(self.button_immortal) 29 | layout.addWidget(self.button_fly) 30 | 31 | def peace_clicked(self): 32 | print("The world is now a peaceful place") 33 | 34 | def immortal_clicked(self): 35 | print("You are now immortal") 36 | 37 | def fly_clicked(self): 38 | raise RuntimeError("No one can fly") 39 | 40 | 41 | if __name__ == '__main__': 42 | app = QtWidgets.QApplication([]) 43 | 44 | window = Window() 45 | window.resize(800, 150) 46 | window.show() 47 | 48 | # Make sure to instanciate *after* creating the top level widgets 49 | css_editor = CSSEditor('Demo Project') 50 | 51 | app.exec_() 52 | -------------------------------------------------------------------------------- /examples/declarative-form.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os.path 3 | from datetime import datetime 4 | from Qt import QtWidgets, QtCore 5 | from guibedos import css 6 | from guibedos import declarative_form as df 7 | 8 | 9 | def _is_mail_valid(text): 10 | return '@' in text and ' ' not in text 11 | 12 | 13 | root_property = df.Group('personal_info', caption="Personnal Information", properties=( 14 | df.Text('name', caption='Name', default='Jean'), 15 | df.Text('surname', caption='Surname', default='Bauchefort'), 16 | df.Text('password', caption='Password'), 17 | df.Label('info', caption='This is a bit of text\nthat can help your user understand what is going'), 18 | df.Group('address', caption="Address", layout=df.HORIZONTAL, properties=( 19 | df.Text('street', caption='Street', default='123 Fake Street'), 20 | df.Enum('country', caption='Country', items=[ 21 | df.Enum.Item('France', data='FR'), 22 | df.Enum.Item('Etats-Unis', data='US', current=True), 23 | df.Enum.Item('Chine ', data='CH'), 24 | ]) 25 | )), 26 | None, 27 | df.Integer('age', caption='Age', default=27, range_=[18, 109]), 28 | df.Text('email', caption='E-mail', default='jean.bauchefort@gmail.com', validator=_is_mail_valid), 29 | df.Bool('single', caption='Celibataire', default=True), 30 | df.Filepath('profile_picture', caption='Profile picture', default='C:/test.jpg', validator=os.path.exists), 31 | df.Datetime( 32 | 'birthday', 33 | caption='Birthday', 34 | default=datetime.timestamp(datetime.strptime('1995-06-25 03:30:00', "%Y-%m-%d %H:%M:%S")) 35 | ), 36 | df.Group('interests', caption='Centres d interet', layout=df.FLOW, properties=( 37 | df.Bool('music', caption="Musique", default=False), 38 | df.Bool('movies', caption="Cinema", default=True), 39 | df.Bool('sports', caption="Sport", default=False), 40 | df.Bool('alcohol', caption="Alcool", default=False), 41 | df.Bool('cooking', caption="Cuisine", default=False), 42 | df.Bool('travel', caption="Voyages", default=False), 43 | df.Bool('theater', caption="Theatre", default=False), 44 | df.Bool('murder', caption="Meurtre", default=False), 45 | df.Bool('capitalism', caption="Capitalisme", default=False), 46 | df.Bool('communism', caption="Communisme", default=False), 47 | df.Bool('web_dev', caption="Developpement Web", default=False) 48 | )), 49 | df.List('tags', caption='Tags', default=['Personne', 'Humain']) 50 | )) 51 | 52 | 53 | app = QtWidgets.QApplication([]) 54 | css.set_theme(app, 'light-blue') 55 | 56 | widget = df.DeclarativeForm(df.Label('info', caption='this wont be shown')) 57 | 58 | widget.reload(root_property) 59 | 60 | widget.show() 61 | app.exec_() 62 | 63 | print(json.dumps(widget.data(), indent=2)) 64 | -------------------------------------------------------------------------------- /examples/error-reporting.py: -------------------------------------------------------------------------------- 1 | from Qt import QtWidgets 2 | 3 | from guibedos.error_reporting import error_reported 4 | 5 | 6 | class Window(QtWidgets.QWidget): 7 | 8 | def __init__(self, parent=None): 9 | QtWidgets.QWidget.__init__(self, parent) 10 | 11 | self.button_normal = QtWidgets.QPushButton('Normal Button') 12 | self.button_normal.clicked.connect(self.button_normal_clicked) 13 | 14 | self.button_raising = QtWidgets.QPushButton('Error raising Button') 15 | self.button_raising.clicked.connect(self.button_raising_clicked) 16 | 17 | layout = QtWidgets.QGridLayout(self) 18 | layout.addWidget(self.button_normal) 19 | layout.addWidget(self.button_raising) 20 | 21 | @error_reported('Normal Clicked') 22 | def button_normal_clicked(self): 23 | print("Normal button clicked") 24 | 25 | @error_reported('Raising demonstration') 26 | def button_raising_clicked(self): 27 | raise RuntimeError('An exception has occurred') 28 | 29 | 30 | if __name__ == '__main__': 31 | app = QtWidgets.QApplication([]) 32 | 33 | window = Window() 34 | window.resize(800, 150) 35 | window.show() 36 | 37 | app.exec_() 38 | -------------------------------------------------------------------------------- /examples/message-box.py: -------------------------------------------------------------------------------- 1 | from Qt import QtWidgets 2 | 3 | from guibedos.messagebox import before 4 | 5 | 6 | class Window(QtWidgets.QWidget): 7 | 8 | def __init__(self, parent=None): 9 | QtWidgets.QWidget.__init__(self, parent) 10 | 11 | self.button_info = QtWidgets.QPushButton('Information before') 12 | self.button_info.clicked.connect(self.button_info_clicked) 13 | 14 | self.button_warning = QtWidgets.QPushButton('Warning before') 15 | self.button_warning.clicked.connect(self.button_warning_clicked) 16 | 17 | layout = QtWidgets.QGridLayout(self) 18 | layout.addWidget(self.button_info) 19 | layout.addWidget(self.button_warning) 20 | 21 | @before.info('You are about to do something') 22 | def button_info_clicked(self): 23 | print("Something just happened") 24 | 25 | @before.warning('Attention ! You are about to do something !') 26 | def button_warning_clicked(self): 27 | print("Wow ! Something just happened !") 28 | 29 | 30 | if __name__ == '__main__': 31 | app = QtWidgets.QApplication([]) 32 | 33 | window = Window() 34 | window.resize(800, 150) 35 | window.show() 36 | 37 | app.exec_() 38 | -------------------------------------------------------------------------------- /examples/row-table.py: -------------------------------------------------------------------------------- 1 | """ 2 | This demonstrates the usage of a QTableView associated width a QAbstractTableModel 3 | 4 | Presented data is organized in rows 5 | """ 6 | import random 7 | from PySide2.QtWidgets import QApplication 8 | from guibedos.table import Row, RowTableModel, RowTableWidget 9 | 10 | 11 | def process_row(row): 12 | row.cells[0][0] += ' <' 13 | row.cells[1][1] = (0, 255, 255, 128) 14 | row.cells[4] = ( 15 | 'PROCESSED : {}'.format(row.data), 16 | (255, 0, 0, 150), 17 | (255, 255, 255), 18 | None 19 | ) 20 | 21 | return row 22 | 23 | 24 | def make_data(row_count): 25 | rows = list() 26 | colors = [None, (0, 255, 255), (255, 255, 0), (255, 0, 255), (255, 0, 0), (0, 255, 0), (0, 0, 255)] 27 | words = [ 28 | "Word", "War", "Why", "Jambon", "Beurre", "Pomme", "Lenalol", "Pulene", 29 | "Monde", "Guerre", "Pourquoi", "Ham", "Butter", "Apple", "Imaig", "Pouer" 30 | ] 31 | processed_words = ["Apathie", "Finance", "Usul", "Gataz", "Arnault", "Ponpon"] 32 | 33 | for i in range(row_count): 34 | rows.append(Row([ 35 | (random.choice(words), None, None, i), # cell column 0 36 | (random.choice(words), random.choice(colors), None, None), # cell column 1 37 | (random.choice(words), None, None, None), # cell column 2 38 | (random.choice(words), None, random.choice(colors), None), # cell column 3 39 | ('...', None, None, None) # cell column 4, will be computed in background 40 | ], { 41 | "random_word": random.choice(processed_words) 42 | })) 43 | 44 | return rows 45 | 46 | 47 | if __name__ == '__main__': 48 | app = QApplication([]) 49 | vue = RowTableWidget( 50 | auto_resize=False, 51 | single_row_select=True, 52 | context_menu_callback=None 53 | ) 54 | 55 | model = RowTableModel( 56 | background_processing_callback=process_row 57 | ) 58 | model.set_headers(['Header', 'are', 'set', 'here', 'Computed data here']) 59 | model.set_rows(make_data(200)) 60 | model.start() 61 | 62 | vue.set_model(model) 63 | 64 | vue.resize(1280, 720) 65 | vue.show() 66 | 67 | app.exec_() 68 | -------------------------------------------------------------------------------- /examples/tag-bar.py: -------------------------------------------------------------------------------- 1 | from Qt import QtWidgets 2 | from guibedos import css 3 | from guibedos.widgets import TagBar 4 | 5 | 6 | class Window(QtWidgets.QWidget): 7 | 8 | def __init__(self, parent=None): 9 | QtWidgets.QWidget.__init__(self, parent) 10 | 11 | self.one = TagBar() 12 | self.one.autocompletables = ['Layout', 'Buildings', 'Characters', 'Animation'] 13 | self.two = TagBar() 14 | 15 | layout = QtWidgets.QGridLayout(self) 16 | layout.addWidget(QtWidgets.QLabel("TagBar 1 :"), 0, 0) 17 | layout.addWidget(self.one, 0, 1) 18 | layout.addWidget(QtWidgets.QLabel("TagBar 2 :"), 1, 0) 19 | layout.addWidget(self.two, 1, 1) 20 | layout.addWidget(QtWidgets.QWidget(), 2, 0) 21 | layout.setColumnStretch(1, 100) 22 | layout.setRowStretch(2, 100) 23 | 24 | self.one.set_tags(['Modeling', 'Vegetation', 'Scatterable']) 25 | self.two.set_tags(['Flowers']) 26 | 27 | 28 | if __name__ == '__main__': 29 | app = QtWidgets.QApplication([]) 30 | css.set_theme(app, 'dark-blue') 31 | 32 | window = Window() 33 | window.resize(800, 150) 34 | window.show() 35 | 36 | print(window.one.tags) 37 | print(window.two.tags) 38 | 39 | app.exec_() 40 | -------------------------------------------------------------------------------- /guibedos/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/__init__.py -------------------------------------------------------------------------------- /guibedos/analytics/__init__.py: -------------------------------------------------------------------------------- 1 | import time 2 | import logging 3 | import functools 4 | 5 | from .constants import * 6 | 7 | 8 | def analyzed(name): 9 | logging.info(REGISTER_MESSAGE, name) 10 | 11 | def decorator(func): 12 | 13 | @functools.wraps(func) 14 | def wrapper(*args, **kwargs): 15 | now = time.time() 16 | raised = False 17 | 18 | try: 19 | return func(*args, **kwargs) 20 | 21 | except Exception as e: 22 | raised = True 23 | raise 24 | 25 | finally: 26 | logging.info( 27 | CALL_MESSAGE, 28 | name, 29 | time.time() - now, 30 | ['', '*'][raised] 31 | ) 32 | 33 | return wrapper 34 | 35 | return decorator 36 | -------------------------------------------------------------------------------- /guibedos/analytics/__main__.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import logging 3 | import argparse 4 | 5 | from guibedos.analytics.runner import Runner 6 | 7 | 8 | def parse_args(args): 9 | parser = argparse.ArgumentParser( 10 | prog='python -m guibedos.analytics', 11 | description='Wrap a python command to parse analytics log messages' 12 | ) 13 | 14 | parser.add_argument( 15 | '-n', '--name', 16 | type=str, 17 | required=True, 18 | help='application name' 19 | ) 20 | 21 | parser.add_argument( 22 | '-j', '--json', 23 | type=str, 24 | required=False, 25 | help='JSON filepath to output report to' 26 | ) 27 | parser.add_argument( 28 | '-e', '--elasticsearch', 29 | type=str, 30 | help='host to elasticsearch to save report to' 31 | ) 32 | 33 | return parser.parse_known_args(args) 34 | 35 | 36 | if __name__ == '__main__': 37 | logging.basicConfig(level=logging.INFO) 38 | 39 | parsed_args, command = parse_args(sys.argv[1:]) 40 | 41 | runner = Runner(parsed_args.name) 42 | report = runner.run([sys.executable] + command) 43 | 44 | if parsed_args.json: 45 | from guibedos.analytics.json_ import JSON 46 | 47 | json = JSON(parsed_args.json) 48 | json.save(report) 49 | 50 | if parsed_args.elasticsearch: 51 | from guibedos.analytics.elasticsearch_ import Elasticsearch 52 | 53 | elasticsearch = Elasticsearch(parsed_args.elasticsearch) 54 | elasticsearch.save(report) 55 | 56 | sys.exit(report['exit_code']) 57 | -------------------------------------------------------------------------------- /guibedos/analytics/constants.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | REGISTER_MESSAGE = "Analytics register [%s]" 4 | REGISTER_PATTERN = r"Analytics register \[([^\]]+)]" 5 | 6 | CALL_MESSAGE = "Analytics call[%s](%s)%s" 7 | CALL_PATTERN = r"Analytics call\[([^\]]+)]\(([^)]+)\)(\*?)" 8 | -------------------------------------------------------------------------------- /guibedos/analytics/elasticsearch_.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from datetime import datetime 3 | 4 | import elasticsearch 5 | 6 | 7 | class Elasticsearch: 8 | def __init__(self, host): 9 | self.connection = elasticsearch.Elasticsearch(host) 10 | 11 | def save(self, report): 12 | logging.info('Analytics : saving session data to Elasticsearch') 13 | 14 | timestamp = datetime.fromtimestamp(report['start_time']).astimezone().isoformat() 15 | 16 | self.connection.index( 17 | index='guibedosanalytics_session', 18 | body={ 19 | 'timestamp': timestamp, 20 | 'name': report['name'], 21 | 'exit_code': not report['exit_code'], 22 | 'duration': report['session_duration'] 23 | } 24 | ) 25 | 26 | for name, details in report['calls'].items(): 27 | details.update( 28 | session=report['name'], 29 | timestamp=timestamp 30 | ) 31 | self.connection.index( 32 | index='guibedosanalytics_call', 33 | body=details 34 | ) 35 | -------------------------------------------------------------------------------- /guibedos/analytics/json_.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | 4 | 5 | class JSON: 6 | def __init__(self, filepath): 7 | self.filepath = filepath 8 | 9 | def save(self, report): 10 | logging.info('Analytics : saving session data to {}'.format(self.filepath)) 11 | 12 | with open(self.filepath, "w+") as f_json: 13 | json.dump(report, f_json, indent=2) 14 | -------------------------------------------------------------------------------- /guibedos/analytics/runner.py: -------------------------------------------------------------------------------- 1 | import re 2 | import time 3 | 4 | from .constants import * 5 | from .subprocess_async import run 6 | 7 | 8 | _RE_REGISTER = re.compile(REGISTER_PATTERN) 9 | _RE_CALL = re.compile(CALL_PATTERN) 10 | 11 | 12 | class Runner: 13 | def __init__(self, name): 14 | self.end_time = 0 15 | self.start_time = 0 16 | self.session_duration = 0 17 | self.name = name 18 | self.calls = dict() 19 | self.exit_code = None 20 | 21 | @property 22 | def report(self): 23 | return vars(self) 24 | 25 | def process_output(self, line): 26 | line = line.decode() 27 | 28 | for registered in _RE_REGISTER.findall(line): 29 | self.calls[registered] = {'calls': list()} 30 | 31 | for called in _RE_CALL.findall(line): 32 | name, duration, error = called 33 | self.calls[name]['calls'].append(( 34 | float(duration), 35 | not error 36 | )) 37 | 38 | def _make_stats(self): 39 | self.session_duration = self.end_time - self.start_time 40 | 41 | for name, data in self.calls.items(): 42 | count = len(data['calls']) 43 | 44 | if count: 45 | total_time = sum(call[0] for call in data['calls']) 46 | average = total_time / count 47 | ratio = total_time / self.session_duration 48 | exception_count = count - sum(call[1] for call in data['calls']) 49 | else: 50 | total_time = 0 51 | average = 0 52 | ratio = 0 53 | exception_count = 0 54 | 55 | self.calls[name] = { 56 | 'name': name, 57 | 'time_ratio': ratio, 58 | 'total_time': total_time, 59 | 'average': average, 60 | 'count': count, 61 | 'exception_count': exception_count 62 | } 63 | 64 | def run(self, command): 65 | self.start_time = time.time() 66 | self.exit_code = run(command, stderr_callback=self.process_output) 67 | self.end_time = time.time() 68 | 69 | self._make_stats() 70 | 71 | return self.report 72 | -------------------------------------------------------------------------------- /guibedos/analytics/subprocess_async.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import asyncio 3 | import platform 4 | 5 | 6 | class _Buffer: 7 | """ 8 | This was created to fix JetBrain's FlushingStringIO having no .buffer attribute (used for tests) 9 | https://github.com/JetBrains/teamcity-messages/blob/master/teamcity/common.py 10 | """ 11 | def __init__(self, o): 12 | self.o = o 13 | 14 | def write(self, l): 15 | try: 16 | self.o.buffer.write(l) 17 | except AttributeError: 18 | self.o.write(l.decode()) 19 | 20 | 21 | async def _read_stream(stream, callback, buffer): 22 | while True: 23 | line = await stream.readline() 24 | if line: 25 | buffer.write(line) 26 | if callback is not None: 27 | callback(line) 28 | else: 29 | break 30 | 31 | 32 | async def _stream_subprocess(command, stdout_callback, stderr_callback): 33 | process = await asyncio.create_subprocess_exec( 34 | *command, 35 | stdout=asyncio.subprocess.PIPE, 36 | stderr=asyncio.subprocess.PIPE 37 | ) 38 | 39 | await asyncio.wait([ 40 | _read_stream(process.stdout, stdout_callback, _Buffer(sys.stdout)), 41 | _read_stream(process.stderr, stderr_callback, _Buffer(sys.stderr)) 42 | ]) 43 | 44 | return await process.wait() 45 | 46 | 47 | def run(command, stdout_callback=None, stderr_callback=None): 48 | if platform.system() == "Windows": 49 | loop = asyncio.ProactorEventLoop() 50 | asyncio.set_event_loop(loop) 51 | else: 52 | loop = asyncio.get_event_loop() 53 | 54 | exit_code = loop.run_until_complete( 55 | _stream_subprocess( 56 | command, 57 | stdout_callback, 58 | stderr_callback, 59 | )) 60 | loop.close() 61 | return exit_code 62 | -------------------------------------------------------------------------------- /guibedos/blender27.py: -------------------------------------------------------------------------------- 1 | """ 2 | Allows to use Qt.py inside Blender 3 | 4 | !!! warning 5 | **Do not use** `QApplication.exec_()` as it will block Blender's main loop 6 | 7 | See `tube_scenemanager`, `character_picker` and `resource_library` for examples 8 | """ 9 | import atexit 10 | from Qt import QtCore 11 | from Qt import QtWidgets 12 | from . import css 13 | import bpy 14 | from bpy.app.handlers import persistent 15 | 16 | 17 | _CSS_THEME = 'dark-blue' 18 | _CSS_CENTRAL_STYLE = """ 19 | background-color: #8c8c8c; 20 | background-image: url(qss:images/background_mdi.png); 21 | background-position: center center; 22 | """ 23 | _theme_set = False 24 | _main_window = None 25 | _application = None 26 | _widgets = list() 27 | 28 | 29 | class MainWindow(QtWidgets.QMainWindow): 30 | def __init__(self, parent=None): 31 | QtWidgets.QMainWindow.__init__(self, parent) 32 | self.setWindowTitle("GUI Bedos : Blender") 33 | self.resize(800, 700) 34 | self.setDockNestingEnabled(True) 35 | 36 | central = QtWidgets.QLabel() 37 | central.setStyleSheet(css.parse_images(_CSS_CENTRAL_STYLE)) 38 | self.setCentralWidget(central) 39 | 40 | self.closed = False 41 | 42 | self.settings = QtCore.QSettings('GUIBedos', 'Blender') 43 | geometry = self.settings.value('geometry', '') 44 | if geometry: 45 | self.restoreGeometry(geometry) 46 | 47 | def save_geometry(self): 48 | geometry = self.saveGeometry() 49 | self.settings.setValue('geometry', geometry) 50 | 51 | def closeEvent(self, event): 52 | for dock in self.findChildren(QtWidgets.QDockWidget): 53 | dock.close() 54 | 55 | self.closed = True 56 | 57 | self.save_geometry() 58 | 59 | return QtWidgets.QMainWindow.closeEvent(self, event) 60 | 61 | def event(self, event): 62 | if event.type() == QtCore.QEvent.WindowActivate: 63 | for dock in self.findChildren(QtWidgets.QDockWidget): 64 | #dock.activate() 65 | pass 66 | 67 | return QtWidgets.QMainWindow.event(self, event) 68 | 69 | 70 | class Dockable(QtWidgets.QDockWidget): 71 | """ 72 | QDockWidget that wraps a given QWidget so it can be docked in MainWindow 73 | """ 74 | def __init__(self, wrapped_widget, parent=None): 75 | QtWidgets.QDockWidget.__init__(self, parent) 76 | self.wrapped_widget = wrapped_widget 77 | self.setWidget(self.wrapped_widget) 78 | self.setFeatures(QtWidgets.QDockWidget.DockWidgetClosable | QtWidgets.QDockWidget.DockWidgetMovable) 79 | self.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas) 80 | self.setWindowTitle(self.wrapped_widget.windowTitle()) 81 | 82 | def closeEvent(self, event): 83 | self.wrapped_widget.close() 84 | return QtWidgets.QDockWidget.closeEvent(self, event) 85 | 86 | 87 | @atexit.register 88 | def save_mainwindow_geometry(): 89 | """ 90 | Saves main window's geometry before exiting 91 | """ 92 | global _main_window 93 | 94 | if _main_window is None or _main_window.closed: 95 | return 96 | 97 | _main_window.save_geometry() 98 | 99 | 100 | def ensure_qapplication(): 101 | """ 102 | Ensures that a QApplication instance exists 103 | """ 104 | global _application, _theme_set 105 | 106 | if _application is not None: 107 | return _application 108 | 109 | _application = QtWidgets.QApplication.instance() 110 | if _application is None: 111 | _application = QtWidgets.QApplication([]) 112 | 113 | if not _theme_set: 114 | css.set_theme(_application, _CSS_THEME) 115 | _theme_set = True 116 | 117 | return _application 118 | 119 | 120 | def ensure_main_window(): 121 | global _main_window 122 | 123 | if _main_window is None or _main_window.closed: 124 | _main_window = MainWindow() 125 | _main_window.show() 126 | 127 | return _main_window 128 | 129 | 130 | @persistent 131 | def _event_loop_kick(dummy): 132 | if QtCore.QEventLoop().isRunning(): 133 | QtCore.QEventLoop().processEvents() 134 | 135 | 136 | def ensure_event_loop(): 137 | """ 138 | Ensures that the QEventLoop handler is registered in Blender's main loop 139 | """ 140 | if _event_loop_kick not in bpy.app.handlers.scene_update_post: 141 | bpy.app.handlers.scene_update_post.append(_event_loop_kick) 142 | 143 | 144 | def prevent_deletion(widget): 145 | """ 146 | Registers a widget to prevent its garbage collection 147 | 148 | :param widget: an instance of any subclass of QWidget 149 | """ 150 | global _widgets 151 | if widget not in _widgets: 152 | _widgets.append(widget) 153 | 154 | 155 | def new_widget(widget_class, *args, **kwargs): 156 | """ 157 | Creates an instance of the given widget class and returns it 158 | 159 | Also ensures a QApplication exists, and it's QLoopEvent is handled by a Blender handler 160 | 161 | :param widget_class: class of the widget (any subclass of QWidget) 162 | :param args: positional arguments for widget creation 163 | :param kwargs: named arguments for widget creation 164 | :return: the newly created widget 165 | """ 166 | # TODO : Cleanup _widgets using https://shiboken.readthedocs.io/en/latest/shibokenmodule.html 167 | ensure_qapplication() 168 | new_widget = widget_class(*args, **kwargs) 169 | prevent_deletion(new_widget) 170 | ensure_event_loop() 171 | 172 | return new_widget 173 | 174 | 175 | def dock_to_main_window(widget): 176 | """ 177 | Wraps the given widget into a QDockWidget and docks it to the QMainWindow 178 | """ 179 | main_window = ensure_main_window() 180 | dockable = Dockable(widget) 181 | 182 | if main_window.height() < widget.height(): 183 | main_window.resize(main_window.width(), widget.height()) 184 | 185 | main_window.addDockWidget(QtCore.Qt.LeftDockWidgetArea, dockable) 186 | dockable.show() 187 | -------------------------------------------------------------------------------- /guibedos/blender29.py: -------------------------------------------------------------------------------- 1 | """ 2 | Allows to use Qt.py inside Blender 3 | 4 | !!! warning 5 | **Do not use** `QApplication.exec_()` as it will block Blender's main loop 6 | 7 | See `tube_scenemanager`, `character_picker` and `resource_library` for examples 8 | """ 9 | import atexit 10 | from Qt import QtCore 11 | from Qt import QtWidgets 12 | from . import css 13 | import bpy 14 | from bpy.app.handlers import persistent 15 | 16 | 17 | _CSS_THEME = 'dark-blue' 18 | _CSS_CENTRAL_STYLE = """ 19 | background-color: #8c8c8c; 20 | background-image: url(qss:images/background_mdi.png); 21 | background-position: center center; 22 | """ 23 | _theme_set = False 24 | _main_window = None 25 | _application = None 26 | _widgets = list() 27 | 28 | 29 | class MainWindow(QtWidgets.QMainWindow): 30 | def __init__(self, parent=None): 31 | QtWidgets.QMainWindow.__init__(self, parent) 32 | self.setWindowTitle("GUI Bedos : Blender") 33 | self.resize(800, 700) 34 | self.setDockNestingEnabled(True) 35 | 36 | central = QtWidgets.QLabel() 37 | central.setStyleSheet(css.parse_images(_CSS_CENTRAL_STYLE)) 38 | self.setCentralWidget(central) 39 | 40 | self.closed = False 41 | 42 | self.settings = QtCore.QSettings('GUIBedos', 'Blender') 43 | geometry = self.settings.value('geometry', '') 44 | if geometry: 45 | self.restoreGeometry(geometry) 46 | 47 | def save_geometry(self): 48 | geometry = self.saveGeometry() 49 | self.settings.setValue('geometry', geometry) 50 | 51 | def closeEvent(self, event): 52 | for dock in self.findChildren(QtWidgets.QDockWidget): 53 | dock.close() 54 | 55 | self.closed = True 56 | 57 | self.save_geometry() 58 | 59 | return QtWidgets.QMainWindow.closeEvent(self, event) 60 | 61 | def event(self, event): 62 | if event.type() == QtCore.QEvent.WindowActivate: 63 | for dock in self.findChildren(QtWidgets.QDockWidget): 64 | #dock.activate() 65 | pass 66 | 67 | return QtWidgets.QMainWindow.event(self, event) 68 | 69 | 70 | class Dockable(QtWidgets.QDockWidget): 71 | """ 72 | QDockWidget that wraps a given QWidget so it can be docked in MainWindow 73 | """ 74 | def __init__(self, wrapped_widget, parent=None): 75 | QtWidgets.QDockWidget.__init__(self, parent) 76 | self.wrapped_widget = wrapped_widget 77 | self.setWidget(self.wrapped_widget) 78 | self.setFeatures(QtWidgets.QDockWidget.DockWidgetClosable | QtWidgets.QDockWidget.DockWidgetMovable) 79 | self.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas) 80 | self.setWindowTitle(self.wrapped_widget.windowTitle()) 81 | 82 | def closeEvent(self, event): 83 | self.wrapped_widget.close() 84 | return QtWidgets.QDockWidget.closeEvent(self, event) 85 | 86 | 87 | @atexit.register 88 | def save_mainwindow_geometry(): 89 | """ 90 | Saves main window's geometry before exiting 91 | """ 92 | global _main_window 93 | 94 | if _main_window is None or _main_window.closed: 95 | return 96 | 97 | _main_window.save_geometry() 98 | 99 | 100 | def ensure_qapplication(): 101 | """ 102 | Ensures that a QApplication instance exists 103 | """ 104 | global _application, _theme_set 105 | 106 | if _application is not None: 107 | return _application 108 | 109 | _application = QtWidgets.QApplication.instance() 110 | if _application is None: 111 | _application = QtWidgets.QApplication([]) 112 | 113 | if not _theme_set: 114 | css.set_theme(_application, _CSS_THEME) 115 | _theme_set = True 116 | 117 | return _application 118 | 119 | 120 | def ensure_main_window(): 121 | global _main_window 122 | 123 | if _main_window is None or _main_window.closed: 124 | _main_window = MainWindow() 125 | _main_window.show() 126 | 127 | return _main_window 128 | 129 | 130 | @persistent 131 | def _event_loop_kick(dummy): 132 | if QtCore.QEventLoop().isRunning(): 133 | QtCore.QEventLoop().processEvents() 134 | 135 | 136 | def ensure_event_loop(): 137 | """ 138 | Ensures that the QEventLoop handler is registered in Blender's main loop 139 | """ 140 | if _event_loop_kick not in bpy.app.handlers.depsgraph_update_post: 141 | bpy.app.handlers.depsgraph_update_post.append(_event_loop_kick) 142 | 143 | 144 | def prevent_deletion(widget): 145 | """ 146 | Registers a widget to prevent its garbage collection 147 | 148 | :param widget: an instance of any subclass of QWidget 149 | """ 150 | global _widgets 151 | if widget not in _widgets: 152 | _widgets.append(widget) 153 | 154 | 155 | def new_widget(widget_class, *args, **kwargs): 156 | """ 157 | Creates an instance of the given widget class and returns it 158 | 159 | Also ensures a QApplication exists, and it's QLoopEvent is handled by a Blender handler 160 | 161 | :param widget_class: class of the widget (any subclass of QWidget) 162 | :param args: positional arguments for widget creation 163 | :param kwargs: named arguments for widget creation 164 | :return: the newly created widget 165 | """ 166 | # TODO : Cleanup _widgets using https://shiboken.readthedocs.io/en/latest/shibokenmodule.html 167 | ensure_qapplication() 168 | new_widget = widget_class(*args, **kwargs) 169 | prevent_deletion(new_widget) 170 | ensure_event_loop() 171 | 172 | return new_widget 173 | 174 | 175 | def dock_to_main_window(widget): 176 | """ 177 | Wraps the given widget into a QDockWidget and docks it to the QMainWindow 178 | """ 179 | main_window = ensure_main_window() 180 | dockable = Dockable(widget) 181 | 182 | if main_window.height() < widget.height(): 183 | main_window.resize(main_window.width(), widget.height()) 184 | 185 | main_window.addDockWidget(QtCore.Qt.LeftDockWidgetArea, dockable) 186 | dockable.show() 187 | -------------------------------------------------------------------------------- /guibedos/constants.py: -------------------------------------------------------------------------------- 1 | PROPERTY_SIDE_STROKED = 'sideStroked' -------------------------------------------------------------------------------- /guibedos/css/__init__.py: -------------------------------------------------------------------------------- 1 | from .css import * 2 | -------------------------------------------------------------------------------- /guibedos/css/css.py: -------------------------------------------------------------------------------- 1 | """ 2 | CSS Theme management 3 | 4 | CSS Themes are borrowed from FreeCAD, 5 | more info here https://github.com/FreeCAD/FreeCAD/tree/master/src/Gui/Stylesheets 6 | """ 7 | import os 8 | 9 | 10 | def _root(): 11 | return os.path.dirname((os.path.dirname(__file__))) 12 | 13 | 14 | def parse_images(css_content): 15 | """ 16 | Given a CSS content (text), replaces `qss:` with absolute path to images (i.e the `resources` folder of this repo) 17 | 18 | :param css_content: Text of stylesheet 19 | :return: Parsed text of stylesheet 20 | """ 21 | resources_path = os.path.join(_root(), 'resources') 22 | return css_content.replace('qss:', resources_path.replace('\\', '/') + '/') 23 | 24 | 25 | def set_theme(widget, theme_name, custom_stylesheets=None): 26 | """ 27 | Given a QWidget (can be a QApplication), sets the theme 28 | 29 | Available themes are .qss files in `resources` folder 30 | 31 | :param widget: a QWidget 32 | :param theme_name: name of the .qss file 33 | :param custom_stylesheets: List of custom stylesheets to append to the theme style 34 | """ 35 | if custom_stylesheets is None: 36 | custom_stylesheets = [] 37 | 38 | resources_path = os.path.join(_root(), 'resources') 39 | css_filepath = os.path.join(resources_path, theme_name + '.qss') 40 | 41 | if not os.path.isfile(css_filepath): 42 | raise RuntimeError('Could not find theme file ' + css_filepath) 43 | 44 | with open(css_filepath, 'r') as f_css: 45 | theme_style = f_css.read() 46 | 47 | theme_style = parse_images(theme_style) 48 | complete_style = theme_style + " ".join(custom_stylesheets) 49 | widget.setStyleSheet(complete_style) 50 | -------------------------------------------------------------------------------- /guibedos/css/editor/__init__.py: -------------------------------------------------------------------------------- 1 | from .editor import CSSEditor 2 | -------------------------------------------------------------------------------- /guibedos/css/editor/color.py: -------------------------------------------------------------------------------- 1 | import colorsys 2 | from Qt.QtCore import Signal, Qt 3 | from Qt.QtWidgets import QWidget, QSlider, QGridLayout, QLabel 4 | 5 | 6 | class Color(QWidget): 7 | changed = Signal(object, object, object) 8 | 9 | def __init__(self, parent=None): 10 | QWidget.__init__(self, parent) 11 | 12 | self.hue = QSlider() 13 | self.hue.setMaximum(100) 14 | self.hue.setOrientation(Qt.Horizontal) 15 | self.hue.valueChanged.connect(self._changed) 16 | 17 | self.saturation = QSlider() 18 | self.saturation.setMaximum(100) 19 | self.saturation.setOrientation(Qt.Horizontal) 20 | self.saturation.valueChanged.connect(self._changed) 21 | 22 | self.value = QSlider() 23 | self.value.setMaximum(100) 24 | self.value.setOrientation(Qt.Horizontal) 25 | self.value.valueChanged.connect(self._changed) 26 | 27 | layout = QGridLayout(self) 28 | layout.addWidget(QLabel("H")) 29 | layout.addWidget(QLabel("S")) 30 | layout.addWidget(QLabel("V")) 31 | layout.addWidget(self.hue, 0, 1) 32 | layout.addWidget(self.saturation, 1, 1) 33 | layout.addWidget(self.value, 2, 1) 34 | 35 | def set_rgb(self, r, g, b): 36 | h, s, v = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0) 37 | self.hue.setValue(h * 100) 38 | self.saturation.setValue(s * 100) 39 | self.value.setValue(v * 100) 40 | 41 | def _changed(self): 42 | r, g, b = colorsys.hsv_to_rgb( 43 | self.hue.value() / 100.0, 44 | self.saturation.value() / 100.0, 45 | self.value.value() / 100.0, 46 | ) 47 | self.changed.emit( 48 | int(r * 255), 49 | int(g * 255), 50 | int(b * 255) 51 | ) 52 | -------------------------------------------------------------------------------- /guibedos/css/editor/css_text_edit.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | from Qt.QtGui import QFont 4 | from Qt.QtCore import Signal 5 | from Qt.QtWidgets import QTabWidget, QPlainTextEdit 6 | 7 | from .highlighter import TemplateHighlighter 8 | 9 | 10 | RE_TABS = re.compile(r'^\/\*([^\/\*]+)\*\/$', re.MULTILINE) 11 | DEFAULT_TAB = "CSS" 12 | 13 | 14 | class CSSTextEdit(QTabWidget): 15 | changed = Signal() 16 | 17 | def __init__(self, parent=None): 18 | QTabWidget.__init__(self, parent) 19 | 20 | self._font = QFont('monospace') 21 | self._texts = dict() 22 | self._widgets_indexes = dict() 23 | 24 | self.new_tab(DEFAULT_TAB, '') 25 | 26 | def clear(self): 27 | QTabWidget.clear(self) 28 | self._texts = dict() 29 | self._widgets_indexes = dict() 30 | 31 | def new_tab(self, title, text): 32 | new_editor = QPlainTextEdit() 33 | new_editor.setFont(self._font) 34 | new_editor.setPlainText(text) 35 | TemplateHighlighter(new_editor.document()) 36 | 37 | new_editor.textChanged.connect(self._text_changed) 38 | self._widgets_indexes[new_editor] = self.count() 39 | self.addTab(new_editor, title) 40 | 41 | def set_plain_text(self, text): 42 | self.clear() 43 | 44 | if not text: 45 | self.new_tab(DEFAULT_TAB, '') 46 | return 47 | 48 | items = iter(RE_TABS.split(text)) 49 | for item in items: 50 | if not item: 51 | continue 52 | 53 | tab_name = item.strip() 54 | tab_text = next(items).strip() 55 | 56 | self._texts[tab_name] = tab_text 57 | self.new_tab(tab_name, tab_text) 58 | 59 | def plain_text(self): 60 | texts = list() 61 | for name, text in self._texts.items(): 62 | if not text: 63 | continue 64 | 65 | texts.append('/* {} */'.format(name)) 66 | texts.append(text) 67 | texts.append("") 68 | 69 | return '\n'.join(texts) 70 | 71 | def _text_changed(self, *args): 72 | text_edit = self.sender() 73 | text = text_edit.toPlainText() 74 | tab_name = self.tabBar().tabText(self._widgets_indexes[self.sender()]) 75 | 76 | self._texts[tab_name] = text 77 | 78 | if RE_TABS.findall(text): 79 | whole_text = self.plain_text() 80 | self.set_plain_text(whole_text) 81 | 82 | self.changed.emit() 83 | -------------------------------------------------------------------------------- /guibedos/css/editor/editor.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | 4 | import jinja2 5 | from jinja2.exceptions import TemplateSyntaxError 6 | from Qt.QtCore import Qt 7 | from Qt.QtWidgets import QApplication, QWidget, QGridLayout, QPlainTextEdit, QSplitter, QPushButton, QLineEdit 8 | 9 | from guibedos.helpers import WindowPosition 10 | from .variables import Variables 11 | from .css_text_edit import CSSTextEdit 12 | 13 | 14 | EDITOR_STATE = '.csseditor' 15 | THEME_VARIABLES = 'theme.variables' 16 | THEME_TEMPLATE = 'theme.template' 17 | COLOR_VARIANTS = [ 18 | 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 95 19 | ] 20 | 21 | 22 | class CSSEditor: 23 | """ 24 | Make sure to instanciate *after* creating the top level widgets of your QApplication 25 | """ 26 | def __init__(self, project_name): 27 | self.project_name = project_name 28 | self._app = QApplication.instance() 29 | self._css_filepath = None 30 | 31 | self.main_window = QWidget() 32 | self.main_window.setWindowFlags(Qt.Tool) 33 | self.main_window.setWindowTitle("CSS Editor - " + self.project_name) 34 | 35 | self.variables = Variables() 36 | self.variables.changed.connect(self._variables_changed) 37 | self.variables.changed.connect(self._render_and_apply) 38 | 39 | self.template = CSSTextEdit() 40 | self.template.changed.connect(self._template_changed) 41 | self.template.changed.connect(self._render_and_apply) 42 | 43 | self.save = QPushButton('Save stylesheet to') 44 | self.save.clicked.connect(self._save_stylesheet) 45 | 46 | self.save_destination = QLineEdit() 47 | self.save_destination.textChanged.connect(self._destination_changed) 48 | 49 | self.splitter = QSplitter() 50 | self.splitter.setOrientation(Qt.Vertical) 51 | self.splitter.addWidget(self.variables) 52 | self.splitter.addWidget(self.template) 53 | 54 | layout = QGridLayout(self.main_window) 55 | layout.addWidget(self.splitter, 0, 0, 1, 2) 56 | layout.addWidget(self.save, 1, 0) 57 | layout.addWidget(self.save_destination, 1, 1) 58 | 59 | self.main_window.resize(800, 600) 60 | 61 | self._project_dir = self._ensure_project_dir() 62 | self._top_level_widgets = [ 63 | widget for widget in QApplication.topLevelWidgets() if 64 | widget.windowTitle() != self.main_window.windowTitle() 65 | ] 66 | self._variables = dict() 67 | self._template = None 68 | self._stylesheet = "" 69 | 70 | self._app.aboutToQuit.connect(self._save_editor_state) 71 | self._open() 72 | self.save_destination.setText(self.css_filepath) 73 | self.main_window.show() 74 | 75 | @property 76 | def css_filepath(self): 77 | if self._css_filepath is None: 78 | return self._project_dir + self.project_name + '.css' 79 | 80 | return self._css_filepath 81 | 82 | def _ensure_project_dir(self): 83 | dir_ = os.path.expanduser('~/CSSEditor/' + self.project_name + '/') 84 | if not os.path.isdir(dir_): 85 | os.makedirs(dir_) 86 | 87 | return dir_ 88 | 89 | def _open(self): 90 | self.variables.blockSignals(True) 91 | self.template.blockSignals(True) 92 | 93 | try: 94 | with open(self._project_dir + EDITOR_STATE, 'r') as qsseditor_file: 95 | qsseditor = json.load(qsseditor_file) 96 | WindowPosition.restore(self.main_window, qsseditor['window']) 97 | self.splitter.setSizes(qsseditor['splitter']) 98 | self._css_filepath = qsseditor.get('save_destination', self.css_filepath) 99 | self.save_destination.setText(self._css_filepath) 100 | 101 | with open(self._project_dir + THEME_VARIABLES, 'r') as f_variables: 102 | self.variables.variables = json.load(f_variables) 103 | 104 | with open(self._project_dir + THEME_TEMPLATE, 'r') as f_template: 105 | self.template.set_plain_text(f_template.read()) 106 | except Exception as e: 107 | pass 108 | self.variables.blockSignals(False) 109 | self.template.blockSignals(False) 110 | 111 | self._template_changed() 112 | self._variables_changed() 113 | self._render_and_apply() 114 | 115 | def _destination_changed(self): 116 | self._css_filepath = self.save_destination.text() 117 | self._save_editor_state() 118 | 119 | def _save_editor_state(self): 120 | with open(self._project_dir + EDITOR_STATE, 'w+') as f_qsseditor: 121 | json.dump({ 122 | 'window': WindowPosition.save(self.main_window), 123 | 'splitter': self.splitter.sizes(), 124 | 'save_destination': self.css_filepath 125 | }, f_qsseditor) 126 | 127 | def _template_changed(self): 128 | template = self.template.plain_text() 129 | with open(self._project_dir + THEME_TEMPLATE, 'w+') as f_template: 130 | f_template.write(template) 131 | 132 | try: 133 | self._template = jinja2.Template(template) 134 | except TemplateSyntaxError: 135 | pass 136 | 137 | def _variables_changed(self): 138 | with open(self._project_dir + THEME_VARIABLES, 'w+') as f_variables: 139 | f_variables.write(json.dumps(self.variables.variables, indent=2)) 140 | 141 | self._variables = dict() 142 | 143 | for variable_name, variable_value in self.variables.variables.items(): 144 | if isinstance(variable_value, list) and len(variable_value) == 3: 145 | self._variables[variable_name] = 'rgb({})'.format(', '.join([str(channel) for channel in variable_value])) 146 | 147 | for variant in COLOR_VARIANTS: 148 | channels = [str(int(channel * variant * 0.01)) for channel in variable_value] 149 | self._variables['{}{:02d}'.format(variable_name, variant)] = 'rgb({})'.format(', '.join(channels)) 150 | 151 | else: 152 | self._variables[variable_name] = variable_value 153 | 154 | def _apply_style(self, style): 155 | for widget in self._top_level_widgets: 156 | widget.setStyleSheet(style) 157 | 158 | def _render_and_apply(self): 159 | self._apply_style("") 160 | 161 | if self._template is None: 162 | return 163 | 164 | self._stylesheet = self._template.render(**self._variables) 165 | self._apply_style(self._stylesheet) 166 | 167 | def _save_stylesheet(self): 168 | stylesheet = [ 169 | "/* GUI Bedos - CSS Template */", 170 | "/****************************/", 171 | "", 172 | "/* VARIABLES", 173 | json.dumps(self.variables.variables, indent=2), 174 | "/****************************/", 175 | "", 176 | "/* TEMPLATE", 177 | self.template.plain_text().replace('*/', '*|'), 178 | "/****************************/", 179 | "", 180 | "/* ACTUAL CSS */", 181 | "", 182 | self._stylesheet 183 | ] 184 | with open(self.css_filepath, 'w+') as f_stylesheet: 185 | f_stylesheet.write('\n'.join(stylesheet)) 186 | -------------------------------------------------------------------------------- /guibedos/css/editor/highlighter.py: -------------------------------------------------------------------------------- 1 | import re 2 | from Qt.QtCore import Qt 3 | from Qt.QtGui import QSyntaxHighlighter, QTextCharFormat, QFont 4 | 5 | 6 | COMMENT_RE = re.compile(r"/\*.+\*/") 7 | COMMENT_FORMAT = QTextCharFormat() 8 | COMMENT_FORMAT.setFontItalic(True) 9 | COMMENT_FORMAT.setForeground(Qt.darkGray) 10 | 11 | JINJA_RE = re.compile(r"{{.+}}") 12 | JINJA_FORMAT = QTextCharFormat() 13 | JINJA_FORMAT.setFontWeight(QFont.Bold) 14 | JINJA_FORMAT.setForeground(Qt.darkMagenta) 15 | 16 | QCLASS_RE = re.compile(r"Q[\w]+") 17 | QCLASS_FORMAT = QTextCharFormat() 18 | QCLASS_FORMAT.setFontWeight(QFont.Bold) 19 | QCLASS_FORMAT.setForeground(Qt.darkGreen) 20 | 21 | QSUBELEMENT_RE = re.compile(r"::([\w-]+)") 22 | QSUBELEMENT_FORMAT = QTextCharFormat() 23 | QSUBELEMENT_FORMAT.setFontWeight(QFont.Bold) 24 | QSUBELEMENT_FORMAT.setForeground(Qt.darkBlue) 25 | 26 | PROPERTY_RE = re.compile(r"\[[^=]+=[^\]]+]") 27 | PROPERTY_FORMAT = QTextCharFormat() 28 | PROPERTY_FORMAT.setFontItalic(True) 29 | PROPERTY_FORMAT.setForeground(Qt.darkGreen) 30 | 31 | 32 | class TemplateHighlighter(QSyntaxHighlighter): 33 | RULES = { 34 | QCLASS_RE: QCLASS_FORMAT, 35 | QSUBELEMENT_RE: QSUBELEMENT_FORMAT, 36 | PROPERTY_RE: PROPERTY_FORMAT, 37 | JINJA_RE: JINJA_FORMAT, 38 | COMMENT_RE: COMMENT_FORMAT, 39 | } 40 | 41 | def __init__(self, parent=None): 42 | QSyntaxHighlighter.__init__(self, parent) 43 | 44 | def highlightBlock(self, text): 45 | for expression, style in self.RULES.items(): 46 | 47 | for found in expression.finditer(text): 48 | start, end = found.span() 49 | self.setFormat(start, end - start, style) 50 | -------------------------------------------------------------------------------- /guibedos/css/editor/variables.py: -------------------------------------------------------------------------------- 1 | from Qt.QtCore import Signal 2 | from Qt.QtWidgets import QWidget, QGridLayout, QTableWidget, QPushButton, QTableWidgetItem 3 | from .color import Color 4 | 5 | 6 | class Variables(QWidget): 7 | changed = Signal(object) 8 | 9 | def __init__(self, parent=None): 10 | QWidget.__init__(self, parent) 11 | 12 | self.setMinimumWidth(500) 13 | 14 | self.table = QTableWidget() 15 | self.table.setSelectionMode(QTableWidget.SingleSelection) 16 | self.table.itemChanged.connect(self._item_changed) 17 | self.table.currentItemChanged.connect(self._current_item_changed) 18 | self.table.horizontalHeader().hide() 19 | self.table.verticalHeader().hide() 20 | self.table.setColumnCount(3) 21 | self.table.horizontalHeader().resizeSection(0, 200) 22 | self.table.horizontalHeader().resizeSection(1, 200) 23 | self.table.horizontalHeader().resizeSection(2, 20) 24 | 25 | self.new = QPushButton('New variable') 26 | self.new.clicked.connect(self._new) 27 | 28 | self.color = Color() 29 | self.color.changed.connect(self._color_changed) 30 | 31 | layout = QGridLayout(self) 32 | layout.addWidget(self.table) 33 | layout.addWidget(self.color) 34 | layout.addWidget(self.new) 35 | 36 | @property 37 | def variables(self): 38 | variables = dict() 39 | 40 | for row_index in range(self.table.rowCount()): 41 | name = self.table.item(row_index, 0).text() 42 | value = self.table.item(row_index, 1).text() 43 | 44 | if value.startswith('[') and value.endswith(']'): 45 | value = eval(value) # OULA LA 46 | 47 | variables[name] = value 48 | 49 | return variables 50 | 51 | @variables.setter 52 | def variables(self, variables): 53 | self.table.blockSignals(True) 54 | self.table.clear() 55 | for name, value in variables.items(): 56 | self._add_row(name, value) 57 | 58 | self.table.blockSignals(False) 59 | self.changed.emit(variables) 60 | 61 | def _item_changed(self, item): 62 | self.changed.emit(self.variables) 63 | self._current_item_changed(item) 64 | 65 | def _current_item_changed(self, item): 66 | self.color.setEnabled(False) 67 | 68 | if item is None or item.column() != 1: 69 | return 70 | 71 | text = item.text().strip() 72 | if not (text.startswith('[') and text.endswith(']')): 73 | return 74 | 75 | r, g, b = [int(channel.strip()) for channel in text[1:-1].split(',')] 76 | 77 | self.color.blockSignals(True) 78 | self.color.set_rgb(r, g, b) 79 | self.color.setEnabled(True) 80 | self.color.blockSignals(False) 81 | 82 | def _color_changed(self, r, g, b): 83 | self.table.blockSignals(True) 84 | self.table.currentItem().setText('[{}, {}, {}]'.format(r, g, b)) 85 | self.table.blockSignals(False) 86 | self.changed.emit(self.variables) 87 | 88 | def _add_row(self, name, value): 89 | row = self.table.rowCount() 90 | self.table.setRowCount(row + 1) 91 | 92 | name = QTableWidgetItem(name) 93 | value = QTableWidgetItem(str(value)) 94 | 95 | delete = QPushButton("X") 96 | delete.name_item = name 97 | delete.clicked.connect(self._delete) 98 | 99 | self.table.blockSignals(True) 100 | self.table.setItem(row, 0, name) 101 | self.table.setItem(row, 1, value) 102 | self.table.setCellWidget(row, 2, delete) 103 | self.table.blockSignals(False) 104 | 105 | def _new(self): 106 | self._add_row('new_variable', '[255, 255, 255]') 107 | self.changed.emit(self.variables) 108 | 109 | def _delete(self): 110 | name_item = self.sender().name_item 111 | self.table.removeRow(name_item.row()) 112 | 113 | self.changed.emit(self.variables) 114 | -------------------------------------------------------------------------------- /guibedos/declarative_form/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Declarative Form 3 | 4 | A data structure based Form widget for user input 5 | 6 | see `demo-declarative-form.py` 7 | """ 8 | from .constants import * 9 | from .properties import * 10 | from .form import DeclarativeForm 11 | from .handler import InteractionHandler 12 | -------------------------------------------------------------------------------- /guibedos/declarative_form/constants.py: -------------------------------------------------------------------------------- 1 | FLOW = 'FLOW' 2 | VERTICAL = 'VERTICAL' 3 | HORIZONTAL = 'HORIZONTAL' 4 | -------------------------------------------------------------------------------- /guibedos/declarative_form/form.py: -------------------------------------------------------------------------------- 1 | from Qt import QtWidgets 2 | from . import maker, handler 3 | from guibedos.helpers import clear_layout 4 | 5 | 6 | _ROOT_WIDGET = '_ROOT_WIDGET' 7 | 8 | 9 | class DeclarativeForm(QtWidgets.QFrame): 10 | def __init__(self, root_property, parent=None, handler=None): 11 | QtWidgets.QFrame.__init__(self, parent) 12 | self.handler = handler 13 | self.reload(root_property) 14 | 15 | def reload(self, root_property): 16 | if not self.layout(): 17 | layout = QtWidgets.QVBoxLayout(self) 18 | layout.setContentsMargins(0, 0, 0, 0) 19 | else: 20 | clear_layout(self.layout()) 21 | 22 | self.base_widget = maker.make_widget(root_property, self) 23 | 24 | if self.handler: 25 | self.handler.assign(self.widgets()) 26 | 27 | def widgets(self, widget=_ROOT_WIDGET): 28 | widgets = dict() 29 | if widget == _ROOT_WIDGET: 30 | widget = self.base_widget 31 | 32 | if widget is None: 33 | return dict() 34 | 35 | property_ = widget.property_ 36 | 37 | if isinstance(widget, QtWidgets.QGroupBox): 38 | subdata = dict() 39 | for subwidget in widget.subwidgets: 40 | subdata.update(self.widgets(subwidget)) 41 | widgets[property_] = subdata 42 | 43 | else: 44 | widgets[widget.property_] = widget 45 | 46 | return widgets 47 | 48 | def data(self, widget=_ROOT_WIDGET): 49 | data_ = dict() 50 | if widget == _ROOT_WIDGET: 51 | widget = self.base_widget 52 | 53 | if widget is None: 54 | return dict() 55 | 56 | property_ = widget.property_ 57 | 58 | if isinstance(widget, QtWidgets.QGroupBox): 59 | subdata = dict() 60 | for subwidget in widget.subwidgets: 61 | subdata.update(self.data(subwidget)) 62 | data_[property_.name] = subdata 63 | 64 | else: 65 | data_[widget.property_.name] = property_.value if property_.is_valid() else None 66 | 67 | return data_ 68 | -------------------------------------------------------------------------------- /guibedos/declarative_form/groupbox.py: -------------------------------------------------------------------------------- 1 | from Qt import QtWidgets 2 | from guibedos.widgets import FlowLayout 3 | # TODO : this is not part of the widgets packages because maker cannot be imported from there -> "find a better way" 4 | try: 5 | import maker 6 | from constants import * 7 | except ModuleNotFoundError as e: 8 | from . import maker 9 | from .constants import * 10 | 11 | 12 | class GroupBox(QtWidgets.QGroupBox): 13 | 14 | def __init__(self, property_, parent=None): 15 | QtWidgets.QGroupBox.__init__(self, property_.caption, parent) 16 | self.property_ = property_ 17 | 18 | layout = { 19 | VERTICAL: QtWidgets.QVBoxLayout, 20 | HORIZONTAL: QtWidgets.QHBoxLayout, 21 | FLOW: FlowLayout 22 | }[self.property_.layout](self) 23 | layout.setContentsMargins(0, 5, 0, 0) 24 | 25 | subwidgets = list() 26 | for subdata in property_.properties: 27 | new_widget = maker.make_widget(subdata, self) 28 | subwidgets.append(new_widget) 29 | 30 | self.subwidgets = subwidgets 31 | -------------------------------------------------------------------------------- /guibedos/declarative_form/handler.py: -------------------------------------------------------------------------------- 1 | class InteractionHandler: 2 | def __init__(self): 3 | self.widgets = {} 4 | 5 | def _get_property(self, given_property, widgets): 6 | for property, widget in widgets.items(): 7 | if property.name == given_property: 8 | return property 9 | 10 | if type(widget) == dict: 11 | result = self._get_property(given_property, widget) 12 | if result: 13 | return result 14 | 15 | return False 16 | 17 | def _get_widget(self, given_property, widgets): 18 | for property, widget in widgets.items(): 19 | if property.name == given_property.name: 20 | return widget 21 | 22 | if type(widget) == dict: 23 | result = self._get_widget(given_property, widget) 24 | if result: 25 | return result 26 | 27 | return False 28 | 29 | def widget(self, widget): 30 | return self._get_widget(widget, self.widgets) 31 | 32 | def property(self, property_name): 33 | return self._get_property(property_name, self.widgets) 34 | 35 | def assign(self, widgets): 36 | self.widgets = widgets 37 | 38 | def register(self, property, callback): 39 | if type(property) == str: 40 | property = self.property(property) 41 | 42 | self.widget(property).callback(callback=callback, sender=property) 43 | -------------------------------------------------------------------------------- /guibedos/declarative_form/maker.py: -------------------------------------------------------------------------------- 1 | from Qt import QtWidgets 2 | from .widgets import * 3 | from .properties import * 4 | from .groupbox import GroupBox 5 | 6 | 7 | def vertical_layout(widgets, stretches=None): 8 | """ 9 | Makes a QWidget with a zero-margin vertical layout, with given QWidgets and stretches 10 | 11 | :param widgets: A list of QWidget 12 | :param stretches: A list of int 13 | :return: A QWidget 14 | """ 15 | widget = QtWidgets.QWidget() 16 | layout = QtWidgets.QHBoxLayout(widget) 17 | layout.setContentsMargins(0, 0, 0, 0) 18 | 19 | if stretches is None: 20 | stretches = [0] * len(widgets) 21 | 22 | for widget_, stretch in zip(widgets, stretches): 23 | layout.addWidget(widget_) 24 | layout.setStretch(layout.count() - 1, stretch) 25 | 26 | return widget 27 | 28 | 29 | def make_widget(property_, parent_widget): 30 | if property_ is None: 31 | return None 32 | 33 | new_widget = { 34 | Group: _make_group, 35 | Label: _make_label, 36 | Text: _make_text, 37 | Enum: _make_enum, 38 | Integer: _make_integer, 39 | Bool: _make_bool, 40 | Datetime: _make_datetime, 41 | Filepath: _make_filepath, 42 | List: _make_list 43 | }[type(property_)](property_, parent_widget) 44 | 45 | return new_widget 46 | 47 | 48 | def _make_group(property_, parent_widget): 49 | group = GroupBox(property_) 50 | 51 | parent_widget.layout().addWidget(group) 52 | return group 53 | 54 | 55 | def _make_label(property_, parent_widget): 56 | label = LabelWidget(property_) 57 | 58 | parent_widget.layout().addWidget(label) 59 | return label 60 | 61 | 62 | def _make_text(property_, parent_widget): 63 | label = QtWidgets.QLabel(property_.caption) 64 | lineedit = LineEdit(property_) 65 | 66 | parent_widget.layout().addWidget(vertical_layout( 67 | widgets=[label, lineedit] 68 | )) 69 | return lineedit 70 | 71 | 72 | def _make_enum(property_, parent_widget): 73 | label = QtWidgets.QLabel(property_.caption) 74 | combo = ComboBox(property_) 75 | 76 | parent_widget.layout().addWidget(vertical_layout( 77 | widgets=[label, combo], 78 | stretches=[0, 100] 79 | )) 80 | return combo 81 | 82 | 83 | def _make_integer(property_, parent_widget): 84 | label = QtWidgets.QLabel(property_.caption) 85 | spin = SpinBox(property_) 86 | 87 | parent_widget.layout().addWidget(vertical_layout( 88 | widgets=[label, spin], 89 | stretches=[0, 100] 90 | )) 91 | return spin 92 | 93 | 94 | def _make_bool(property_, parent_widget): 95 | bool_ = CheckBox(property_) 96 | parent_widget.layout().addWidget(bool_) 97 | return bool_ 98 | 99 | 100 | def _make_filepath(property_, parent_widget): 101 | label = QtWidgets.QLabel(property_.caption) 102 | filepath = FilepathWidget(property_) 103 | parent_widget.layout().addWidget(vertical_layout( 104 | widgets=[label, filepath], 105 | stretches=[0, 100] 106 | )) 107 | return filepath 108 | 109 | 110 | def _make_list(property_, parent_widget): 111 | label = QtWidgets.QLabel(property_.caption) 112 | listwidget = ListWidget(property_) 113 | parent_widget.layout().addWidget(vertical_layout( 114 | widgets=[label, listwidget], 115 | stretches=[0, 100] 116 | )) 117 | return listwidget 118 | 119 | 120 | def _make_datetime(property_, parent_widget): 121 | label = QtWidgets.QLabel(property_.caption) 122 | date_widget = DateTimeEdit(property_) 123 | parent_widget.layout().addWidget(vertical_layout( 124 | widgets=[label, date_widget], 125 | stretches=[0, 100] 126 | )) 127 | return date_widget 128 | 129 | -------------------------------------------------------------------------------- /guibedos/declarative_form/properties/__init__.py: -------------------------------------------------------------------------------- 1 | __all__ = [ 2 | 'Text', 3 | 'Enum', 4 | 'Bool', 5 | 'List', 6 | 'Label', 7 | 'Integer', 8 | 'Filepath', 9 | 'Group', 10 | 'Datetime' 11 | ] 12 | 13 | from .text import Text 14 | from .enum import Enum 15 | from .bool_ import Bool 16 | from .datetime import Datetime 17 | from .list_ import List 18 | from .label import Label 19 | from .integer import Integer 20 | from .filepath import Filepath 21 | from ..constants import * 22 | 23 | 24 | class Group(object): 25 | def __init__(self, name, caption, properties, layout=VERTICAL): 26 | self.name = name 27 | self.caption = caption 28 | self.properties = properties 29 | self.layout = layout 30 | -------------------------------------------------------------------------------- /guibedos/declarative_form/properties/base_property.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class BaseProperty(object): 4 | 5 | def __init__(self, name, caption, default=None, widget=None, validator=None): 6 | self.name = name 7 | self.caption = caption 8 | self.value = default 9 | self.widget = widget 10 | self.validator = validator 11 | 12 | @property 13 | def value(self): 14 | raise NotImplementedError 15 | 16 | @value.setter 17 | def value(self, value): 18 | raise NotImplementedError 19 | 20 | def is_valid(self): 21 | if not self._validate(): 22 | return False 23 | 24 | if self.validator: 25 | return self.validator(self.value) 26 | 27 | return True 28 | 29 | def _validate(self): 30 | raise NotImplementedError 31 | -------------------------------------------------------------------------------- /guibedos/declarative_form/properties/bool_.py: -------------------------------------------------------------------------------- 1 | from .base_property import BaseProperty 2 | 3 | 4 | class Bool(BaseProperty): 5 | 6 | @property 7 | def value(self): 8 | return self._value 9 | 10 | @value.setter 11 | def value(self, value): 12 | self._value = bool(value) 13 | 14 | def _validate(self): 15 | return True 16 | -------------------------------------------------------------------------------- /guibedos/declarative_form/properties/datetime.py: -------------------------------------------------------------------------------- 1 | from .base_property import BaseProperty 2 | 3 | 4 | class Datetime(BaseProperty): 5 | 6 | @property 7 | def value(self): 8 | return self._value 9 | 10 | @value.setter 11 | def value(self, value): 12 | self._value = value 13 | 14 | def _validate(self): 15 | return True 16 | -------------------------------------------------------------------------------- /guibedos/declarative_form/properties/enum.py: -------------------------------------------------------------------------------- 1 | from .base_property import BaseProperty 2 | 3 | 4 | class Enum(BaseProperty): 5 | 6 | class Item(object): 7 | def __init__(self, caption, data, current=False): 8 | self.caption = caption 9 | self.current = current 10 | self.data = data 11 | 12 | def __init__(self, name, caption, items, widget=None, validator=None): 13 | BaseProperty.__init__(self, name, caption, None, widget, validator) 14 | self.items = items 15 | 16 | current_item = self.items[0] 17 | for item in self.items: 18 | if item.current: 19 | current_item = item 20 | break 21 | 22 | for item in self.items: 23 | item.current = item == current_item 24 | 25 | self.value = current_item.data 26 | 27 | @property 28 | def value(self): 29 | return self._value 30 | 31 | @value.setter 32 | def value(self, value): 33 | self._value = value 34 | 35 | def _validate(self): 36 | return True 37 | -------------------------------------------------------------------------------- /guibedos/declarative_form/properties/filepath.py: -------------------------------------------------------------------------------- 1 | import os.path 2 | from .base_property import BaseProperty 3 | 4 | 5 | class Filepath(BaseProperty): 6 | 7 | @property 8 | def value(self): 9 | return self._value 10 | 11 | @value.setter 12 | def value(self, value): 13 | self._value = value 14 | 15 | def _validate(self): 16 | return True 17 | # TODO : is this relevant ? 18 | # if self.value is None: 19 | # return False 20 | # return os.path.exists(self.value) 21 | -------------------------------------------------------------------------------- /guibedos/declarative_form/properties/integer.py: -------------------------------------------------------------------------------- 1 | from .base_property import BaseProperty 2 | 3 | 4 | class Integer(BaseProperty): 5 | def __init__(self, name, caption, range_=None, default=None, widget=None, validator=None): 6 | BaseProperty.__init__(self, name, caption, default, widget, validator) 7 | self.range = range_ 8 | 9 | @property 10 | def value(self): 11 | return self._value 12 | 13 | @value.setter 14 | def value(self, value): 15 | self._value = value 16 | 17 | def _validate(self): 18 | if self.range is None: 19 | return True 20 | lower_bound = self.range[0] is not None and self.value >= self.range[0] 21 | upper_bound = self.range[1] is not None and self.value <= self.range[1] 22 | return lower_bound and upper_bound 23 | -------------------------------------------------------------------------------- /guibedos/declarative_form/properties/label.py: -------------------------------------------------------------------------------- 1 | from .base_property import BaseProperty 2 | 3 | 4 | class Label(BaseProperty): 5 | def __init__(self, name, caption, default=None, widget=None, validator=None): 6 | BaseProperty.__init__(self, name, caption, default, widget, validator) 7 | 8 | @property 9 | def value(self): 10 | return None 11 | 12 | @value.setter 13 | def value(self, value): 14 | pass 15 | 16 | def _validate(self): 17 | return True 18 | -------------------------------------------------------------------------------- /guibedos/declarative_form/properties/list_.py: -------------------------------------------------------------------------------- 1 | from .base_property import BaseProperty 2 | 3 | 4 | class List(BaseProperty): 5 | 6 | def __init__(self, name, caption, default, validator=None): 7 | BaseProperty.__init__(self, name, caption, default, None, validator) 8 | 9 | @property 10 | def value(self): 11 | return self._value 12 | 13 | @value.setter 14 | def value(self, value): 15 | self._value = value 16 | 17 | def _validate(self): 18 | return True 19 | -------------------------------------------------------------------------------- /guibedos/declarative_form/properties/text.py: -------------------------------------------------------------------------------- 1 | from .base_property import BaseProperty 2 | 3 | 4 | class Text(BaseProperty): 5 | 6 | @property 7 | def value(self): 8 | return self._value 9 | 10 | @value.setter 11 | def value(self, value): 12 | self._value = value 13 | 14 | def _validate(self): 15 | return True 16 | -------------------------------------------------------------------------------- /guibedos/declarative_form/widgets/__init__.py: -------------------------------------------------------------------------------- 1 | from .spinbox import SpinBox 2 | from .lineedit import LineEdit 3 | from .checkbox import CheckBox 4 | from .combobox import ComboBox 5 | from .datetimeedit import DateTimeEdit 6 | from .listwidget import ListWidget 7 | from .label_widget import LabelWidget 8 | from .filepath_widget import FilepathWidget 9 | -------------------------------------------------------------------------------- /guibedos/declarative_form/widgets/checkbox.py: -------------------------------------------------------------------------------- 1 | from Qt import QtWidgets 2 | 3 | 4 | class CheckBox(QtWidgets.QCheckBox): 5 | 6 | def __init__(self, property_, parent=None): 7 | QtWidgets.QCheckBox.__init__(self, property_.caption, parent) 8 | self.interaction_callback = None 9 | self.property_ = property_ 10 | self.setChecked(property_.value) 11 | 12 | self.stateChanged.connect(self._value_changed) 13 | 14 | def _value_changed(self, value): 15 | self.property_.value = value 16 | if not self.property_.is_valid(): 17 | self.setStyleSheet("background-color: red") 18 | else: 19 | self.setStyleSheet("") 20 | if self.interaction_callback: 21 | self.interaction_callback(value, self.sender) 22 | 23 | def callback(self, callback, sender): 24 | self.interaction_callback = callback 25 | self.sender = sender 26 | self._value_changed(self.isChecked()) 27 | -------------------------------------------------------------------------------- /guibedos/declarative_form/widgets/combobox.py: -------------------------------------------------------------------------------- 1 | from Qt import QtWidgets 2 | 3 | 4 | class ComboBox(QtWidgets.QComboBox): 5 | 6 | def __init__(self, property_, parent=None): 7 | QtWidgets.QComboBox.__init__(self, parent) 8 | self.property_ = property_ 9 | self.interaction_callback = None 10 | self.addItems([item.caption for item in property_.items]) 11 | 12 | self.setCurrentIndex(-1) 13 | for index, item in enumerate(self.property_.items): 14 | if item.current: 15 | self.setCurrentIndex(index) 16 | 17 | self.currentIndexChanged.connect(self._value_changed) 18 | 19 | def _value_changed(self, index): 20 | caption = self.currentText() 21 | current_item = None 22 | 23 | for item in self.property_.items: 24 | if item.caption == caption: 25 | current_item = item 26 | item.current = True 27 | else: 28 | item.current = False 29 | 30 | self.property_.value = current_item.data 31 | 32 | if self.interaction_callback: 33 | self.interaction_callback(caption, self.sender) 34 | 35 | def callback(self, callback, sender): 36 | self.interaction_callback = callback 37 | self.sender = sender 38 | self._value_changed(self.currentIndex()) 39 | -------------------------------------------------------------------------------- /guibedos/declarative_form/widgets/datetimeedit.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | from Qt import QtWidgets 3 | 4 | 5 | class DateTimeEdit(QtWidgets.QDateTimeEdit): 6 | 7 | def __init__(self, property_, parent=None): 8 | QtWidgets.QDateTimeEdit.__init__(self, parent) 9 | self.property_ = property_ 10 | self.setDateTime(datetime.fromtimestamp(self.property_.value)) 11 | self.setDisplayFormat("yyyy'-'MM'-'dd' 'hh':'mm") 12 | self.setCalendarPopup(True) 13 | self.clearMaximumDateTime() 14 | self.clearMinimumDateTime() 15 | self.dateTimeChanged.connect(self._value_changed) 16 | 17 | def _value_changed(self, value): 18 | self.property_.value = value.toTime_t() 19 | if not self.property_.is_valid(): 20 | self.setStyleSheet("background-color: red") 21 | else: 22 | self.setStyleSheet("") 23 | -------------------------------------------------------------------------------- /guibedos/declarative_form/widgets/filepath_widget.py: -------------------------------------------------------------------------------- 1 | import os 2 | from Qt import QtWidgets 3 | 4 | 5 | class FileDialog(QtWidgets.QFileDialog): 6 | def __init__(self, *args): 7 | QtWidgets.QFileDialog.__init__(self, *args) 8 | self.setOption(self.DontUseNativeDialog, False) 9 | self.setFileMode(self.ExistingFiles) 10 | 11 | self.selected_files = list() 12 | 13 | self.open_button = self._hack_button() 14 | self.tree = self.findChild(QtWidgets.QTreeView) 15 | 16 | def _hack_button(self): 17 | buttons = self.findChildren(QtWidgets.QPushButton) 18 | open_button = [x for x in buttons if 'open' in str(x.text()).lower()][0] 19 | open_button.clicked.disconnect() 20 | open_button.clicked.connect(self.openClicked) 21 | return open_button 22 | 23 | def openClicked(self): 24 | indexes = self.tree.selectionModel().selectedIndexes() 25 | files = [] 26 | for index in indexes: 27 | if index.column() == 0: 28 | files.append(os.path.normpath(os.path.join( 29 | str(self.directory().absolutePath()), 30 | str(index.data())) 31 | )) 32 | self.selected_files = files 33 | self.close() 34 | 35 | 36 | class FilepathWidget(QtWidgets.QWidget): 37 | 38 | def __init__(self, property_, parent=None): 39 | QtWidgets.QWidget.__init__(self, parent) 40 | 41 | self.text = QtWidgets.QLineEdit() 42 | self.browse = QtWidgets.QPushButton('Browse ...') 43 | self.browse.clicked.connect(self._browse_clicked) 44 | 45 | layout = QtWidgets.QHBoxLayout(self) 46 | layout.setContentsMargins(0, 0, 0, 0) 47 | layout.addWidget(self.text) 48 | layout.addWidget(self.browse) 49 | 50 | self.property_ = property_ 51 | self.text.textChanged.connect(self._value_changed) 52 | self.text.setText(property_.value) 53 | 54 | def _browse_clicked(self): 55 | dialog = FileDialog() 56 | dialog.exec_() 57 | 58 | selected = dialog.selectedFiles() 59 | if selected: 60 | self.text.setText(selected[0]) 61 | self._value_changed(selected[0]) 62 | return 63 | 64 | selected = dialog.selectedFiles() 65 | if selected: 66 | self.text.setText(selected[0]) 67 | self._value_changed(selected[0]) 68 | 69 | def _value_changed(self, value): 70 | self.property_.value = value 71 | if not self.property_.is_valid(): 72 | self.text.setStyleSheet("background-color: red") 73 | else: 74 | self.text.setStyleSheet("") 75 | -------------------------------------------------------------------------------- /guibedos/declarative_form/widgets/label_widget.py: -------------------------------------------------------------------------------- 1 | from Qt import QtWidgets 2 | 3 | 4 | class LabelWidget(QtWidgets.QLabel): 5 | 6 | def __init__(self, property_, parent=None): 7 | QtWidgets.QLabel.__init__(self, property_.caption, parent) 8 | self.property_ = property_ 9 | -------------------------------------------------------------------------------- /guibedos/declarative_form/widgets/lineedit.py: -------------------------------------------------------------------------------- 1 | from Qt import QtWidgets 2 | 3 | 4 | class LineEdit(QtWidgets.QLineEdit): 5 | 6 | def __init__(self, property_, parent=None): 7 | QtWidgets.QLineEdit.__init__(self, parent) 8 | self.property_ = property_ 9 | self.setText(property_.value) 10 | 11 | self.textChanged.connect(self._value_changed) 12 | 13 | def _value_changed(self, value): 14 | self.property_.value = value 15 | if not self.property_.is_valid(): 16 | self.setStyleSheet("background-color: red") 17 | else: 18 | self.setStyleSheet("") 19 | -------------------------------------------------------------------------------- /guibedos/declarative_form/widgets/listwidget.py: -------------------------------------------------------------------------------- 1 | from guibedos.widgets import TagBar 2 | 3 | 4 | class ListWidget(TagBar): 5 | 6 | def __init__(self, property_, parent=None): 7 | TagBar.__init__(self, parent) 8 | self.property_ = property_ 9 | 10 | self.set_tags(self.property_.value) 11 | self.tags_changed.connect(self._value_changed) 12 | 13 | def _value_changed(self, tags): 14 | self.property_.value = tags 15 | -------------------------------------------------------------------------------- /guibedos/declarative_form/widgets/spinbox.py: -------------------------------------------------------------------------------- 1 | from Qt import QtWidgets 2 | 3 | _MAX = 2147483647 4 | 5 | 6 | class SpinBox(QtWidgets.QSpinBox): 7 | 8 | def __init__(self, property_, parent=None): 9 | QtWidgets.QSpinBox.__init__(self, parent) 10 | self.property_ = property_ 11 | 12 | if property_ is not None \ 13 | and property_.range is not None \ 14 | and property_.range[0] is not None: 15 | self.setMinimum(property_.range[0]) 16 | else: 17 | self.setMinimum(-_MAX) 18 | 19 | if property_ is not None \ 20 | and property_.range is not None \ 21 | and property_.range[1] is not None: 22 | self.setMaximum(property_.range[1]) 23 | else: 24 | self.setMaximum(_MAX) 25 | 26 | self.setValue(property_.value) 27 | 28 | self.valueChanged.connect(self._value_changed) 29 | 30 | def _value_changed(self, value): 31 | self.property_.value = value 32 | -------------------------------------------------------------------------------- /guibedos/error_reporting/__init__.py: -------------------------------------------------------------------------------- 1 | import functools 2 | import traceback 3 | 4 | from Qt.QtGui import QFontDatabase, QFont 5 | from Qt.QtWidgets import QDialog, QPlainTextEdit, QLabel, QGridLayout,QApplication, QStyle, QPushButton 6 | 7 | from .highlighter import TracebackHighlighter 8 | 9 | 10 | ICON_SIZE = 48 11 | 12 | # http://srinikom.github.io/pyside-docs/PySide/QtGui/QStyle.html#PySide.QtGui.PySide.QtGui.QStyle.StandardPixmap 13 | 14 | 15 | class _ReportingWindow(QDialog): 16 | def __init__(self, name, report, parent=None): 17 | QDialog.__init__(self, parent) 18 | icon = self.style().standardIcon(QStyle.SP_MessageBoxCritical) 19 | 20 | self.setWindowTitle('Error reporting') 21 | self.setWindowIcon(icon) 22 | 23 | try: 24 | font = QFontDatabase().systemFont(QFontDatabase.FixedFont) 25 | except AttributeError as e: 26 | font = QFont() 27 | font.setStyleHint(QFont.TypeWriter) 28 | 29 | self.text = QPlainTextEdit() 30 | self.text.setFont(font) 31 | self.text.setReadOnly(True) 32 | self.text.setLineWrapMode(QPlainTextEdit.NoWrap) 33 | self.text.setPlainText(report) 34 | TracebackHighlighter(self.text.document()) 35 | 36 | icon_label = QLabel() 37 | icon_label.setPixmap(icon.pixmap(ICON_SIZE, ICON_SIZE)) 38 | 39 | label = QLabel("{} error !".format(name)) 40 | label.setFont(QFont('default', pointSize=14)) 41 | 42 | button_copy = QPushButton('Copy to clipboard') 43 | button_copy.clicked.connect(self._copy) 44 | 45 | layout = QGridLayout(self) 46 | layout.addWidget(icon_label, 0, 0) 47 | layout.addWidget(label, 0, 1) 48 | layout.addWidget(self.text, 1, 0, 1, 2) 49 | layout.addWidget(button_copy, 2, 0, 1, 2) 50 | layout.setColumnStretch(1, 100) 51 | 52 | self.setModal(True) 53 | self.resize(600, 400) 54 | 55 | def _copy(self): 56 | clipboard = QApplication.clipboard() 57 | clipboard.setText('```\n' + self.text.toPlainText() + '\n```') 58 | 59 | 60 | def error_reported(name): 61 | 62 | def decorator(func): 63 | @functools.wraps(func) 64 | def wrapper(*args, **kwargs): 65 | 66 | try: 67 | return func(*args, **kwargs) 68 | except Exception as e: 69 | window = _ReportingWindow( 70 | name, 71 | traceback.format_exc(), 72 | parent=QApplication.activeWindow() 73 | ) 74 | window.show() 75 | 76 | raise 77 | 78 | return wrapper 79 | return decorator 80 | -------------------------------------------------------------------------------- /guibedos/error_reporting/highlighter.py: -------------------------------------------------------------------------------- 1 | import re 2 | from Qt.QtCore import Qt 3 | from Qt.QtGui import QSyntaxHighlighter, QTextCharFormat, QFont 4 | 5 | 6 | LINE_FILE_RE = re.compile(r"^\s\s\S.+") 7 | LINE_FILE_FORMAT = QTextCharFormat() 8 | LINE_FILE_FORMAT.setForeground(Qt.lightGray) 9 | 10 | LINE_CODE_RE = re.compile(r"^\s\s\s\s\S.+") 11 | LINE_CODE_FORMAT = QTextCharFormat() 12 | LINE_CODE_FORMAT.setFontWeight(QFont.Bold) 13 | 14 | FILE_RE = re.compile(r"\"[^\"]+\"") 15 | FILE_FORMAT = QTextCharFormat() 16 | FILE_FORMAT.setFontItalic(True) 17 | FILE_FORMAT.setForeground(Qt.black) 18 | 19 | CALL_RE = re.compile(r", in ([^$]+)$") 20 | CALL_FORMAT = QTextCharFormat() 21 | CALL_FORMAT.setFontWeight(QFont.Bold) 22 | CALL_FORMAT.setForeground(Qt.magenta) 23 | 24 | LINE_RE = re.compile(r"line \d+") 25 | LINE_FORMAT = QTextCharFormat() 26 | LINE_FORMAT.setForeground(Qt.green) 27 | 28 | 29 | class TracebackHighlighter(QSyntaxHighlighter): 30 | RULES = { 31 | LINE_FILE_RE: LINE_FILE_FORMAT, 32 | LINE_CODE_RE: LINE_CODE_FORMAT, 33 | CALL_RE: CALL_FORMAT, 34 | LINE_RE: LINE_FORMAT 35 | } 36 | 37 | def __init__(self, parent=None): 38 | QSyntaxHighlighter.__init__(self, parent) 39 | 40 | def highlightBlock(self, text): 41 | for expression, style in self.RULES.items(): 42 | 43 | for found in expression.finditer(text): 44 | start, end = found.span() 45 | self.setFormat(start, end - start, style) 46 | -------------------------------------------------------------------------------- /guibedos/helpers.py: -------------------------------------------------------------------------------- 1 | from Qt import QtCore 2 | from Qt import QtWidgets 3 | 4 | 5 | class Hourglass: 6 | """ 7 | Context manager to freeze and show a hourglass 8 | 9 | ```` 10 | with Hourglass(self): 11 | # do lengthy stuff 12 | ```` 13 | """ 14 | 15 | def __init__(self, parent=None): 16 | if parent is None: 17 | parent = QtWidgets.QApplication.instance() 18 | self._parent = parent 19 | 20 | def __enter__(self): 21 | QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor) 22 | try: 23 | self._parent.setEnabled(False) 24 | except AttributeError: 25 | pass 26 | QtWidgets.QApplication.processEvents() 27 | 28 | def __exit__(self, exc_type, exc_val, exc_tb): 29 | try: 30 | self._parent.setEnabled(True) 31 | except AttributeError: 32 | pass 33 | QtWidgets.QApplication.restoreOverrideCursor() 34 | QtWidgets.QApplication.processEvents() 35 | 36 | 37 | def update_combo(combo, items, select=None): 38 | """ 39 | Clears and updates a QComboBox with given items, and tries to restore selection without emitting a signal 40 | 41 | !!! note 42 | If the previously selected item is not found among new items, nothing is selected and a signal is emitted 43 | 44 | :param combo: a QComboBox 45 | :param items: list of strings 46 | :param select: a string to be set as current selection 47 | """ 48 | if select is None: 49 | current = combo.currentText() 50 | else: 51 | current = select 52 | dont_emit = current in items + [''] 53 | 54 | combo.blockSignals(True) 55 | combo.clear() 56 | combo.addItems(items) 57 | 58 | if dont_emit: 59 | combo.setCurrentIndex(combo.findText(current)) 60 | combo.blockSignals(False) 61 | else: 62 | combo.blockSignals(False) 63 | combo.setCurrentIndex(combo.findText(current)) 64 | 65 | 66 | class WindowPosition: 67 | @staticmethod 68 | def restore(widget, data): 69 | if data['maximized']: 70 | widget.setWindowState(QtCore.Qt.WindowMaximized) 71 | else: 72 | geometry = QtCore.QRect() 73 | geometry.setCoords(*data['geometry']) 74 | widget.setGeometry(geometry) 75 | 76 | @staticmethod 77 | def save(widget): 78 | return { 79 | 'geometry': widget.geometry().getCoords(), 80 | 'maximized': bool(widget.windowState() & QtCore.Qt.WindowMaximized) 81 | } 82 | 83 | 84 | def clear_layout(layout): 85 | if layout is not None: 86 | while layout.count(): 87 | item = layout.takeAt(0) 88 | widget = item.widget() 89 | if widget is not None: 90 | widget.deleteLater() 91 | else: 92 | clear_layout(item.layout()) 93 | 94 | 95 | def cursor_line_number(text_lines, cursor_position): 96 | character_count = 0 97 | for line, text in enumerate(text_lines): 98 | character_count += len(text) + 1 99 | if cursor_position < character_count: 100 | return line 101 | 102 | return len(text_lines) 103 | 104 | 105 | def set_style_property(widget, value, property_name="style"): 106 | """ 107 | Refreshes a QWidget property then unpolishes/polishes it's style 108 | """ 109 | widget.setProperty(property_name, value); 110 | widget.style().unpolish(widget); 111 | widget.style().polish(widget); 112 | 113 | 114 | def load_stylesheet(widget, css_filepath): 115 | """ 116 | Loads given file contents then sets it as given widget stylesheet 117 | """ 118 | with open(css_filepath, 'r') as css_file: 119 | widget.setStyleSheet(css_file.read()) 120 | -------------------------------------------------------------------------------- /guibedos/messagebox/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/messagebox/__init__.py -------------------------------------------------------------------------------- /guibedos/messagebox/_widget.py: -------------------------------------------------------------------------------- 1 | from Qt import QtWidgets 2 | 3 | 4 | WARNING = QtWidgets.QMessageBox.Icon.Warning 5 | INFO = QtWidgets.QMessageBox.Icon.Information 6 | 7 | 8 | def make_box(message, title, icon): 9 | confirmation_box = QtWidgets.QMessageBox(QtWidgets.QApplication.topLevelWidgets()[0]) 10 | confirmation_box.setIcon(icon) 11 | confirmation_box.setWindowTitle(title) 12 | confirmation_box.setText(message) 13 | confirmation_box.setStandardButtons(QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel) 14 | 15 | result = confirmation_box.exec_() == QtWidgets.QMessageBox.Ok 16 | confirmation_box.deleteLater() 17 | 18 | return result 19 | -------------------------------------------------------------------------------- /guibedos/messagebox/before.py: -------------------------------------------------------------------------------- 1 | import functools 2 | 3 | from . import _widget 4 | 5 | 6 | def info(message, title="Information"): 7 | 8 | def decorator(func): 9 | @functools.wraps(func) 10 | def wrapper(*args, **kwargs): 11 | 12 | if _widget.make_box(message, title, _widget.INFO): 13 | return func(*args, **kwargs) 14 | 15 | return wrapper 16 | return decorator 17 | 18 | 19 | def warning(message, title="Warning !"): 20 | 21 | def decorator(func): 22 | @functools.wraps(func) 23 | def wrapper(*args, **kwargs): 24 | 25 | if _widget.make_box(message, title, _widget.WARNING): 26 | return func(*args, **kwargs) 27 | 28 | return wrapper 29 | return decorator 30 | -------------------------------------------------------------------------------- /guibedos/resources/images/Hmovetoolbar_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/Hmovetoolbar_dark.png -------------------------------------------------------------------------------- /guibedos/resources/images/Hmovetoolbar_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/Hmovetoolbar_light.png -------------------------------------------------------------------------------- /guibedos/resources/images/Hsepartoolbar_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/Hsepartoolbar_dark.png -------------------------------------------------------------------------------- /guibedos/resources/images/Hsepartoolbar_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/Hsepartoolbar_light.png -------------------------------------------------------------------------------- /guibedos/resources/images/Vmovetoolbar_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/Vmovetoolbar_dark.png -------------------------------------------------------------------------------- /guibedos/resources/images/Vmovetoolbar_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/Vmovetoolbar_light.png -------------------------------------------------------------------------------- /guibedos/resources/images/Vsepartoolbar_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/Vsepartoolbar_dark.png -------------------------------------------------------------------------------- /guibedos/resources/images/Vsepartoolbar_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/Vsepartoolbar_light.png -------------------------------------------------------------------------------- /guibedos/resources/images/background_mdi.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/background_mdi.png -------------------------------------------------------------------------------- /guibedos/resources/images/branch_closed_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/branch_closed_dark.png -------------------------------------------------------------------------------- /guibedos/resources/images/branch_closed_darker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/branch_closed_darker.png -------------------------------------------------------------------------------- /guibedos/resources/images/branch_end.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/branch_end.png -------------------------------------------------------------------------------- /guibedos/resources/images/branch_more.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/branch_more.png -------------------------------------------------------------------------------- /guibedos/resources/images/branch_open_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/branch_open_dark.png -------------------------------------------------------------------------------- /guibedos/resources/images/branch_open_darker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/branch_open_darker.png -------------------------------------------------------------------------------- /guibedos/resources/images/branch_vline.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/branch_vline.png -------------------------------------------------------------------------------- /guibedos/resources/images/checkbox_indeterminate_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/checkbox_indeterminate_light.png -------------------------------------------------------------------------------- /guibedos/resources/images/checkbox_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/checkbox_light.png -------------------------------------------------------------------------------- /guibedos/resources/images/close_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/close_dark.png -------------------------------------------------------------------------------- /guibedos/resources/images/close_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/close_light.png -------------------------------------------------------------------------------- /guibedos/resources/images/down_arrow_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/down_arrow_dark.png -------------------------------------------------------------------------------- /guibedos/resources/images/down_arrow_darker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/down_arrow_darker.png -------------------------------------------------------------------------------- /guibedos/resources/images/down_arrow_disabled_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/down_arrow_disabled_dark.png -------------------------------------------------------------------------------- /guibedos/resources/images/down_arrow_disabled_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/down_arrow_disabled_light.png -------------------------------------------------------------------------------- /guibedos/resources/images/down_arrow_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/down_arrow_light.png -------------------------------------------------------------------------------- /guibedos/resources/images/down_arrow_lighter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/down_arrow_lighter.png -------------------------------------------------------------------------------- /guibedos/resources/images/left_arrow_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/left_arrow_dark.png -------------------------------------------------------------------------------- /guibedos/resources/images/left_arrow_darker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/left_arrow_darker.png -------------------------------------------------------------------------------- /guibedos/resources/images/left_arrow_disabled_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/left_arrow_disabled_dark.png -------------------------------------------------------------------------------- /guibedos/resources/images/left_arrow_disabled_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/left_arrow_disabled_light.png -------------------------------------------------------------------------------- /guibedos/resources/images/left_arrow_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/left_arrow_light.png -------------------------------------------------------------------------------- /guibedos/resources/images/left_arrow_lighter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/left_arrow_lighter.png -------------------------------------------------------------------------------- /guibedos/resources/images/more_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/more_dark.png -------------------------------------------------------------------------------- /guibedos/resources/images/more_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/more_light.png -------------------------------------------------------------------------------- /guibedos/resources/images/radiobutton_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/radiobutton_light.png -------------------------------------------------------------------------------- /guibedos/resources/images/right_arrow_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/right_arrow_dark.png -------------------------------------------------------------------------------- /guibedos/resources/images/right_arrow_darker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/right_arrow_darker.png -------------------------------------------------------------------------------- /guibedos/resources/images/right_arrow_disabled_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/right_arrow_disabled_dark.png -------------------------------------------------------------------------------- /guibedos/resources/images/right_arrow_disabled_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/right_arrow_disabled_light.png -------------------------------------------------------------------------------- /guibedos/resources/images/right_arrow_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/right_arrow_light.png -------------------------------------------------------------------------------- /guibedos/resources/images/right_arrow_lighter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/right_arrow_lighter.png -------------------------------------------------------------------------------- /guibedos/resources/images/sizegrip_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/sizegrip_dark.png -------------------------------------------------------------------------------- /guibedos/resources/images/sizegrip_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/sizegrip_light.png -------------------------------------------------------------------------------- /guibedos/resources/images/splitter_horizontal_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/splitter_horizontal_dark.png -------------------------------------------------------------------------------- /guibedos/resources/images/splitter_horizontal_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/splitter_horizontal_light.png -------------------------------------------------------------------------------- /guibedos/resources/images/splitter_vertical_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/splitter_vertical_dark.png -------------------------------------------------------------------------------- /guibedos/resources/images/splitter_vertical_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/splitter_vertical_light.png -------------------------------------------------------------------------------- /guibedos/resources/images/transparent.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/transparent.png -------------------------------------------------------------------------------- /guibedos/resources/images/undock_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/undock_dark.png -------------------------------------------------------------------------------- /guibedos/resources/images/undock_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/undock_light.png -------------------------------------------------------------------------------- /guibedos/resources/images/up-down_arrow_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/up-down_arrow_dark.png -------------------------------------------------------------------------------- /guibedos/resources/images/up-down_arrow_darker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/up-down_arrow_darker.png -------------------------------------------------------------------------------- /guibedos/resources/images/up-down_arrow_disabled_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/up-down_arrow_disabled_dark.png -------------------------------------------------------------------------------- /guibedos/resources/images/up-down_arrow_disabled_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/up-down_arrow_disabled_light.png -------------------------------------------------------------------------------- /guibedos/resources/images/up-down_arrow_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/up-down_arrow_light.png -------------------------------------------------------------------------------- /guibedos/resources/images/up-down_arrow_lighter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/up-down_arrow_lighter.png -------------------------------------------------------------------------------- /guibedos/resources/images/up_arrow_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/up_arrow_dark.png -------------------------------------------------------------------------------- /guibedos/resources/images/up_arrow_darker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/up_arrow_darker.png -------------------------------------------------------------------------------- /guibedos/resources/images/up_arrow_disabled_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/up_arrow_disabled_dark.png -------------------------------------------------------------------------------- /guibedos/resources/images/up_arrow_disabled_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/up_arrow_disabled_light.png -------------------------------------------------------------------------------- /guibedos/resources/images/up_arrow_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/up_arrow_light.png -------------------------------------------------------------------------------- /guibedos/resources/images/up_arrow_lighter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/guibedos/resources/images/up_arrow_lighter.png -------------------------------------------------------------------------------- /guibedos/table/__init__.py: -------------------------------------------------------------------------------- 1 | from .row import Row 2 | from .row_table_model import RowTableModel 3 | from .row_table_widget import RowTableWidget 4 | -------------------------------------------------------------------------------- /guibedos/table/row.py: -------------------------------------------------------------------------------- 1 | from Qt.QtGui import QColor, QPixmap 2 | 3 | 4 | class Row: 5 | """ 6 | Holds data for a table row 7 | 8 | Each cell is a list of list as of this schema 9 | 10 | ```text 11 | [Display role, foreground color, background color] 12 | ``` 13 | 14 | Color are a 0-255 RGB/RGBA tuple `(0, 255, 128)` or `(0, 255, 128, 128)` 15 | 16 | :cells: list of tuples 17 | :data: user data, not displayed 18 | """ 19 | DISPLAY = 0 20 | BACKGROUND = 1 21 | FOREGROUND = 2 22 | SORT = 3 23 | 24 | def __init__(self, cells, data, index=-1): 25 | self.index = index 26 | self.data = data 27 | self.cells = cells 28 | self.search_cache = "" 29 | 30 | def copy(self, new_index=None): 31 | if new_index is None: 32 | new_index = self.index 33 | 34 | return Row(self.cells, self.data, new_index) 35 | 36 | def build_cache(self): 37 | self.search_cache = " ".join('{}'.format(cell[Row.DISPLAY]).lower() for cell in self.cells) 38 | self.cells = [self._cell_cache(cell) for cell in self.cells] 39 | 40 | @staticmethod 41 | def _cell_cache(cell): 42 | display = cell[Row.DISPLAY] 43 | foreground = Row._ensure_qcolor(cell[Row.FOREGROUND]) 44 | background = Row._ensure_qcolor(cell[Row.BACKGROUND]) 45 | sort = cell[Row.SORT] if cell[Row.SORT] is not None else 0 46 | return [display, background, foreground, sort] 47 | 48 | @staticmethod 49 | def _ensure_qcolor(value): 50 | if not value: 51 | return None 52 | 53 | if isinstance(value, tuple): 54 | return QColor(*value) 55 | 56 | elif isinstance(value, str): 57 | return QPixmap(value) 58 | 59 | return value 60 | 61 | def __repr__(self): 62 | return "".format( 63 | self.index, 64 | self.cells 65 | ) 66 | -------------------------------------------------------------------------------- /guibedos/table/row_background_processor.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import traceback 3 | from Qt.QtCore import Signal, QThread 4 | from guibedos.threading import Threadable 5 | 6 | 7 | class RowBackgroundProcessor(Threadable): 8 | SLEEP_MS = 40 9 | row_processed = Signal(object) 10 | 11 | def __init__(self, parent=None): 12 | Threadable.__init__(self, parent) 13 | self._rows = list() 14 | self._process_callback = None 15 | self._processed_row_indexes = list() 16 | 17 | @property 18 | def has_callback(self): 19 | return self._process_callback is not None 20 | 21 | def set_callback(self, callback): 22 | self._process_callback = callback 23 | 24 | def reset(self): 25 | self._rows = list() 26 | self._processed_row_indexes = list() 27 | 28 | def add_row(self, row): 29 | self._rows.append(row) 30 | 31 | def loop_kick(self): 32 | if not self._rows: 33 | QThread.msleep(self.DEFAULT_SLEEP_MS) 34 | return 35 | 36 | row = self._rows.pop() 37 | if row.index not in self._processed_row_indexes: 38 | try: 39 | new_row = self._process_callback(row) 40 | except Exception as e: 41 | traceback.print_exception(*sys.exc_info()) 42 | 43 | new_row.build_cache() 44 | 45 | self.row_processed.emit(new_row) 46 | self._processed_row_indexes.append(new_row.index) 47 | 48 | self._cleanup(row) 49 | 50 | QThread.msleep(self.SLEEP_MS) 51 | 52 | def _cleanup(self, row): 53 | while True: 54 | try: 55 | self._rows.remove(row) 56 | except ValueError: 57 | break 58 | -------------------------------------------------------------------------------- /guibedos/table/row_model_all.py: -------------------------------------------------------------------------------- 1 | from Qt.QtCore import QObject, Signal, QCoreApplication 2 | from guibedos.threading import move_to_new_thread 3 | from .row_background_processor import RowBackgroundProcessor 4 | 5 | 6 | class RowAllModel(QObject): 7 | """ 8 | This class holds all the rows set with `set_rows` and ensure background processing if a callback is provided 9 | """ 10 | row_updated = Signal(object) 11 | progress_updated = Signal(int) 12 | 13 | def __init__(self, background_processing_callback=None, parent=None): 14 | QObject.__init__(self, parent) 15 | self.rows = list() 16 | self.row_count = 0 17 | 18 | self._processed_row_indexes = list() 19 | self._background_processor = RowBackgroundProcessor() 20 | self._background_thread = move_to_new_thread( 21 | self._background_processor, 22 | signals=[ 23 | (self._background_processor.row_processed, self.update_row) 24 | ] 25 | ) 26 | self.set_background_processing_callback(background_processing_callback) 27 | 28 | def reset_background_processing(self): 29 | self._background_processor.reset() 30 | self._processed_row_indexes = list() 31 | 32 | def set_background_processing_callback(self, callback): 33 | self._background_processor.set_callback(callback) 34 | 35 | @property 36 | def has_background_callback(self): 37 | return self._background_processor.has_callback 38 | 39 | def start(self): 40 | self._background_thread.start() 41 | QCoreApplication.instance().aboutToQuit.connect(self.stop) 42 | 43 | def stop(self): 44 | self._background_processor.stop() 45 | 46 | def add_row_for_processing(self, row): 47 | if self.has_background_callback and row.index not in self._processed_row_indexes: 48 | self._background_processor.add_row(row) 49 | 50 | def update_row(self, row): 51 | self._processed_row_indexes.append(row.index) 52 | self.rows[row.index] = row 53 | self.row_updated.emit(row) 54 | self.progress_updated.emit(len(self._processed_row_indexes)) 55 | 56 | def set_rows(self, rows): 57 | self.rows = list() 58 | self._processed_row_indexes = list() 59 | self._background_processor.reset() 60 | 61 | for index, row in enumerate(rows): 62 | new_row = row.copy(new_index=index) 63 | new_row.build_cache() 64 | self.rows.append(new_row) 65 | if self._background_processor.has_callback: 66 | self._background_processor.add_row(new_row) 67 | 68 | self.row_count = len(self.rows) 69 | -------------------------------------------------------------------------------- /guibedos/table/row_table_model.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | from Qt.QtCore import Qt, QAbstractTableModel, Signal 3 | from .row import Row 4 | from .row_model_all import RowAllModel 5 | 6 | 7 | class RowTableModel(QAbstractTableModel): 8 | """ 9 | This is the actual `QAbstractTableModel` that wraps its `AllRowTableModel` member and allows fast text search 10 | """ 11 | progress_updated = Signal(int) 12 | 13 | _ROLES = { 14 | Qt.DisplayRole: Row.DISPLAY, 15 | Qt.BackgroundRole: Row.BACKGROUND, 16 | Qt.ForegroundRole: Row.FOREGROUND 17 | } 18 | 19 | def __init__(self, background_processing_callback=None, parent=None): 20 | QAbstractTableModel.__init__(self, parent) 21 | self._model_all = RowAllModel(background_processing_callback) 22 | self._model_all.row_updated.connect(self._row_updated) 23 | self._model_all.progress_updated.connect(self.progress_updated) 24 | self._rows = list() 25 | self._row_count = 0 26 | self._headers = list() 27 | self._column_count = 0 28 | self._search_items_text = [] 29 | self._search_items_counters = [] 30 | self._search_indexes = dict() 31 | self._sort_column = None 32 | self._sort_reversed = False 33 | self._counters = dict() 34 | 35 | @property 36 | def total_row_count(self): 37 | return self._model_all.row_count 38 | 39 | def reset_background_processing(self): 40 | self._model_all.reset_background_processing() 41 | 42 | def set_background_processing_callback(self, callback): 43 | self._model_all.set_background_processing_callback(callback) 44 | 45 | @property 46 | def has_background_callback(self): 47 | return self._model_all.has_background_callback 48 | 49 | def start(self): 50 | self._model_all.start() 51 | 52 | def stop(self): 53 | self._model_all.stop() 54 | 55 | def set_headers(self, headers): 56 | if headers: 57 | self._headers = headers 58 | self._column_count = len(self._headers) 59 | else: 60 | self._headers = list() 61 | self._column_count = 0 62 | 63 | def set_rows(self, rows): 64 | self._model_all.set_rows(rows) 65 | self.perform_search() 66 | 67 | def set_search_text(self, text): 68 | self._search_items_text = text.lower().split() 69 | self.perform_search() 70 | 71 | def set_search_counters(self, entries): 72 | self._search_items_counters = [entry.lower() for entry in entries] 73 | self.perform_search() 74 | 75 | def reset_counters(self): 76 | for _, counter in self._counters.values(): 77 | counter.clear() 78 | 79 | def perform_search(self): 80 | self.beginResetModel() 81 | self.reset_counters() 82 | self._rows = list() 83 | 84 | search = self._search_items_text + self._search_items_counters 85 | for row in self._model_all.rows: 86 | if any(item not in row.search_cache for item in search): 87 | continue 88 | 89 | for index, counter in self._counters.items(): 90 | counter[1].update([row.cells[index][Row.DISPLAY]]) 91 | 92 | self._rows.append(row) 93 | 94 | self._sort() 95 | 96 | self._row_count = len(self._rows) 97 | self.endResetModel() 98 | 99 | @property 100 | def counters(self): 101 | return dict(self._counters.values()) 102 | 103 | def register_counters(self, column_names): 104 | self._counters = dict() 105 | column_indexes = [self._headers.index(column) for column in column_names] 106 | for column_index in column_indexes: 107 | self._counters[column_index] = self._headers[column_index], Counter() 108 | 109 | def _row_updated(self, row): 110 | index = self._search_indexes.get(row.index, -1) 111 | self.dataChanged.emit( 112 | self.index(0, index), 113 | self.index(self._column_count, index) 114 | ) 115 | 116 | @property 117 | def progress_max(self): 118 | return self._model_all.row_count 119 | 120 | def rowCount(self, parent=None): 121 | return self._row_count 122 | 123 | def columnCount(self, parent=None): 124 | return self._column_count 125 | 126 | def headerData(self, section, orientation=Qt.Horizontal, role=Qt.DisplayRole): 127 | if role == Qt.DisplayRole and orientation == Qt.Horizontal: 128 | return self._headers[section] 129 | 130 | def data(self, index, role=Qt.DisplayRole): 131 | row_index = index.row() 132 | column_index = index.column() 133 | 134 | if role == Qt.DisplayRole: 135 | self._model_all.add_row_for_processing(self._rows[row_index]) 136 | 137 | elif role == Qt.UserRole: 138 | return self._rows[row_index] 139 | 140 | data_type = self._ROLES.get(role) 141 | if data_type is None: 142 | return 143 | 144 | return self._rows[row_index].cells[column_index][data_type] 145 | 146 | def _build_search_indexes(self): 147 | self._search_indexes = dict() 148 | for index, row in enumerate(self._rows): 149 | self._search_indexes[row.index] = index 150 | 151 | def _sort(self): 152 | if self._sort_column is None: 153 | return 154 | 155 | def sort(row): 156 | return row.cells[self._sort_column][Row.SORT] 157 | 158 | self._rows = sorted(self._rows, key=sort, reverse=self._sort_reversed) 159 | self._build_search_indexes() 160 | 161 | def sort(self, column, order=Qt.AscendingOrder): 162 | self.layoutAboutToBeChanged.emit() 163 | self._sort_column = column 164 | self._sort_reversed = order == Qt.AscendingOrder 165 | self._sort() 166 | self.layoutChanged.emit() 167 | -------------------------------------------------------------------------------- /guibedos/table/row_table_view.py: -------------------------------------------------------------------------------- 1 | from Qt.QtCore import Qt, QMargins 2 | from Qt.QtWidgets import QTableView, QAbstractItemView, QStyledItemDelegate 3 | from .row_table_model import RowTableModel 4 | 5 | 6 | CELL_PADDING = 8 7 | 8 | 9 | class CellDelegate(QStyledItemDelegate): 10 | def sizeHint(self, option, index): 11 | return QStyledItemDelegate.sizeHint(self, option, index).grownBy( 12 | QMargins(CELL_PADDING, CELL_PADDING, CELL_PADDING, CELL_PADDING 13 | )) 14 | 15 | 16 | class RowTableView(QTableView): 17 | 18 | def __init__(self, 19 | auto_resize=False, 20 | single_row_select=True, 21 | context_menu_callback=None, 22 | last_column_stretch=False, 23 | parent=None 24 | ): 25 | QTableView.__init__(self, parent) 26 | self.setShowGrid(False) 27 | self.setAlternatingRowColors(True) 28 | self.setSortingEnabled(True) 29 | self.setAttribute(Qt.WA_StyledBackground, True) 30 | self.setSelectionMode( 31 | QAbstractItemView.SingleSelection if single_row_select 32 | else QAbstractItemView.ExtendedSelection 33 | ) 34 | self.setSelectionBehavior(QAbstractItemView.SelectRows) 35 | self.horizontalHeader().setDefaultAlignment(Qt.AlignCenter) 36 | self.horizontalHeader().setStretchLastSection(last_column_stretch) 37 | self.verticalHeader().hide() 38 | self.setContextMenuPolicy(Qt.CustomContextMenu) 39 | self.setHorizontalScrollMode(QTableView.ScrollPerPixel) 40 | self.setItemDelegate(CellDelegate()) 41 | 42 | self.verticalHeader().setDefaultSectionSize(self.verticalHeader().defaultSectionSize() + CELL_PADDING) 43 | 44 | if context_menu_callback is not None: 45 | self.customContextMenuRequested.connect(context_menu_callback) 46 | 47 | self._auto_resize = auto_resize 48 | self._single_row_select = single_row_select 49 | self._model = None 50 | 51 | def setModel(self, model): 52 | if not isinstance(model, RowTableModel): 53 | raise TypeError("Given model must be a RowTableModel") 54 | 55 | QTableView.setModel(self, model) 56 | self._model = model 57 | 58 | if self._auto_resize: 59 | self._model.modelReset.connect(self.resizeColumnsToContents) 60 | self.resizeColumnsToContents() 61 | self.resizeRowsToContents() 62 | -------------------------------------------------------------------------------- /guibedos/table/row_table_widget.py: -------------------------------------------------------------------------------- 1 | """ 2 | This demonstrates the usage of a QTableView associated width a QAbstractTableModel 3 | 4 | Presented data is organized in rows 5 | """ 6 | from Qt.QtCore import Signal, Qt 7 | from Qt.QtWidgets import QGridLayout, QLineEdit, QProgressBar, QPushButton, QLabel, QFrame 8 | from .row_table_view import RowTableView 9 | from guibedos.widgets import Counters 10 | from guibedos.helpers import Hourglass 11 | 12 | 13 | SEARCHBAR_HEIGHT = 24 14 | STATUS_LABEL_WIDTH = 150 15 | STATUS_LABEL_MESSAGE = "{} rows ({} total)" 16 | 17 | 18 | class RowTableWidget(QFrame): 19 | double_clicked = Signal(object) 20 | 21 | def __init__(self, 22 | auto_resize=False, 23 | single_row_select=True, 24 | context_menu_callback=None, 25 | last_column_stretch=True, 26 | has_counters=False, 27 | parent=None 28 | ): 29 | QFrame.__init__(self, parent) 30 | self._has_counters = has_counters 31 | 32 | self.model = None 33 | 34 | self.table_view = RowTableView(auto_resize, single_row_select, context_menu_callback, last_column_stretch) 35 | self.table_view.doubleClicked.connect(self._double_clicked) 36 | 37 | if has_counters: 38 | self.counters = Counters() 39 | self.counters.button_clicked.connect(self._counter_clicked) 40 | 41 | self.search_bar = QLineEdit() 42 | self.search_bar.setFixedHeight(SEARCHBAR_HEIGHT) 43 | self.search_bar.textChanged.connect(self.set_search_text) 44 | self.search_bar.setToolTip("Search bar") 45 | 46 | self.auto_size_button = QPushButton('<>') 47 | self.auto_size_button.setFixedSize(SEARCHBAR_HEIGHT, SEARCHBAR_HEIGHT) 48 | self.auto_size_button.clicked.connect(self._auto_size_clicked) 49 | self.auto_size_button.setToolTip("Auto size") 50 | 51 | self.status_label = QLabel(STATUS_LABEL_MESSAGE.format(0, 0)) 52 | self.status_label.setFixedWidth(STATUS_LABEL_WIDTH) 53 | 54 | self.progress_bar = QProgressBar() 55 | self.progress_bar.setFormat('') 56 | 57 | layout = QGridLayout() 58 | 59 | layout.addWidget(self.search_bar, 0, 0, 1, 3) 60 | layout.addWidget(self.auto_size_button, 0, 3) 61 | if has_counters: 62 | layout.addWidget(self.counters, 1, 0, 1, 2) 63 | layout.addWidget(self.table_view, 1, 2, 1, 2) 64 | else: 65 | layout.addWidget(self.table_view, 1, 0, 1, 4) 66 | layout.addWidget(self.status_label, 2, 0) 67 | layout.addWidget(self.progress_bar, 2, 1, 1, 3) 68 | layout.setColumnStretch(2, 100) 69 | 70 | self.setLayout(layout) 71 | 72 | def set_model(self, model): 73 | self.model = model 74 | self.table_view.setModel(model) 75 | 76 | model.modelReset.connect(self._set_progress_maximum) 77 | model.modelReset.connect(self._update_status) 78 | if self._has_counters: 79 | model.modelReset.connect(self._update_counters) 80 | self._update_counters() 81 | model.progress_updated.connect(self._update_progress) 82 | 83 | self._set_progress_maximum() 84 | self._update_status() 85 | self.progress_bar.setVisible(model.has_background_callback) 86 | 87 | @property 88 | def selected_rows(self): 89 | return [self.model.data(index, Qt.UserRole) for index 90 | in self.table_view.selectionModel().selectedIndexes() if index.column() == 0] 91 | 92 | @property 93 | def search_text(self): 94 | return self.search_bar.text() 95 | 96 | def set_search_text(self, text): 97 | self.search_bar.blockSignals(True) 98 | self.search_bar.setText(text) 99 | self.search_bar.blockSignals(False) 100 | self.model.set_search_text(text) 101 | 102 | def _set_progress_maximum(self): 103 | self.progress_bar.setMaximum(self.model.progress_max) # do better ? 104 | 105 | def _update_progress(self, value): 106 | self.progress_bar.setValue(value) 107 | 108 | def _update_status(self): 109 | self.status_label.setText(STATUS_LABEL_MESSAGE.format( 110 | self.model.rowCount(), self.model.total_row_count 111 | )) 112 | 113 | def _counter_clicked(self, entry, checked_buttons): 114 | entries = [entry for entry, active in checked_buttons.items() if active] 115 | self.model.set_search_counters(entries) 116 | 117 | def _update_counters(self): 118 | self.counters.set(self.model.counters) 119 | 120 | def _auto_size_clicked(self): 121 | with Hourglass(): 122 | self.table_view.resizeColumnsToContents() 123 | 124 | def _double_clicked(self, index): 125 | row = self.model.data(index, Qt.UserRole) 126 | self.double_clicked.emit(row) 127 | 128 | def state(self): 129 | header_sizes = list() 130 | header = self.table_view.horizontalHeader() 131 | for section_index in range(header.count()): 132 | header_sizes.append(header.sectionSize(section_index)) 133 | 134 | return { 135 | 'header_sizes': header_sizes, 136 | 'search_text': self.search_bar.text() 137 | } 138 | 139 | def load_state(self, state): 140 | header = self.table_view.horizontalHeader() 141 | for section_index, size in enumerate(state['header_sizes']): 142 | header.resizeSection(section_index, size) 143 | 144 | self.search_bar.setText(state['search_text']) 145 | -------------------------------------------------------------------------------- /guibedos/threading.py: -------------------------------------------------------------------------------- 1 | from Qt import QtCore 2 | 3 | 4 | class Threadable(QtCore.QObject): 5 | """ 6 | Implement loop_kick() or exec_() 7 | 8 | To be used with move_to_new_thread() 9 | """ 10 | DEFAULT_SLEEP_MS = 100 11 | finished = QtCore.Signal() 12 | stopped = QtCore.Signal() 13 | 14 | def __init__(self, parent=None): 15 | QtCore.QObject.__init__(self, parent) 16 | self._running = False 17 | 18 | def stop(self): 19 | self._running = False 20 | self.stopped.emit() 21 | 22 | def loop_kick(self): 23 | QtCore.QThread.msleep(self.DEFAULT_SLEEP) 24 | 25 | def exec_(self): 26 | self._running = True 27 | while self._running: 28 | self.loop_kick() 29 | 30 | self.finished.emit() 31 | 32 | 33 | def move_to_new_thread(threadable, signals=list()): 34 | """ 35 | Creates a new `QThread`. Attaches the given instance of `Threadable` to it 36 | 37 | Give a list of (source, target) signals to be connected if needed 38 | 39 | Returns the new `QThread` instance 40 | """ 41 | thread = QtCore.QThread() 42 | thread.started.connect(threadable.exec_) 43 | 44 | for source, target in signals: 45 | source.connect(target) 46 | 47 | threadable.stopped.connect(thread.quit) 48 | threadable.stopped.connect(thread.wait) 49 | threadable.finished.connect(thread.quit) 50 | threadable.finished.connect(thread.wait) 51 | 52 | threadable.moveToThread(thread) 53 | 54 | return thread 55 | -------------------------------------------------------------------------------- /guibedos/use_case.py: -------------------------------------------------------------------------------- 1 | from .analytics import analyzed 2 | from .error_reporting import error_reported 3 | 4 | 5 | def use_case(name): 6 | """ 7 | Composes the `@analytics.analyzed` and `@error_reporting.error_reported` decorators 8 | 9 | :param name: Name that will be reported in logs and error reporting windows 10 | """ 11 | def decorator(func): 12 | return error_reported(name)(analyzed(name)(func)) 13 | return decorator 14 | -------------------------------------------------------------------------------- /guibedos/widgets/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Helper widgets for Qt bindings 3 | """ 4 | from .tag_bar import TagBar 5 | from .counters import Counters 6 | from .flow_layout import FlowLayout 7 | -------------------------------------------------------------------------------- /guibedos/widgets/counters.py: -------------------------------------------------------------------------------- 1 | from Qt.QtCore import Qt, Signal 2 | from Qt.QtWidgets import QWidget, QScrollArea, QPushButton, QVBoxLayout, QLabel 3 | from guibedos.helpers import clear_layout 4 | from guibedos.constants import PROPERTY_SIDE_STROKED 5 | 6 | 7 | class Counters(QScrollArea): 8 | button_clicked = Signal(object, object) 9 | SPACING = 2 10 | 11 | def __init__(self, parent=None): 12 | QScrollArea.__init__(self, parent) 13 | self.setWidgetResizable(True) 14 | self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) 15 | self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) 16 | 17 | self._layout = QVBoxLayout() 18 | self._layout.setContentsMargins(0, 0, 0, 0) 19 | self._layout.setSpacing(Counters.SPACING) 20 | 21 | widget = QWidget() 22 | widget.setLayout(self._layout) 23 | self.setWidget(widget) 24 | 25 | self.setFixedWidth(200) 26 | self.checked_buttons = dict() 27 | 28 | def set(self, counters): 29 | previous_buttons = self.checked_buttons.copy() 30 | self.clear() 31 | 32 | for column, counter in counters.items(): 33 | for entry, value in counter.items(): 34 | checked = previous_buttons.get(entry, False) 35 | self.checked_buttons[entry] = checked 36 | 37 | button = QPushButton('{} {}'.format(entry, value)) 38 | button.setProperty(PROPERTY_SIDE_STROKED, checked) 39 | button.clicked.connect(self._clicked) 40 | self._layout.addWidget(button) 41 | 42 | self._layout.addWidget(QLabel()) 43 | 44 | self._layout.addWidget(QWidget()) 45 | self._layout.setStretch(self._layout.count() - 1, 100) 46 | 47 | def clear(self): 48 | clear_layout(self._layout) 49 | self.checked_buttons = dict() 50 | 51 | def _clicked(self): 52 | button = self.sender() 53 | checked = not button.property(PROPERTY_SIDE_STROKED) 54 | 55 | entry = button.text().split()[0] 56 | self.checked_buttons[entry] = checked 57 | 58 | button.setProperty(PROPERTY_SIDE_STROKED, checked) 59 | 60 | self.button_clicked.emit(entry, self.checked_buttons) 61 | -------------------------------------------------------------------------------- /guibedos/widgets/flow_layout.py: -------------------------------------------------------------------------------- 1 | """ 2 | Flow Layout 3 | 4 | Presents in 2D a 1D list of Widgets 5 | 6 | Adapted from https://github.com/PySide/Examples/blob/master/examples/layouts/flowlayout.py 7 | 8 | This file is licensed under GPLv2 9 | """ 10 | from Qt import QtCore 11 | from Qt import QtWidgets 12 | 13 | 14 | class FlowLayout(QtWidgets.QLayout): 15 | def __init__(self, parent=None, margin=0, spacing=-1, expand_last=(False, False)): 16 | QtWidgets.QLayout.__init__(self, parent) 17 | self.item_list = [] 18 | self._expand_h = expand_last[0] 19 | self._expand_v = expand_last[1] 20 | self._expand_last = expand_last[0] or expand_last[1] 21 | 22 | def __del__(self): 23 | item = self.takeAt(0) 24 | while item: 25 | item = self.takeAt(0) 26 | 27 | def addItem(self, item): 28 | self.item_list.append(item) 29 | 30 | def count(self): 31 | return len(self.item_list) 32 | 33 | def insertWidget(self, index, widget): 34 | self.addWidget(widget) 35 | self.item_list.insert(index, self.item_list.pop(-1)) 36 | 37 | def itemAt(self, index): 38 | if index >= 0 and index < len(self.item_list): 39 | return self.item_list[index] 40 | return None 41 | 42 | def takeAt(self, index): 43 | if index >= 0 and index < len(self.item_list): 44 | return self.item_list.pop(index) 45 | 46 | return None 47 | 48 | def removeAt(self, index): 49 | item = self.takeAt(index) 50 | if item is None: 51 | return None 52 | 53 | item.widget().setParent(None) 54 | item.widget().deleteLater() 55 | return True 56 | 57 | def expandingDirections(self): 58 | return QtCore.Qt.Orientations(QtCore.Qt.Orientation(0)) 59 | 60 | def hasHeightForWidth(self): 61 | return True 62 | 63 | def heightForWidth(self, width): 64 | height = self.do_layout(QtCore.QRect(0, 0, width, 0)) 65 | return height 66 | 67 | def setGeometry(self, rect): 68 | super(FlowLayout, self).setGeometry(rect) 69 | self.do_layout(rect, False) 70 | 71 | def sizeHint(self): 72 | return self.minimumSize() 73 | 74 | def minimumSize(self): 75 | size = QtCore.QSize(2 * self.contentsMargins().top(), 2 * self.contentsMargins().top()) 76 | return size 77 | 78 | def do_layout(self, rect, test_only=True): 79 | margins = self.contentsMargins() 80 | start_x = rect.x() + margins.left() 81 | start_y = rect.y() + margins.top() 82 | 83 | x = start_x 84 | y = start_y 85 | line_height = 0 86 | 87 | for item in self.item_list: 88 | widget = item.widget() 89 | 90 | space_x = self.spacing() + widget.style().layoutSpacing( 91 | QtWidgets.QSizePolicy.PushButton, QtWidgets.QSizePolicy.PushButton, QtCore.Qt.Horizontal 92 | ) 93 | space_y = self.spacing() + widget.style().layoutSpacing( 94 | QtWidgets.QSizePolicy.PushButton, QtWidgets.QSizePolicy.PushButton, QtCore.Qt.Vertical 95 | ) + 1 96 | 97 | next_x = x + widget.sizeHint().width() + space_x 98 | if next_x - space_x > rect.right() and line_height > 0: 99 | x = start_x 100 | y = y + line_height + space_y 101 | next_x = x + widget.sizeHint().width() + space_x 102 | line_height = 0 103 | 104 | if item == self.item_list[-1] and self._expand_last: 105 | width = rect.width() - x - 1 if self._expand_h else item.sizeHint().width() 106 | height = rect.height() - y - 1 if self._expand_v else item.sizeHint().height() 107 | size = QtCore.QSize(width, height) 108 | else: 109 | size = item.sizeHint() 110 | 111 | if not test_only: 112 | item.setGeometry(QtCore.QRect(QtCore.QPoint(x, y), size)) 113 | 114 | x = next_x 115 | 116 | line_height = max(line_height, item.sizeHint().height()) 117 | 118 | return y + line_height - rect.y() 119 | -------------------------------------------------------------------------------- /guibedos/widgets/tag_bar.py: -------------------------------------------------------------------------------- 1 | """ 2 | Button based LineEdit, for tag edition 3 | """ 4 | import re 5 | from Qt import QtCore 6 | from Qt import QtWidgets 7 | from ..css import parse_images 8 | from .flow_layout import FlowLayout 9 | 10 | 11 | _REGEXP = re.compile(r']+)>') 12 | 13 | 14 | class Clipboard(object): 15 | """ 16 | Thin wrapper around QApplication's clipboard 17 | """ 18 | 19 | @staticmethod 20 | def get(): 21 | clipboard = QtWidgets.QApplication.clipboard() 22 | return clipboard.text() 23 | 24 | @staticmethod 25 | def set(text_): 26 | clipboard = QtWidgets.QApplication.clipboard() 27 | clipboard.setText(text_) 28 | 29 | 30 | class _ButtonSelectionModel(object): 31 | def __init__(self): 32 | self._names = list() 33 | self._index = 0 34 | self._shift_index = 0 35 | self._is_shift = False 36 | 37 | @property 38 | def names(self): 39 | return self._names 40 | 41 | @names.setter 42 | def names(self, names): 43 | self._names = names 44 | self._index = 0 45 | self._shift_index = 0 46 | 47 | @property 48 | def current(self): 49 | """ 50 | Name of the selected Button (active) 51 | :return: 52 | """ 53 | return self.names[self._index] 54 | 55 | def _update_shift(self, is_shift=False): 56 | """ 57 | Checks whether shift status has changed, then stores the index at which shift was pressed 58 | :param is_shift: Shift status 59 | """ 60 | if self._is_shift != is_shift: 61 | self._shift_index = self._index 62 | 63 | self._is_shift = is_shift 64 | 65 | def desselect(self): 66 | self._index = 0 67 | self._shift_index = 0 68 | self._is_shift = False 69 | 70 | def left(self, is_shift=False): 71 | """ 72 | Move selection one step left 73 | :param is_shift: if shift key is pressed 74 | """ 75 | self._update_shift(is_shift) 76 | self._index = max(self._index - 1, -len(self.names)) 77 | 78 | def right(self, is_shift=False): 79 | """ 80 | Move selection one step right 81 | :param is_shift: if shift key is pressed 82 | """ 83 | self._update_shift(is_shift) 84 | self._index = min(0, self._index + 1) 85 | 86 | def selected(self): 87 | """ 88 | Names of the selected Buttons 89 | :return: 90 | """ 91 | if self._is_shift: 92 | if self._index == self._shift_index: 93 | return [self.names[self._index]] 94 | 95 | elif self._index < self._shift_index: 96 | self._shift_index = min(-1, self._shift_index) 97 | indexes = range(self._index, self._shift_index + 1) 98 | return [self.names[i] for i in indexes] 99 | 100 | else: 101 | self._index = min(-1, self._index) 102 | indexes = range(self._shift_index, self._index + 1) 103 | return [self.names[i] for i in indexes] 104 | 105 | if self._index == 0: 106 | return list() 107 | 108 | return [self.names[self._index]] 109 | 110 | 111 | class TagBar(QtWidgets.QWidget): 112 | STYLE_SHEET = """ 113 | QPushButton { 114 | padding: 3px 17px 3px 8px; 115 | margin: 0px 0px; 116 | background-image: url(qss:images/close_light.png); 117 | background-position: right; 118 | background-repeat: none; 119 | } 120 | 121 | QComboBox:editable { 122 | color : #5a5a5a; 123 | background-color: #cbd8e6; 124 | padding: 0px 0px 2px 0px; 125 | } 126 | 127 | QComboBox QAbstractItemView { 128 | color : #5a5a5a; 129 | } 130 | """ 131 | tags_changed = QtCore.Signal(list) 132 | 133 | def __init__(self, parent=None): 134 | super(TagBar, self).__init__(parent=parent) 135 | self.setStyleSheet(parse_images(self.STYLE_SHEET)) 136 | self.setFocusPolicy(QtCore.Qt.StrongFocus) 137 | 138 | self._model = _ButtonSelectionModel() 139 | self._buttons = list() 140 | 141 | self._autocompletables = list() 142 | 143 | self._editor = QtWidgets.QComboBox() 144 | self._editor.name = "-#-#-EDITOR-#-#-" 145 | self._editor.currentIndexChanged.connect(self._index_changed) 146 | self._editor.setEditable(True) 147 | self._editor.installEventFilter(self) 148 | 149 | self._layout = FlowLayout(self, expand_last=(True, False)) 150 | self._layout.addWidget(self._editor) 151 | 152 | @property 153 | def tags(self): 154 | return [button.name for button in self._buttons] 155 | 156 | @property 157 | def autocompletables(self): 158 | return self._autocompletables 159 | 160 | @autocompletables.setter 161 | def autocompletables(self, items): 162 | self._autocompletables = items 163 | completer = QtWidgets.QCompleter(self._autocompletables, self) 164 | completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive) 165 | self._editor.blockSignals(True) 166 | self._editor.setCompleter(completer) 167 | self._editor.clear() 168 | self._editor.addItems(items) 169 | self._editor.blockSignals(False) 170 | self._editor.setCurrentIndex(-1) 171 | 172 | def _index_changed(self): 173 | """ 174 | When a choice is made in the combobox 175 | """ 176 | self.add_button_from_text() 177 | 178 | def _update_model(self): 179 | """ 180 | Updates model with current button names 181 | """ 182 | self._model.names = [button.name for button in self._buttons] 183 | 184 | def _new_button(self, tag): 185 | """ 186 | Creates a new widget button 187 | :param tag: A valid tag 188 | :return: the new QPushButton, None otherwise 189 | """ 190 | if tag in self._model.names: 191 | return 192 | 193 | if '<' in tag or '>' in tag or not tag: 194 | return 195 | 196 | button = QtWidgets.QPushButton(tag) 197 | button.clicked.connect(self._button_clicked) 198 | button.setFocusPolicy(QtCore.Qt.NoFocus) 199 | button.installEventFilter(self) 200 | button.name = tag 201 | 202 | self._layout.insertWidget(self._layout.count() - 1, button) 203 | self._buttons.append(button) 204 | self._update_model() 205 | 206 | self.tags_changed.emit(self.tags) 207 | 208 | return button 209 | 210 | def _button_clicked(self): 211 | """ 212 | Deletes button when clicked 213 | """ 214 | self._delete_button(self.sender().name) 215 | 216 | def _set_text_editable(self, is_enabled): 217 | """ 218 | Defines if text edit is editable 219 | :param is_enabled: bool 220 | """ 221 | self._editor.lineEdit().setReadOnly(not is_enabled) 222 | 223 | def _set_text_cursor_position(self, position): 224 | """ 225 | Defines cursor position of text edit 226 | :param position: int 227 | """ 228 | self._editor.lineEdit().setCursorPosition(position) 229 | 230 | def _select_buttons(self): 231 | """ 232 | Updates buttons states according to model 233 | """ 234 | _ = [button.setDown(False) for button in self._buttons] 235 | 236 | for name in self._model.selected(): 237 | index = self._model.names.index(name) 238 | button = self._buttons[index] 239 | button.setDown(True) 240 | 241 | def _delete_button(self, name): 242 | """ 243 | Deletes a button by its name 244 | :param name: Button name 245 | """ 246 | index = [item.widget().name for item in self._layout.item_list].index(name) 247 | if self._layout.removeAt(index) is not None: 248 | self._buttons.pop(index) 249 | 250 | self._update_model() 251 | 252 | self.tags_changed.emit(self.tags) 253 | 254 | def _delete_selected_buttons(self): 255 | """ 256 | Removes selected buttons 257 | """ 258 | names = self._model.selected() 259 | 260 | # TODO : this should be dealt with by caller !! 261 | if not names: 262 | names = [self._model.names[-1]] 263 | 264 | for name in names: 265 | self._delete_button(name) 266 | 267 | def desselect(self): 268 | """ 269 | Clears button selection 270 | """ 271 | self._model.desselect() 272 | self._select_buttons() 273 | 274 | def add_button_from_text(self): 275 | """ 276 | Adds a new button, according to editable text content, clears text editor 277 | """ 278 | text = self._editor.currentText() 279 | self._new_button(text) 280 | 281 | self._editor.blockSignals(True) 282 | self._editor.setEditText('') 283 | self._editor.blockSignals(False) 284 | 285 | def set_tags(self, tags): 286 | """ 287 | Clears buttons and sets them 288 | :param tags: list of str 289 | """ 290 | for name in self._model.names: 291 | self._delete_button(name) 292 | 293 | for name in tags: 294 | self._new_button(name) 295 | 296 | def eventFilter(self, object_, event): 297 | type_ = event.type() 298 | text = self._editor.currentText() 299 | cursor = self._editor.lineEdit().cursorPosition() 300 | text_selected = self._editor.lineEdit().selectedText() 301 | is_shift = QtWidgets.QApplication.keyboardModifiers() & QtCore.Qt.ShiftModifier == QtCore.Qt.ShiftModifier 302 | is_ctrl = QtWidgets.QApplication.keyboardModifiers() & QtCore.Qt.ControlModifier == QtCore.Qt.ControlModifier 303 | 304 | if type_ == QtCore.QEvent.KeyPress: 305 | key = event.key() 306 | 307 | # TODO : better unification with model._delete_selected_buttons() 308 | if key == QtCore.Qt.Key_Backspace and cursor == 0 and self._buttons and not text_selected: 309 | self._delete_selected_buttons() 310 | 311 | if key == QtCore.Qt.Key_Delete and self._model.selected(): 312 | self._delete_selected_buttons() 313 | 314 | elif key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return) and text: 315 | self.add_button_from_text() 316 | return True 317 | 318 | elif key == QtCore.Qt.Key_Left and cursor == 0 and self._buttons: 319 | self._model.left(is_shift) 320 | self._select_buttons() 321 | return True 322 | 323 | elif key == QtCore.Qt.Key_Right and cursor == 0: 324 | self._model.right(is_shift) 325 | self._select_buttons() 326 | return bool(self._model.selected()) 327 | 328 | elif key == QtCore.Qt.Key_C and is_ctrl: 329 | tags = ' '.join([''.format(tag) for tag in self._model.selected()]) 330 | Clipboard.set(tags) 331 | self.desselect() 332 | return True 333 | 334 | elif key == QtCore.Qt.Key_V and is_ctrl: 335 | for tag in _REGEXP.findall(Clipboard.get()): 336 | self._new_button(tag) 337 | self.desselect() 338 | return True 339 | 340 | elif key == QtCore.Qt.Key_Tab: 341 | parent = self.parent() 342 | if parent: parent.focusNextChild() 343 | 344 | elif key == QtCore.Qt.Key_Backtab: 345 | parent = self.parent() 346 | if parent: parent.focusPreviousChild() 347 | 348 | return QtWidgets.QWidget.eventFilter(self, object_, event) 349 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from os import path 2 | from codecs import open 3 | from setuptools import setup, find_packages 4 | 5 | 6 | NAME = 'guibedos' 7 | VERSION = '1.7.2' 8 | DESCRIPTION = 'PySide widgets and helpers' 9 | AUTHOR = 'Cube Creative' 10 | AUTHOR_EMAIL = 'development@cube-creative.com' 11 | 12 | 13 | _here = path.abspath(path.dirname(__file__)) 14 | _readme_filepath = path.join(_here, 'README.md') 15 | _requirements_filepath = path.join(_here, 'requirements.txt') 16 | 17 | 18 | if path.isfile(_readme_filepath): 19 | with open(_readme_filepath, encoding='utf-8') as readme_file: 20 | _long_description = readme_file.read() 21 | else: 22 | _long_description = 'Unable to load README.md' 23 | 24 | 25 | if path.isfile(_requirements_filepath): 26 | with open(_requirements_filepath) as requirements_file: 27 | _requirements = requirements_file.readlines() 28 | else: 29 | _requirements = list() 30 | 31 | 32 | setup( 33 | name=NAME, 34 | version=VERSION, 35 | description=DESCRIPTION, 36 | long_description=_long_description, 37 | author=AUTHOR, 38 | author_email=AUTHOR_EMAIL, 39 | packages=find_packages(exclude=['tests']), 40 | install_requires=_requirements, 41 | include_package_data=True 42 | ) 43 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cube-creative/guibedos/3c0bbadcb70d9b935236ccb06ca44f9b17240b6d/tests/__init__.py -------------------------------------------------------------------------------- /tests/_analytics_script.py: -------------------------------------------------------------------------------- 1 | """ 2 | This script demonstrates the usage of the analytics module of guibedos 3 | """ 4 | import logging 5 | from guibedos.analytics import analyzed 6 | 7 | 8 | logging.basicConfig(level=logging.INFO) 9 | 10 | 11 | @analyzed('Never used') 12 | def never_used(): 13 | pass 14 | 15 | 16 | @analyzed('Used five times') 17 | def used_five_times(): 18 | logging.info('I will be called five times') 19 | 20 | 21 | @analyzed('Raising exception') 22 | def raising_exception(): 23 | raise RuntimeError('I am raising an exception') 24 | 25 | 26 | if __name__ == '__main__': 27 | logging.info("Analytics test script") 28 | 29 | for _ in range(5): 30 | used_five_times() 31 | 32 | raising_exception() 33 | -------------------------------------------------------------------------------- /tests/tests_analytics.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from unittest import TestCase 3 | 4 | from guibedos.analytics.runner import Runner 5 | 6 | 7 | class TestAnalytics(TestCase): 8 | 9 | def testAll(self): 10 | runner = Runner('Analytics Tests') 11 | report = runner.run([sys.executable, '_analytics_script.py']) 12 | 13 | # General 14 | self.assertEqual(report['name'], 'Analytics Tests') 15 | self.assertEqual(report['exit_code'], 1) 16 | 17 | # Never Used 18 | self.assertEqual(report['calls']['Never used']['count'], 0) 19 | 20 | # Five times 21 | self.assertEqual(report['calls']['Used five times']['count'], 5) 22 | self.assertEqual(report['calls']['Used five times']['exception_count'], 0) 23 | 24 | # Raising exception 25 | self.assertEqual(report['calls']['Raising exception']['count'], 1) 26 | self.assertEqual(report['calls']['Raising exception']['exception_count'], 1) 27 | --------------------------------------------------------------------------------