├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── azure-pipelines.yml ├── ci ├── build-mac.yml ├── build-win.yml ├── deploy.yml ├── deps-common.yml ├── deps-mac.yml ├── deps-win.yml ├── install-rust.yml ├── test.yml └── ubuntu │ ├── Dockerfile │ └── build_app_image.sh ├── examples ├── form │ ├── form1.yml │ ├── form2.yml │ ├── form3.yml │ └── form4.yml └── search │ ├── search1.yml │ └── search2.yml ├── images ├── example1.png ├── linuxform.png ├── macform.png └── winform.png ├── modulo-sys ├── Cargo.toml ├── build.rs ├── native │ ├── common.cpp │ ├── common.h │ ├── form.cpp │ ├── interop.h │ ├── mac.h │ ├── mac.mm │ └── search.cpp ├── res │ └── win.manifest └── src │ ├── form.rs │ ├── interop.rs │ ├── lib.rs │ └── search.rs ├── modulo ├── Cargo.toml └── src │ ├── form │ ├── config.rs │ ├── generator.rs │ ├── mod.rs │ └── parser │ │ ├── layout.rs │ │ ├── mod.rs │ │ └── split.rs │ ├── main.rs │ └── search │ ├── algorithm.rs │ ├── config.rs │ ├── generator.rs │ └── mod.rs └── packaging ├── linux ├── icon.svg └── modulo.desktop └── shasum.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | 12 | dist/ 13 | 14 | #Added by cargo 15 | 16 | /target 17 | 18 | .vscode/ 19 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = [ 3 | "modulo", 4 | "modulo-sys" 5 | ] 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # modulo 2 | 3 | > A (very) basic Cross-platform GUI Toolkit for Any Language 4 | 5 | Modulo is a simple, distributable binary that can be used to generate a variety of native GUI dialogs with ease: 6 | 7 | macOS | Linux | Windows 8 | :-------------------------:|:-------------------------:|:-------------------------: 9 | ![](/images/macform.png) | ![](/images/linuxform.png) | ![](/images/winform.png) 10 | 11 | ## Table of Contents 12 | 13 | * [Installation](#installation) 14 | * [Windows](#windows) 15 | * [macOS](#macos) 16 | * [Linux](#linux) 17 | * [Getting Started](#getting-started) 18 | * [Technology](#technology) 19 | 20 | ## Installation 21 | 22 | modulo is still in its early days, so some of the details are work in progress. 23 | 24 | ### Windows 25 | 26 | #### espanso users 27 | 28 | If you use modulo as part of espanso, it's shipped by default with it since version 0.7.0. 29 | 30 | #### Prebuilt release 31 | 32 | For Windows x64 systems, you can find the prebuilt `modulo-win.exe` in the [Releases](https://github.com/federico-terzi/modulo/releases) page. 33 | 34 | While you can simply download it in your favourite location, if you use modulo as part of espanso you should: 35 | 36 | * Rename the executable from `modulo-win.exe` to `modulo.exe` 37 | * Move it to a persistent location, such as `C:\modulo\modulo.exe` 38 | * Add that location (`C:\modulo`) to the PATH environment variable. 39 | 40 | **modulo also requires [Visual C++ Redistributable 2019](https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads) to run.** 41 | 42 | #### Compile from source 43 | 44 | To compile modulo on Windows, you need a recend Rust compiler, the MSVC C++ compiler and the LLVM compiler. 45 | 46 | TODO 47 | 48 | ### macOS 49 | 50 | #### espanso users 51 | 52 | If you use modulo as part of espanso and used Homebrew to install it, modulo is automatically included since version 0.7.0. 53 | 54 | #### Prebuilt release 55 | 56 | For x64 macOS systems, you can find the prebuilt `modulo-mac` in the [Releases](https://github.com/federico-terzi/modulo/releases) page. 57 | 58 | While you can simply download it in your favourite location, if you use modulo as part of espanso you should: 59 | 60 | * Rename the executable from `modulo-mac` to `modulo` 61 | * Place it in `/usr/local/bin` 62 | 63 | #### Compile from source 64 | 65 | Compiling from source on macOS requires a few steps: 66 | 67 | 1. Download the [wxWidgets source archive](https://www.wxwidgets.org/downloads/) 68 | 2. Extract the content of the archive in a known directory, such as `$USER/wxWidgets`. 69 | 3. Open a terminal, cd into the wxWidgets directory and type the follwing commands: 70 | 71 | ``` 72 | mkdir build-cocoa 73 | cd build-cocoa 74 | ../configure --disable-shared --enable-macosx_arch=x86_64 75 | make -j6 76 | ``` 77 | 78 | 4. Install LLVM using Homebrew with: `brew install llvm` 79 | 80 | 5. Now open the `modulo` project directory in the Terminal and compile with: `WXMAC=$USER/wxWidgets cargo build --release` 81 | 82 | 6. You will find the compiled binary in the `target/release` directory. 83 | 84 | ### Linux 85 | 86 | #### AppImage 87 | 88 | On Linux the easiest way to use modulo is the offical AppImage, that you can find in the [Releases](https://github.com/federico-terzi/modulo/releases) page. 89 | 90 | #### Compile from source 91 | 92 | Compiling modulo is not too difficult, but requires many tools so it's highly suggested to use the AppImage instead. If you still want to compile it: 93 | 94 | 1. Install the wxWidgets development packages for you platform, the Clang compiler and the Rust compiler. On Ubuntu/Debian, they can be installed with: `sudo apt install clang libwxgtk3.0-0v5 libwxgtk3.0-dev build-essential`. 95 | 96 | 2. In the project directory run: `cargo build --release`. 97 | 3. You will find the compiled binary in the `target/release` directory. 98 | 99 | ## Getting started 100 | 101 | ### Creating a Form 102 | 103 | There are a variety of built-in dialogs that can be customized by feeding modulo with YAML (or JSON) descriptors: 104 | 105 | 1. Create a `form.yml` file with the following content: 106 | 107 | ```yaml 108 | layout: | 109 | Hey {{name}}, 110 | This form is built with modulo! 111 | ``` 112 | 113 | 2. Invoke `modulo` with the command: 114 | 115 | ``` 116 | modulo form -i form.yml 117 | ``` 118 | 119 | 3. The dialog will appear: 120 | 121 | ![Example](images/example1.png) 122 | 123 | 4. After clicking on `Submit` (or pressing CTRL+Enter), modulo will return to the `STDOUT` the values as JSON: 124 | 125 | ```json 126 | {"name":"John"} 127 | ``` 128 | 129 | This was a very simple example to get you started, but its only the tip of the iceberg! 130 | 131 | ### Technology 132 | 133 | Modulo is written in Rust and uses the [wxWidgets](https://www.wxwidgets.org/) GUI toolkit under the hoods. This allows modulo to use platform-specific controls that feel, look and behave much better than other solutions based on emulation (such as web-based technologies as Electron), with the additional benefit of a very small final size. 134 | 135 | More info coming soon... -------------------------------------------------------------------------------- /azure-pipelines.yml: -------------------------------------------------------------------------------- 1 | # Starter pipeline 2 | # Start with a minimal pipeline that you can customize to build and deploy your code. 3 | # Add steps that build, run tests, deploy, and more: 4 | # https://aka.ms/yaml 5 | 6 | variables: 7 | # Increment and commit this number to invalidate wxWidgets cache 8 | WXWIDGETS_CACHE_ID: 2 9 | 10 | trigger: 11 | - master 12 | 13 | jobs: 14 | - job: UbuntuDocker 15 | pool: 16 | vmImage: 'ubuntu-latest' 17 | steps: 18 | - script: | 19 | mkdir dist 20 | sudo docker build -t modulo-ubuntu . -f ci/ubuntu/Dockerfile 21 | sudo docker run --rm -v "$(pwd)/dist:/shared" modulo-ubuntu modulo/ci/ubuntu/build_app_image.sh 22 | displayName: Setting up docker 23 | - template: ci/deploy.yml 24 | 25 | - job: macOS 26 | pool: 27 | vmImage: 'macOS-10.14' 28 | steps: 29 | - template: ci/deps-mac.yml 30 | - template: ci/build-mac.yml 31 | - template: ci/deploy.yml 32 | #- template: ci/publish-homebrew.yml 33 | 34 | - job: Windows 35 | pool: 36 | vmImage: 'windows-2019' 37 | steps: 38 | - template: ci/deps-win.yml 39 | - template: ci/build-win.yml 40 | - template: ci/deploy.yml -------------------------------------------------------------------------------- /ci/build-mac.yml: -------------------------------------------------------------------------------- 1 | steps: 2 | - script: | 3 | echo "##vso[task.setvariable variable=WXMAC]$(pwd)/wxWidgets" 4 | displayName: "Set wxWidgets directory" 5 | 6 | - script: | 7 | set -e 8 | cargo test --release 9 | displayName: Cargo test 10 | 11 | - script: | 12 | set -e 13 | cargo build --release 14 | displayName: Cargo build 15 | 16 | - script: | 17 | mkdir dist 18 | pushd target/release 19 | dir 20 | popd 21 | cp target/release/modulo dist/modulo-mac 22 | displayName: Copy artifacts -------------------------------------------------------------------------------- /ci/build-win.yml: -------------------------------------------------------------------------------- 1 | steps: 2 | - task: PythonScript@0 3 | displayName: "Find LLVM path" 4 | inputs: 5 | scriptSource: 'inline' 6 | script: | 7 | import subprocess 8 | path = subprocess.run(['vswhere', '-latest', '-products', '*', '-requires', 'Microsoft.VisualStudio.Component.VC.Llvm.Clang', '-property', 'installationPath'], stdout=subprocess.PIPE).stdout.decode('utf-8') 9 | path = path.replace('"', "").strip() 10 | path = path + "\\VC\\Tools\\Llvm\\x64\\bin" 11 | print("Clang path ", path) 12 | print("##vso[task.setvariable variable=LIBCLANG_PATH]"+path) 13 | 14 | - script: | 15 | echo ##vso[task.setvariable variable=WXWIN]%cd%\wxWidgets 16 | displayName: "Set wxWidgets directory" 17 | 18 | - script: | 19 | pushd %LIBCLANG_PATH% 20 | dir 21 | popd 22 | displayName: LLVM info 23 | 24 | - script: | 25 | set 26 | cargo test --release 27 | displayName: Cargo test 28 | 29 | - script: | 30 | cargo build --release 31 | displayName: Cargo build 32 | 33 | - script: | 34 | mkdir dist 35 | pushd target\release 36 | dir 37 | popd 38 | copy target\release\modulo.exe dist 39 | pushd dist 40 | ren modulo.exe modulo-win.exe 41 | displayName: Copy artifacts -------------------------------------------------------------------------------- /ci/deploy.yml: -------------------------------------------------------------------------------- 1 | parameters: 2 | github: 3 | isPreRelease: false 4 | repositoryName: '$(Build.Repository.Name)' 5 | gitHubConnection: "MyGithubConnection" 6 | dependsOn: [] 7 | displayName: "Release to github" 8 | 9 | steps: 10 | - script: | 11 | VER=$(cat modulo/Cargo.toml| grep version -m 1 | awk -F '"' '{ print $2 }') 12 | echo '##vso[task.setvariable variable=vers]'v$VER 13 | condition: not(eq(variables['Agent.OS'], 'Windows_NT')) 14 | displayName: Obtain version from Cargo.toml on Unix 15 | - powershell: | 16 | Select-String -Path "modulo\Cargo.toml" -Pattern "version" | Select-Object -First 1 -outvariable v 17 | $vv = [regex]::match($v, '"([^"]+)"').Groups[1].Value 18 | echo "##vso[task.setvariable variable=vers]v$vv" 19 | condition: eq(variables['Agent.OS'], 'Windows_NT') 20 | displayName: Obtain version from Cargo.toml on Windows 21 | 22 | - task: UsePythonVersion@0 23 | inputs: 24 | versionSpec: '3.7' 25 | addToPath: true 26 | 27 | - task: PythonScript@0 28 | displayName: "Calculate SHA sums" 29 | inputs: 30 | scriptSource: 'filePath' 31 | scriptPath: "packaging/shasum.py" 32 | arguments: "dist" 33 | 34 | - task: GitHubRelease@0 35 | displayName: Create GitHub release 36 | inputs: 37 | gitHubConnection: ${{ parameters.github.gitHubConnection }} 38 | tagSource: manual 39 | title: '$(vers)' 40 | tag: '$(vers)' 41 | assetUploadMode: replace 42 | action: edit 43 | assets: 'dist/*' 44 | addChangeLog: false 45 | repositoryName: ${{ parameters.github.repositoryName }} 46 | isPreRelease: ${{ parameters.github.isPreRelease }} 47 | condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/master')) -------------------------------------------------------------------------------- /ci/deps-common.yml: -------------------------------------------------------------------------------- 1 | steps: 2 | - task: UsePythonVersion@0 3 | inputs: 4 | versionSpec: '3.7' 5 | addToPath: true 6 | 7 | - task: Cache@2 8 | inputs: 9 | key: '"$(Agent.OS)" | "$(WXWIDGETS_CACHE_ID)"' 10 | path: "wxWidgets" 11 | cacheHitVar: WX_CACHE_RESTORED 12 | displayName: Cache wxWidgets libs 13 | 14 | - task: PythonScript@0 15 | displayName: "Download wxWidgets" 16 | inputs: 17 | scriptSource: 'inline' 18 | script: | 19 | import urllib.request 20 | urllib.request.urlretrieve("https://github.com/wxWidgets/wxWidgets/releases/download/v3.1.4/wxWidgets-3.1.4.zip", "wxWidgets.zip") 21 | condition: ne(variables.WX_CACHE_RESTORED, 'true') 22 | 23 | - task: ExtractFiles@1 24 | displayName: "Extract wxWidgets" 25 | inputs: 26 | archiveFilePatterns: "wxWidgets.zip" 27 | destinationFolder: "wxWidgets" 28 | condition: ne(variables.WX_CACHE_RESTORED, 'true') 29 | -------------------------------------------------------------------------------- /ci/deps-mac.yml: -------------------------------------------------------------------------------- 1 | steps: 2 | - template: "deps-common.yml" 3 | 4 | - script: | 5 | brew install llvm 6 | displayName: "Install LLVM" 7 | 8 | - script: | 9 | pushd wxWidgets 10 | mkdir build-cocoa 11 | pushd build-cocoa 12 | ../configure --disable-shared --enable-macosx_arch=x86_64 --with-libjpeg=builtin --with-libpng=builtin --with-libtiff=builtin 13 | make -j4 14 | displayName: "Compile wxWidgets" 15 | condition: ne(variables.WX_CACHE_RESTORED, 'true') 16 | 17 | - template: "install-rust.yml" -------------------------------------------------------------------------------- /ci/deps-win.yml: -------------------------------------------------------------------------------- 1 | steps: 2 | - template: "deps-common.yml" 3 | 4 | - script: | 5 | for /f "tokens=*" %%i in ('vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath') do set msbuildpath="%%i" 6 | echo "##vso[task.setvariable variable=msbuildpath]%msbuildpath%" 7 | echo "Path " %msbuildpath% 8 | call %msbuildpath%\VC\Auxiliary\Build\vcvars64.bat 9 | dir 10 | cd wxWidgets\build\msw 11 | dir 12 | echo "compiling..." 13 | nmake /f makefile.vc BUILD=release TARGET_CPU=X64 14 | displayName: "Compile wxWidgets" 15 | condition: ne(variables.WX_CACHE_RESTORED, 'true') 16 | 17 | - template: "install-rust.yml" -------------------------------------------------------------------------------- /ci/install-rust.yml: -------------------------------------------------------------------------------- 1 | # defaults for any parameters that aren't specified 2 | parameters: 3 | rust_version: stable 4 | 5 | steps: 6 | # Linux and macOS. 7 | - script: | 8 | set -e 9 | curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain $RUSTUP_TOOLCHAIN 10 | echo "##vso[task.setvariable variable=PATH;]$PATH:$HOME/.cargo/bin" 11 | env: 12 | RUSTUP_TOOLCHAIN: ${{parameters.rust_version}} 13 | displayName: "Install rust (*nix)" 14 | condition: not(eq(variables['Agent.OS'], 'Windows_NT')) 15 | # Windows. 16 | - script: | 17 | curl -sSf -o rustup-init.exe https://win.rustup.rs 18 | rustup-init.exe -y --default-toolchain %RUSTUP_TOOLCHAIN% --default-host x86_64-pc-windows-msvc 19 | set PATH=%PATH%;%USERPROFILE%\.cargo\bin 20 | echo "##vso[task.setvariable variable=PATH;]%PATH%;%USERPROFILE%\.cargo\bin" 21 | env: 22 | RUSTUP_TOOLCHAIN: ${{parameters.rust_version}} 23 | displayName: "Install rust (windows)" 24 | condition: eq(variables['Agent.OS'], 'Windows_NT') 25 | # Install additional components: 26 | - ${{ each component in parameters.components }}: 27 | - script: rustup component add ${{ component }} 28 | 29 | # All platforms. 30 | - script: | 31 | rustup -V 32 | rustup component list --installed 33 | rustc -Vv 34 | cargo -V 35 | displayName: Query rust and cargo versions -------------------------------------------------------------------------------- /ci/test.yml: -------------------------------------------------------------------------------- 1 | steps: 2 | - script: | 3 | echo Master check 4 | displayName: Master branch check 5 | condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/master')) 6 | 7 | - script: | 8 | set -e 9 | cargo test --release 10 | displayName: Cargo tests on Unix 11 | condition: not(eq(variables['Agent.OS'], 'Windows_NT')) -------------------------------------------------------------------------------- /ci/ubuntu/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:16.04 2 | 3 | RUN apt-get update \ 4 | && apt-get install -y \ 5 | clang libwxgtk3.0-0v5 libwxgtk3.0-dev \ 6 | wget git build-essential 7 | 8 | ENV RUSTUP_HOME=/usr/local/rustup \ 9 | CARGO_HOME=/usr/local/cargo \ 10 | PATH=/usr/local/cargo/bin:$PATH \ 11 | RUST_VERSION=1.44.0 12 | 13 | RUN set -eux; \ 14 | dpkgArch="$(dpkg --print-architecture)"; \ 15 | case "${dpkgArch##*-}" in \ 16 | amd64) rustArch='x86_64-unknown-linux-gnu'; rustupSha256='ad1f8b5199b3b9e231472ed7aa08d2e5d1d539198a15c5b1e53c746aad81d27b' ;; \ 17 | armhf) rustArch='armv7-unknown-linux-gnueabihf'; rustupSha256='6c6c3789dabf12171c7f500e06d21d8004b5318a5083df8b0b02c0e5ef1d017b' ;; \ 18 | arm64) rustArch='aarch64-unknown-linux-gnu'; rustupSha256='26942c80234bac34b3c1352abbd9187d3e23b43dae3cf56a9f9c1ea8ee53076d' ;; \ 19 | i386) rustArch='i686-unknown-linux-gnu'; rustupSha256='27ae12bc294a34e566579deba3e066245d09b8871dc021ef45fc715dced05297' ;; \ 20 | *) echo >&2 "unsupported architecture: ${dpkgArch}"; exit 1 ;; \ 21 | esac; \ 22 | url="https://static.rust-lang.org/rustup/archive/1.21.1/${rustArch}/rustup-init"; \ 23 | wget "$url"; \ 24 | echo "${rustupSha256} *rustup-init" | sha256sum -c -; \ 25 | chmod +x rustup-init; \ 26 | ./rustup-init -y --no-modify-path --profile minimal --default-toolchain $RUST_VERSION; \ 27 | rm rustup-init; \ 28 | chmod -R a+w $RUSTUP_HOME $CARGO_HOME; \ 29 | rustup --version; \ 30 | cargo --version; \ 31 | rustc --version; 32 | 33 | RUN mkdir modulo 34 | 35 | COPY . modulo -------------------------------------------------------------------------------- /ci/ubuntu/build_app_image.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | echo "Testing modulo..." 6 | cd modulo 7 | cargo test --release 8 | 9 | ls 10 | 11 | echo "Building binary" 12 | pushd modulo 13 | cargo build --release 14 | popd 15 | 16 | echo "Downloading linuxdeploy to create AppImage" 17 | 18 | wget https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous/linuxdeploy-x86_64.AppImage 19 | 20 | # make them executable 21 | chmod +x linuxdeploy*.AppImage 22 | 23 | echo "Building AppImage" 24 | 25 | ./linuxdeploy-x86_64.AppImage --appimage-extract-and-run -e "/modulo/target/release/modulo" -d "/modulo/packaging/linux/modulo.desktop" -i "/modulo/packaging/linux/icon.svg" --appdir AppDir --output appimage 26 | 27 | cp ./modulo-*.AppImage /shared/modulo-x86_64.AppImage 28 | 29 | ls /shared -------------------------------------------------------------------------------- /examples/form/form1.yml: -------------------------------------------------------------------------------- 1 | title: "Example Form" 2 | #icon: "C:\\Users\\Freddy\\AppData\\Local\\espanso\\espanso.ico" 3 | layout: | 4 | Hey {{name}}, 5 | {{message}} 6 | 7 | {{end}} 8 | 9 | Cheers :) 10 | fields: 11 | name: 12 | default: "John" 13 | message: 14 | multiline: true 15 | end: 16 | type: choice 17 | values: 18 | - "Looking forward to hearing from you" 19 | - "Let me know what you think" 20 | - "Let me know if that helps" 21 | - "Thanks for the help!" -------------------------------------------------------------------------------- /examples/form/form2.yml: -------------------------------------------------------------------------------- 1 | layout: | 2 | Hey {{name}}, 3 | This form is built with modulo! 4 | -------------------------------------------------------------------------------- /examples/form/form3.yml: -------------------------------------------------------------------------------- 1 | layout: "Author: {{author}}" 2 | fields: 3 | author: 4 | default: "Two" 5 | type: choice 6 | values: 7 | - "AmberHaelo" 8 | - "Two" 9 | - "Three" 10 | -------------------------------------------------------------------------------- /examples/form/form4.yml: -------------------------------------------------------------------------------- 1 | layout: | 2 | Hello 中文測試 {{name}}, 3 | This form is built with modulo! 4 | fields: 5 | name: 6 | default: 中 -------------------------------------------------------------------------------- /examples/search/search1.yml: -------------------------------------------------------------------------------- 1 | title: "Test Search" 2 | #icon: "C:\\Users\\Freddy\\AppData\\Local\\espanso\\espanso.ico" 3 | items: 4 | - id: "open" 5 | label: "Open modulo" 6 | - id: "close" 7 | label: "Close modulo" 8 | - id: "search" 9 | label: "Search items" -------------------------------------------------------------------------------- /examples/search/search2.yml: -------------------------------------------------------------------------------- 1 | title: "Test Search" 2 | items: 3 | - id: "open" 4 | label: "Open modulo" 5 | - id: "close" 6 | label: "Close modulo" 7 | - id: "search" 8 | label: "Search items" 9 | - id: "exit" 10 | label: "Exit" 11 | - id: "another" 12 | label: "Another entry" 13 | - id: "open" 14 | label: "Open modulo" 15 | - id: "close" 16 | label: "Close modulo" 17 | - id: "search" 18 | label: "Search items" 19 | - id: "exit" 20 | label: "Exit" 21 | - id: "another" 22 | label: "Another entry" -------------------------------------------------------------------------------- /images/example1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/federico-terzi/modulo/b4f6d2c032ca75face8c078583b3a3dd641f93ab/images/example1.png -------------------------------------------------------------------------------- /images/linuxform.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/federico-terzi/modulo/b4f6d2c032ca75face8c078583b3a3dd641f93ab/images/linuxform.png -------------------------------------------------------------------------------- /images/macform.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/federico-terzi/modulo/b4f6d2c032ca75face8c078583b3a3dd641f93ab/images/macform.png -------------------------------------------------------------------------------- /images/winform.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/federico-terzi/modulo/b4f6d2c032ca75face8c078583b3a3dd641f93ab/images/winform.png -------------------------------------------------------------------------------- /modulo-sys/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "modulo-sys" 3 | version = "0.1.0" 4 | license = "GPL-3.0" 5 | readme = "README.md" 6 | homepage = "https://github.com/federico-terzi/modulo" 7 | authors = ["Federico Terzi "] 8 | edition = "2018" 9 | build = "build.rs" 10 | 11 | [dependencies] 12 | 13 | [build-dependencies] 14 | cc = "1.0.58" 15 | bindgen = "0.54.0" 16 | regex = "1.3.9" 17 | 18 | [target.'cfg(windows)'.build-dependencies] 19 | winres = "0.1.11" 20 | -------------------------------------------------------------------------------- /modulo-sys/build.rs: -------------------------------------------------------------------------------- 1 | use regex::Regex; 2 | use std::path::{Path, PathBuf}; 3 | 4 | // TODO: add documentation for windows compile 5 | // Go to %WXWIN%/build/msw 6 | // nmake /f makefile.vc BUILD=release TARGET_CPU=X64 7 | 8 | // Then install bindgen dependencies: 9 | // https://rust-lang.github.io/rust-bindgen/requirements.html 10 | 11 | #[cfg(target_os = "windows")] 12 | fn build_native() { 13 | let wx_location = std::env::var("WXWIN").expect("unable to find wxWidgets directory, please add a WXWIN env variable with the absolute path"); 14 | let wx_path = PathBuf::from(&wx_location); 15 | println!("{}", wx_location); 16 | if !wx_path.is_dir() { 17 | panic!("The given WXWIN directory is not valid"); 18 | } 19 | 20 | // Make sure wxWidgets is compiled 21 | if !wx_path 22 | .join("build") 23 | .join("msw") 24 | .join("vc_mswu_x64") 25 | .is_dir() 26 | { 27 | panic!("wxWidgets is not compiled correctly, missing 'build/msw/vc_mswu_x64' directory") 28 | } 29 | 30 | let wx_include_dir = wx_path.join("include"); 31 | let wx_include_msvc_dir = wx_include_dir.join("msvc"); 32 | let wx_lib_dir = wx_path.join("lib").join("vc_x64_lib"); 33 | 34 | cc::Build::new() 35 | .cpp(true) 36 | .file("native/form.cpp") 37 | .file("native/search.cpp") 38 | .file("native/common.cpp") 39 | .flag("/EHsc") 40 | .include(wx_include_dir) 41 | .include(wx_include_msvc_dir) 42 | .compile("modulosys"); 43 | 44 | // Add resources (manifest) 45 | let mut resources = winres::WindowsResource::new(); 46 | resources.set_manifest(include_str!("res/win.manifest")); 47 | resources 48 | .compile() 49 | .expect("unable to compile resource file"); 50 | 51 | println!( 52 | "cargo:rustc-link-search=native={}", 53 | wx_lib_dir.to_string_lossy() 54 | ); 55 | } 56 | 57 | // TODO: add documentation for macos 58 | // Install LLVM: 59 | // brew install llvm 60 | // Compile wxWidgets: 61 | // mkdir build-cocoa 62 | // cd build-cocoa 63 | // ../configure --disable-shared --enable-macosx_arch=x86_64 64 | // make -j6 65 | // 66 | // Run 67 | // WXMAC=/Users/freddy/wxWidgets cargo run 68 | #[cfg(target_os = "macos")] 69 | fn build_native() { 70 | let wx_location = std::env::var("WXMAC").expect("unable to find wxWidgets directory, please add a WXMAC env variable with the absolute path"); 71 | let wx_path = PathBuf::from(&wx_location); 72 | println!("{}", wx_location); 73 | if !wx_path.is_dir() { 74 | panic!("The given WXMAC directory is not valid"); 75 | } 76 | 77 | // Make sure wxWidgets is compiled 78 | if !wx_path.join("build-cocoa").is_dir() { 79 | panic!("wxWidgets is not compiled correctly, missing 'build-cocoa/' directory") 80 | } 81 | 82 | let config_path = wx_path.join("build-cocoa").join("wx-config"); 83 | let cpp_flags = get_cpp_flags(&config_path); 84 | 85 | let mut build = cc::Build::new(); 86 | build 87 | .cpp(true) 88 | .file("native/form.cpp") 89 | .file("native/common.cpp") 90 | .file("native/search.cpp") 91 | .file("native/mac.mm"); 92 | build.flag("-std=c++17"); 93 | 94 | for flag in cpp_flags { 95 | build.flag(&flag); 96 | } 97 | 98 | build.compile("modulosys"); 99 | 100 | // Render linker flags 101 | 102 | generate_linker_flags(&config_path); 103 | 104 | // On (older) OSX we need to link against the clang runtime, 105 | // which is hidden in some non-default path. 106 | // 107 | // More details at https://github.com/alexcrichton/curl-rust/issues/279. 108 | if let Some(path) = macos_link_search_path() { 109 | println!("cargo:rustc-link-lib=clang_rt.osx"); 110 | println!("cargo:rustc-link-search={}", path); 111 | } 112 | } 113 | 114 | fn get_cpp_flags(wx_config_path: &Path) -> Vec { 115 | let config_output = std::process::Command::new(&wx_config_path) 116 | .arg("--cxxflags") 117 | .output() 118 | .expect("unable to execute wx-config"); 119 | let config_libs = 120 | String::from_utf8(config_output.stdout).expect("unable to parse wx-config output"); 121 | let cpp_flags: Vec = config_libs 122 | .split(" ") 123 | .into_iter() 124 | .filter_map(|s| { 125 | if !s.trim().is_empty() { 126 | Some(s.trim().to_owned()) 127 | } else { 128 | None 129 | } 130 | }) 131 | .collect(); 132 | cpp_flags 133 | } 134 | 135 | fn generate_linker_flags(wx_config_path: &Path) { 136 | let config_output = std::process::Command::new(&wx_config_path) 137 | .arg("--libs") 138 | .output() 139 | .expect("unable to execute wx-config libs"); 140 | let config_libs = 141 | String::from_utf8(config_output.stdout).expect("unable to parse wx-config libs output"); 142 | let linker_flags: Vec = config_libs 143 | .split(" ") 144 | .into_iter() 145 | .filter_map(|s| { 146 | if !s.trim().is_empty() { 147 | Some(s.trim().to_owned()) 148 | } else { 149 | None 150 | } 151 | }) 152 | .collect(); 153 | 154 | let static_lib_extract = Regex::new(r"lib/lib(.*)\.a").unwrap(); 155 | 156 | // Translate the flags generated by `wx-config` to commands 157 | // that cargo can understand. 158 | for (i, flag) in linker_flags.iter().enumerate() { 159 | if flag.starts_with("-L") { 160 | let path = flag.trim_start_matches("-L"); 161 | println!("cargo:rustc-link-search=native={}", path); 162 | } else if flag.starts_with("-framework") { 163 | println!("cargo:rustc-link-lib=framework={}", linker_flags[i + 1]); 164 | } else if flag.starts_with("/") { 165 | let captures = static_lib_extract 166 | .captures(flag) 167 | .expect("unable to capture flag regex"); 168 | let libname = captures.get(1).expect("unable to find static libname"); 169 | println!("cargo:rustc-link-lib=static={}", libname.as_str()); 170 | } else if flag.starts_with("-l") { 171 | let libname = flag.trim_start_matches("-l"); 172 | println!("cargo:rustc-link-lib=dylib={}", libname); 173 | } 174 | } 175 | } 176 | 177 | // Taken from curl-rust: https://github.com/alexcrichton/curl-rust/pull/283/files 178 | #[cfg(target_os = "macos")] 179 | fn macos_link_search_path() -> Option { 180 | let output = std::process::Command::new("clang") 181 | .arg("--print-search-dirs") 182 | .output() 183 | .ok()?; 184 | if !output.status.success() { 185 | println!( 186 | "failed to run 'clang --print-search-dirs', continuing without a link search path" 187 | ); 188 | return None; 189 | } 190 | 191 | let stdout = String::from_utf8_lossy(&output.stdout); 192 | for line in stdout.lines() { 193 | if line.contains("libraries: =") { 194 | let path = line.split('=').skip(1).next()?; 195 | return Some(format!("{}/lib/darwin", path)); 196 | } 197 | } 198 | 199 | println!("failed to determine link search path, continuing without it"); 200 | None 201 | } 202 | 203 | // TODO: add documentation for linux 204 | // Install LLVM: 205 | // sudo apt install clang 206 | // Install wxWidgets: 207 | // sudo apt install libwxgtk3.0-0v5 libwxgtk3.0-dev 208 | // 209 | // cargo run 210 | #[cfg(target_os = "linux")] 211 | fn build_native() { 212 | // Make sure wxWidgets is installed 213 | if !std::process::Command::new("wx-config") 214 | .arg("--version") 215 | .output() 216 | .is_ok() 217 | { 218 | panic!("wxWidgets is not installed, as `wx-config` cannot be exectued") 219 | } 220 | 221 | let config_path = PathBuf::from("wx-config"); 222 | let cpp_flags = get_cpp_flags(&config_path); 223 | 224 | let mut build = cc::Build::new(); 225 | build 226 | .cpp(true) 227 | .file("native/form.cpp") 228 | .file("native/search.cpp") 229 | .file("native/common.cpp"); 230 | build.flag("-std=c++17"); 231 | 232 | for flag in cpp_flags { 233 | build.flag(&flag); 234 | } 235 | 236 | build.compile("modulosys"); 237 | 238 | // Render linker flags 239 | 240 | generate_linker_flags(&config_path); 241 | } 242 | 243 | fn generate_bindings() { 244 | let bindings = bindgen::Builder::default() 245 | .header("native/interop.h") 246 | .parse_callbacks(Box::new(bindgen::CargoCallbacks)) 247 | .generate() 248 | .expect("unable to generate bindings"); 249 | 250 | let out_path = PathBuf::from(std::env::var("OUT_DIR").unwrap()); 251 | bindings 252 | .write_to_file(out_path.join("bindings.rs")) 253 | .expect("unable to write bindings"); 254 | } 255 | 256 | fn main() { 257 | // Generate the Rust bindings 258 | generate_bindings(); 259 | 260 | // TODO: might need to add rerun if changed: https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargorerun-if-changedpath 261 | 262 | build_native(); 263 | } 264 | -------------------------------------------------------------------------------- /modulo-sys/native/common.cpp: -------------------------------------------------------------------------------- 1 | #include "common.h" 2 | 3 | #ifdef __WXMSW__ 4 | #include 5 | #endif 6 | #ifdef __WXOSX__ 7 | #include "mac.h" 8 | #endif 9 | 10 | void setFrameIcon(const char * iconPath, wxFrame * frame) { 11 | if (iconPath) { 12 | wxString iconPath(iconPath); 13 | wxBitmapType imgType = wxICON_DEFAULT_TYPE; 14 | 15 | #ifdef __WXMSW__ 16 | imgType = wxBITMAP_TYPE_ICO; 17 | #endif 18 | 19 | wxIcon icon; 20 | icon.LoadFile(iconPath, imgType); 21 | if (icon.IsOk()) { 22 | frame->SetIcon(icon); 23 | } 24 | } 25 | } 26 | 27 | void Activate(wxFrame * frame) { 28 | #ifdef __WXMSW__ 29 | 30 | HWND handle = frame->GetHandle(); 31 | if (handle == GetForegroundWindow()) { 32 | return; 33 | } 34 | 35 | if (IsIconic(handle)) { 36 | ShowWindow(handle, 9); 37 | } 38 | 39 | INPUT ip; 40 | ip.type = INPUT_KEYBOARD; 41 | ip.ki.wScan = 0; 42 | ip.ki.time = 0; 43 | ip.ki.dwExtraInfo = 0; 44 | ip.ki.wVk = VK_MENU; 45 | ip.ki.dwFlags = 0; 46 | 47 | SendInput(1, &ip, sizeof(INPUT)); 48 | ip.ki.dwFlags = KEYEVENTF_KEYUP; 49 | 50 | SendInput(1, &ip, sizeof(INPUT)); 51 | 52 | SetForegroundWindow(handle); 53 | 54 | #endif 55 | #ifdef __WXOSX__ 56 | ActivateApp(); 57 | #endif 58 | } -------------------------------------------------------------------------------- /modulo-sys/native/common.h: -------------------------------------------------------------------------------- 1 | #ifndef MODULO_COMMON 2 | #define MODULO_COMMON 3 | 4 | #define _UNICODE 5 | 6 | #include 7 | #ifndef WX_PRECOMP 8 | #include 9 | #endif 10 | 11 | void setFrameIcon(const char * iconPath, wxFrame * frame); 12 | 13 | void Activate(wxFrame * frame); 14 | 15 | #endif -------------------------------------------------------------------------------- /modulo-sys/native/form.cpp: -------------------------------------------------------------------------------- 1 | #define _UNICODE 2 | 3 | #include "common.h" 4 | 5 | #include "interop.h" 6 | 7 | #include 8 | #include 9 | #include 10 | 11 | // https://docs.wxwidgets.org/stable/classwx_frame.html 12 | const long DEFAULT_STYLE = wxSTAY_ON_TOP | wxCLOSE_BOX | wxCAPTION; 13 | 14 | const int PADDING = 5; 15 | const int MULTILINE_MIN_HEIGHT = 100; 16 | const int MULTILINE_MIN_WIDTH = 100; 17 | 18 | FormMetadata *formMetadata = nullptr; 19 | std::vector values; 20 | 21 | // Field Wrappers 22 | 23 | class FieldWrapper { 24 | public: 25 | virtual wxString getValue() = 0; 26 | }; 27 | 28 | class TextFieldWrapper { 29 | wxTextCtrl * control; 30 | public: 31 | explicit TextFieldWrapper(wxTextCtrl * control): control(control) {} 32 | 33 | virtual wxString getValue() { 34 | return control->GetValue(); 35 | } 36 | }; 37 | 38 | class ChoiceFieldWrapper { 39 | wxChoice * control; 40 | public: 41 | explicit ChoiceFieldWrapper(wxChoice * control): control(control) {} 42 | 43 | virtual wxString getValue() { 44 | return control->GetStringSelection(); 45 | } 46 | }; 47 | 48 | class ListFieldWrapper { 49 | wxListBox * control; 50 | public: 51 | explicit ListFieldWrapper(wxListBox * control): control(control) {} 52 | 53 | virtual wxString getValue() { 54 | return control->GetStringSelection(); 55 | } 56 | }; 57 | 58 | // App Code 59 | 60 | class FormApp: public wxApp 61 | { 62 | public: 63 | virtual bool OnInit(); 64 | }; 65 | class FormFrame: public wxFrame 66 | { 67 | public: 68 | FormFrame(const wxString& title, const wxPoint& pos, const wxSize& size); 69 | 70 | wxPanel *panel; 71 | std::vector fields; 72 | std::unordered_map> idMap; 73 | wxButton *submit; 74 | private: 75 | void AddComponent(wxPanel *parent, wxBoxSizer *sizer, FieldMetadata meta); 76 | void Submit(); 77 | void OnSubmitBtn(wxCommandEvent& event); 78 | void OnEscape(wxKeyEvent& event); 79 | }; 80 | enum 81 | { 82 | ID_Submit = 20000 83 | }; 84 | 85 | bool FormApp::OnInit() 86 | { 87 | FormFrame *frame = new FormFrame(formMetadata->windowTitle, wxPoint(50, 50), wxSize(450, 340) ); 88 | setFrameIcon(formMetadata->iconPath, frame); 89 | frame->Show( true ); 90 | 91 | Activate(frame); 92 | 93 | return true; 94 | } 95 | FormFrame::FormFrame(const wxString& title, const wxPoint& pos, const wxSize& size) 96 | : wxFrame(NULL, wxID_ANY, title, pos, size, DEFAULT_STYLE) 97 | { 98 | panel = new wxPanel(this, wxID_ANY); 99 | wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); 100 | panel->SetSizer(vbox); 101 | 102 | for (int field = 0; field < formMetadata->fieldSize; field++) { 103 | FieldMetadata meta = formMetadata->fields[field]; 104 | AddComponent(panel, vbox, meta); 105 | } 106 | 107 | submit = new wxButton(panel, ID_Submit, "Submit"); 108 | vbox->Add(submit, 1, wxEXPAND | wxALL, PADDING); 109 | 110 | Bind(wxEVT_BUTTON, &FormFrame::OnSubmitBtn, this, ID_Submit); 111 | Bind(wxEVT_CHAR_HOOK, &FormFrame::OnEscape, this, wxID_ANY); 112 | // TODO: register ESC click handler: https://forums.wxwidgets.org/viewtopic.php?t=41926 113 | 114 | this->SetClientSize(panel->GetBestSize()); 115 | this->CentreOnScreen(); 116 | } 117 | 118 | void FormFrame::AddComponent(wxPanel *parent, wxBoxSizer *sizer, FieldMetadata meta) { 119 | void * control = nullptr; 120 | 121 | switch (meta.fieldType) { 122 | case FieldType::LABEL: 123 | { 124 | const LabelMetadata *labelMeta = static_cast(meta.specific); 125 | auto label = new wxStaticText(parent, wxID_ANY, wxString::FromUTF8(labelMeta->text), wxDefaultPosition, wxDefaultSize); 126 | control = label; 127 | fields.push_back(label); 128 | break; 129 | } 130 | case FieldType::TEXT: 131 | { 132 | const TextMetadata *textMeta = static_cast(meta.specific); 133 | long style = 0; 134 | if (textMeta->multiline) { 135 | style |= wxTE_MULTILINE; 136 | } 137 | 138 | auto textControl = new wxTextCtrl(parent, NewControlId(), wxString::FromUTF8(textMeta->defaultText), wxDefaultPosition, wxDefaultSize, style); 139 | 140 | if (textMeta->multiline) { 141 | textControl->SetMinSize(wxSize(MULTILINE_MIN_WIDTH, MULTILINE_MIN_HEIGHT)); 142 | } 143 | 144 | // Create the field wrapper 145 | std::unique_ptr field((FieldWrapper*) new TextFieldWrapper(textControl)); 146 | idMap[meta.id] = std::move(field); 147 | control = textControl; 148 | fields.push_back(textControl); 149 | break; 150 | } 151 | case FieldType::CHOICE: 152 | { 153 | const ChoiceMetadata *choiceMeta = static_cast(meta.specific); 154 | 155 | int selectedItem = -1; 156 | wxArrayString choices; 157 | for (int i = 0; ivalueSize; i++) { 158 | choices.Add(wxString::FromUTF8(choiceMeta->values[i])); 159 | 160 | if (strcmp(choiceMeta->values[i], choiceMeta->defaultValue) == 0) { 161 | selectedItem = i; 162 | } 163 | } 164 | 165 | void * choice = nullptr; 166 | if (choiceMeta->choiceType == ChoiceType::DROPDOWN) { 167 | choice = (void*) new wxChoice(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, choices); 168 | 169 | if (selectedItem >= 0) { 170 | ((wxChoice*)choice)->SetSelection(selectedItem); 171 | } 172 | 173 | // Create the field wrapper 174 | std::unique_ptr field((FieldWrapper*) new ChoiceFieldWrapper((wxChoice*) choice)); 175 | idMap[meta.id] = std::move(field); 176 | }else { 177 | choice = (void*) new wxListBox(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, choices); 178 | 179 | if (selectedItem >= 0) { 180 | ((wxListBox*)choice)->SetSelection(selectedItem); 181 | } 182 | 183 | // Create the field wrapper 184 | std::unique_ptr field((FieldWrapper*) new ListFieldWrapper((wxListBox*) choice)); 185 | idMap[meta.id] = std::move(field); 186 | } 187 | 188 | 189 | 190 | control = choice; 191 | fields.push_back(choice); 192 | break; 193 | } 194 | case FieldType::ROW: 195 | { 196 | const RowMetadata *rowMeta = static_cast(meta.specific); 197 | 198 | auto innerPanel = new wxPanel(panel, wxID_ANY); 199 | wxBoxSizer *hbox = new wxBoxSizer(wxHORIZONTAL); 200 | innerPanel->SetSizer(hbox); 201 | sizer->Add(innerPanel, 0, wxEXPAND | wxALL, 0); 202 | fields.push_back(innerPanel); 203 | 204 | for (int field = 0; field < rowMeta->fieldSize; field++) { 205 | FieldMetadata innerMeta = rowMeta->fields[field]; 206 | AddComponent(innerPanel, hbox, innerMeta); 207 | } 208 | 209 | break; 210 | } 211 | default: 212 | // TODO: handle unknown field type 213 | break; 214 | } 215 | 216 | if (control) { 217 | sizer->Add((wxWindow*) control, 0, wxEXPAND | wxALL, PADDING); 218 | } 219 | } 220 | 221 | void FormFrame::Submit() { 222 | for (auto& field: idMap) { 223 | FieldWrapper * fieldWrapper = (FieldWrapper*) field.second.get(); 224 | wxString value {fieldWrapper->getValue()}; 225 | wxCharBuffer buffer {value.ToUTF8()}; 226 | char * id = strdup(field.first); 227 | char * c_value = strdup(buffer.data()); 228 | ValuePair valuePair = { 229 | id, 230 | c_value, 231 | }; 232 | values.push_back(valuePair); 233 | } 234 | 235 | Close(true); 236 | } 237 | 238 | void FormFrame::OnSubmitBtn(wxCommandEvent &event) { 239 | Submit(); 240 | } 241 | 242 | void FormFrame::OnEscape(wxKeyEvent& event) { 243 | if (event.GetKeyCode() == WXK_ESCAPE) { 244 | Close(true); 245 | }else if(event.GetKeyCode() == WXK_RETURN && wxGetKeyState(WXK_RAW_CONTROL)) { 246 | Submit(); 247 | }else{ 248 | event.Skip(); 249 | } 250 | } 251 | 252 | extern "C" void interop_show_form(FormMetadata * _metadata, void (*callback)(ValuePair *values, int size, void *data), void *data) { 253 | // Setup high DPI support on Windows 254 | #ifdef __WXMSW__ 255 | SetProcessDPIAware(); 256 | #endif 257 | 258 | formMetadata = _metadata; 259 | 260 | wxApp::SetInstance(new FormApp()); 261 | int argc = 0; 262 | wxEntry(argc, (char **)nullptr); 263 | 264 | callback(values.data(), values.size(), data); 265 | 266 | // Free up values 267 | for (auto pair: values) { 268 | free((void*) pair.id); 269 | free((void*) pair.value); 270 | } 271 | } -------------------------------------------------------------------------------- /modulo-sys/native/interop.h: -------------------------------------------------------------------------------- 1 | // FORM 2 | 3 | typedef enum FieldType { 4 | ROW, 5 | LABEL, 6 | TEXT, 7 | CHOICE, 8 | CHECKBOX, 9 | } FieldType; 10 | 11 | typedef struct LabelMetadata { 12 | const char *text; 13 | } LabelMetadata; 14 | 15 | typedef struct TextMetadata { 16 | const char *defaultText; 17 | const int multiline; 18 | } TextMetadata; 19 | 20 | typedef enum ChoiceType { 21 | DROPDOWN, 22 | LIST, 23 | } ChoiceType; 24 | 25 | typedef struct ChoiceMetadata { 26 | const char * const * values; 27 | const int valueSize; 28 | const char *defaultValue; 29 | const ChoiceType choiceType; 30 | } ChoiceMetadata; 31 | 32 | typedef struct FieldMetadata { 33 | const char * id; 34 | FieldType fieldType; 35 | const void * specific; 36 | } FieldMetadata; 37 | 38 | typedef struct RowMetadata { 39 | const FieldMetadata *fields; 40 | const int fieldSize; 41 | } RowMetadata; 42 | 43 | typedef struct FormMetadata { 44 | const char *windowTitle; 45 | const char *iconPath; 46 | const FieldMetadata *fields; 47 | const int fieldSize; 48 | } FormMetadata; 49 | 50 | typedef struct ValuePair { 51 | const char *id; 52 | const char *value; 53 | } ValuePair; 54 | 55 | // SEARCH 56 | 57 | typedef struct SearchItem { 58 | const char *id; 59 | const char *label; 60 | } SearchItem; 61 | 62 | typedef struct SearchResults { 63 | const SearchItem * items; 64 | const int itemSize; 65 | } SearchResults; 66 | 67 | typedef struct SearchMetadata { 68 | const char *windowTitle; 69 | const char *iconPath; 70 | } SearchMetadata; -------------------------------------------------------------------------------- /modulo-sys/native/mac.h: -------------------------------------------------------------------------------- 1 | void ActivateApp(); -------------------------------------------------------------------------------- /modulo-sys/native/mac.mm: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | void ActivateApp() { 4 | [[NSRunningApplication currentApplication] activateWithOptions:(NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps)]; 5 | } -------------------------------------------------------------------------------- /modulo-sys/native/search.cpp: -------------------------------------------------------------------------------- 1 | #define _UNICODE 2 | 3 | #include "common.h" 4 | 5 | #include 6 | 7 | #include "interop.h" 8 | 9 | #include 10 | #include 11 | #include 12 | 13 | // https://docs.wxwidgets.org/stable/classwx_frame.html 14 | const long DEFAULT_STYLE = wxSTAY_ON_TOP | wxCLOSE_BOX | wxCAPTION; 15 | const int MIN_WIDTH = 500; 16 | const int MIN_HEIGHT = 20; 17 | 18 | typedef void (*QueryCallback)(const char * query, void * app, void * data); 19 | typedef void (*ResultCallback)(const char * id, void * data); 20 | 21 | SearchMetadata *searchMetadata = nullptr; 22 | QueryCallback queryCallback = nullptr; 23 | ResultCallback resultCallback = nullptr; 24 | void * data = nullptr; 25 | void * resultData = nullptr; 26 | wxArrayString wxItems; 27 | wxArrayString wxIds; 28 | 29 | // App Code 30 | 31 | class SearchApp: public wxApp 32 | { 33 | public: 34 | virtual bool OnInit(); 35 | }; 36 | 37 | class ResultListView: public wxListView 38 | { 39 | public: 40 | ResultListView(wxWindow *parent, 41 | const wxWindowID id, 42 | const wxPoint& pos, 43 | const wxSize& size, 44 | long style) 45 | : wxListView(parent, id, pos, size, style) 46 | {} 47 | void RescaleColumns(); 48 | private: 49 | virtual wxString OnGetItemText(long item, long column) const; 50 | }; 51 | 52 | wxString ResultListView::OnGetItemText(long item, long column) const 53 | { 54 | return wxItems[item]; 55 | } 56 | 57 | // Taken from https://groups.google.com/forum/#!topic/wx-users/jOwhl53ES5M 58 | // Used to hide the horizontal scrollbar 59 | void ResultListView::RescaleColumns() 60 | { 61 | int nWidth, nHeight; 62 | GetClientSize(&nWidth, &nHeight); 63 | const int main_col = 0; 64 | if (GetColumnWidth(main_col) != nWidth ) 65 | { 66 | SetColumnWidth(main_col, nWidth); 67 | } 68 | } 69 | 70 | class SearchFrame: public wxFrame 71 | { 72 | public: 73 | SearchFrame(const wxString& title, const wxPoint& pos, const wxSize& size); 74 | 75 | wxPanel *panel; 76 | wxTextCtrl *searchBar; 77 | ResultListView *resultBox; 78 | void SetItems(SearchItem *items, int itemSize); 79 | private: 80 | void OnCharEvent(wxKeyEvent& event); 81 | void OnQueryChange(wxCommandEvent& event); 82 | void OnItemClickEvent(wxListEvent& event); 83 | void SelectNext(); 84 | void SelectPrevious(); 85 | void Submit(); 86 | }; 87 | 88 | bool SearchApp::OnInit() 89 | { 90 | SearchFrame *frame = new SearchFrame(searchMetadata->windowTitle, wxPoint(50, 50), wxSize(450, 340) ); 91 | setFrameIcon(searchMetadata->iconPath, frame); 92 | frame->Show( true ); 93 | Activate(frame); 94 | return true; 95 | } 96 | SearchFrame::SearchFrame(const wxString& title, const wxPoint& pos, const wxSize& size) 97 | : wxFrame(NULL, wxID_ANY, title, pos, size, DEFAULT_STYLE) 98 | { 99 | panel = new wxPanel(this, wxID_ANY); 100 | wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); 101 | panel->SetSizer(vbox); 102 | 103 | int textId = NewControlId(); 104 | searchBar = new wxTextCtrl(panel, textId, "", wxDefaultPosition, wxDefaultSize); 105 | vbox->Add(searchBar, 1, wxEXPAND | wxALL, 0); 106 | 107 | wxArrayString choices; 108 | int resultId = NewControlId(); 109 | resultBox = new ResultListView(panel, resultId, wxDefaultPosition, wxSize(MIN_WIDTH, MIN_HEIGHT), wxLC_VIRTUAL | wxLC_REPORT | wxLC_NO_HEADER | wxLC_SINGLE_SEL); 110 | resultBox->InsertColumn(0, "Results", wxLIST_FORMAT_LEFT, wxLIST_AUTOSIZE_USEHEADER); 111 | vbox->Add(resultBox, 5, wxEXPAND | wxALL, 0); 112 | 113 | Bind(wxEVT_CHAR_HOOK, &SearchFrame::OnCharEvent, this, wxID_ANY); 114 | Bind(wxEVT_TEXT, &SearchFrame::OnQueryChange, this, textId); 115 | Bind(wxEVT_LIST_ITEM_ACTIVATED, &SearchFrame::OnItemClickEvent, this, resultId); 116 | 117 | this->SetClientSize(panel->GetBestSize()); 118 | this->CentreOnScreen(); 119 | 120 | // Trigger the first data update 121 | queryCallback("", (void*) this, data); 122 | } 123 | 124 | void SearchFrame::OnCharEvent(wxKeyEvent& event) { 125 | if (event.GetKeyCode() == WXK_ESCAPE) { 126 | Close(true); 127 | }else if(event.GetKeyCode() == WXK_TAB) { 128 | if (wxGetKeyState(WXK_SHIFT)) { 129 | SelectPrevious(); 130 | }else{ 131 | SelectNext(); 132 | } 133 | }else if(event.GetKeyCode() == WXK_DOWN) { 134 | SelectNext(); 135 | }else if(event.GetKeyCode() == WXK_UP) { 136 | SelectPrevious(); 137 | }else if (event.GetKeyCode() == WXK_RETURN) { 138 | Submit(); 139 | }else{ 140 | event.Skip(); 141 | } 142 | } 143 | 144 | void SearchFrame::OnQueryChange(wxCommandEvent& event) { 145 | wxString queryString = searchBar->GetValue(); 146 | const char * query = queryString.ToUTF8(); 147 | queryCallback(query, (void*) this, data); 148 | } 149 | 150 | void SearchFrame::OnItemClickEvent(wxListEvent& event) { 151 | resultBox->Select(event.GetIndex()); 152 | Submit(); 153 | } 154 | 155 | void SearchFrame::SetItems(SearchItem *items, int itemSize) { 156 | wxItems.Clear(); 157 | wxIds.Clear(); 158 | 159 | for (int i = 0; iSetItemCount(itemSize); 168 | 169 | if (itemSize > 0) { 170 | resultBox->RefreshItems(0, itemSize-1); 171 | resultBox->Select(0); 172 | resultBox->EnsureVisible(0); 173 | } 174 | 175 | resultBox->RescaleColumns(); 176 | } 177 | 178 | void SearchFrame::SelectNext() { 179 | if (resultBox->GetItemCount() > 0 && resultBox->GetFirstSelected() != wxNOT_FOUND) { 180 | int newSelected = 0; 181 | if (resultBox->GetFirstSelected() < (resultBox->GetItemCount() - 1)) { 182 | newSelected = resultBox->GetFirstSelected() + 1; 183 | } 184 | 185 | resultBox->Select(newSelected); 186 | resultBox->EnsureVisible(newSelected); 187 | } 188 | } 189 | 190 | void SearchFrame::SelectPrevious() { 191 | if (resultBox->GetItemCount() > 0 && resultBox->GetFirstSelected() != wxNOT_FOUND) { 192 | int newSelected = resultBox->GetItemCount() - 1; 193 | if (resultBox->GetFirstSelected() > 0) { 194 | newSelected = resultBox->GetFirstSelected() - 1; 195 | } 196 | 197 | resultBox->Select(newSelected); 198 | resultBox->EnsureVisible(newSelected); 199 | } 200 | } 201 | 202 | void SearchFrame::Submit() { 203 | if (resultBox->GetItemCount() > 0 && resultBox->GetFirstSelected() != wxNOT_FOUND) { 204 | long index = resultBox->GetFirstSelected(); 205 | wxString id = wxIds[index]; 206 | if (resultCallback) { 207 | resultCallback(id.ToUTF8(), resultData); 208 | } 209 | 210 | Close(true); 211 | } 212 | } 213 | 214 | extern "C" void interop_show_search(SearchMetadata * _metadata, QueryCallback _queryCallback, void *_data, ResultCallback _resultCallback, void *_resultData) { 215 | // Setup high DPI support on Windows 216 | #ifdef __WXMSW__ 217 | SetProcessDPIAware(); 218 | #endif 219 | 220 | searchMetadata = _metadata; 221 | queryCallback = _queryCallback; 222 | resultCallback = _resultCallback; 223 | data = _data; 224 | resultData = _resultData; 225 | 226 | wxApp::SetInstance(new SearchApp()); 227 | int argc = 0; 228 | wxEntry(argc, (char **)nullptr); 229 | } 230 | 231 | extern "C" void update_items(void * app, SearchItem * items, int itemSize) { 232 | SearchFrame * frame = (SearchFrame *) app; 233 | frame->SetItems(items, itemSize); 234 | } -------------------------------------------------------------------------------- /modulo-sys/res/win.manifest: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | TODO 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /modulo-sys/src/form.rs: -------------------------------------------------------------------------------- 1 | use crate::interop::*; 2 | use std::collections::HashMap; 3 | use std::ffi::CStr; 4 | use std::os::raw::c_int; 5 | 6 | // Form schema 7 | 8 | pub mod types { 9 | #[derive(Debug)] 10 | pub struct Form { 11 | pub title: String, 12 | pub icon: Option, 13 | pub fields: Vec, 14 | } 15 | 16 | #[derive(Debug)] 17 | pub struct Field { 18 | pub id: Option, 19 | pub field_type: FieldType, 20 | } 21 | 22 | impl Default for Field { 23 | fn default() -> Self { 24 | Self { 25 | id: None, 26 | field_type: FieldType::Unknown, 27 | } 28 | } 29 | } 30 | 31 | #[derive(Debug)] 32 | pub enum FieldType { 33 | Unknown, 34 | Row(RowMetadata), 35 | Label(LabelMetadata), 36 | Text(TextMetadata), 37 | Choice(ChoiceMetadata), 38 | } 39 | 40 | #[derive(Debug)] 41 | pub struct RowMetadata { 42 | pub fields: Vec, 43 | } 44 | 45 | #[derive(Debug)] 46 | pub struct LabelMetadata { 47 | pub text: String, 48 | } 49 | 50 | #[derive(Debug)] 51 | pub struct TextMetadata { 52 | pub default_text: String, 53 | pub multiline: bool, 54 | } 55 | 56 | #[derive(Debug)] 57 | pub enum ChoiceType { 58 | Dropdown, 59 | List, 60 | } 61 | 62 | #[derive(Debug)] 63 | pub struct ChoiceMetadata { 64 | pub values: Vec, 65 | pub choice_type: ChoiceType, 66 | pub default_value: String, 67 | } 68 | } 69 | 70 | // Form interop 71 | 72 | #[allow(dead_code)] 73 | mod interop { 74 | use super::types; 75 | use crate::interop::*; 76 | use crate::Interoperable; 77 | use std::ffi::{c_void, CString}; 78 | use std::os::raw::{c_char, c_int}; 79 | use std::ptr::null; 80 | 81 | pub(crate) struct OwnedForm { 82 | title: CString, 83 | icon_path: CString, 84 | fields: Vec, 85 | 86 | _metadata: Vec, 87 | _interop: Box, 88 | } 89 | 90 | impl Interoperable for OwnedForm { 91 | fn as_ptr(&self) -> *const c_void { 92 | &(*self._interop) as *const FormMetadata as *const c_void 93 | } 94 | } 95 | 96 | impl From for OwnedForm { 97 | fn from(form: types::Form) -> Self { 98 | let title = CString::new(form.title).expect("unable to convert form title to CString"); 99 | let fields: Vec = 100 | form.fields.into_iter().map(|field| field.into()).collect(); 101 | 102 | let _metadata: Vec = 103 | fields.iter().map(|field| field.metadata()).collect(); 104 | 105 | let icon_path = if let Some(icon_path) = form.icon.as_ref() { 106 | icon_path.clone() 107 | } else { 108 | "".to_owned() 109 | }; 110 | 111 | let icon_path = 112 | CString::new(icon_path).expect("unable to convert form icon to CString"); 113 | 114 | let icon_path_ptr = if form.icon.is_some() { 115 | icon_path.as_ptr() 116 | } else { 117 | std::ptr::null() 118 | }; 119 | 120 | let _interop = Box::new(FormMetadata { 121 | windowTitle: title.as_ptr(), 122 | iconPath: icon_path_ptr, 123 | fields: _metadata.as_ptr(), 124 | fieldSize: fields.len() as c_int, 125 | }); 126 | 127 | Self { 128 | title, 129 | icon_path, 130 | fields, 131 | _metadata, 132 | _interop, 133 | } 134 | } 135 | } 136 | 137 | struct OwnedField { 138 | id: Option, 139 | field_type: FieldType, 140 | specific: Box, 141 | } 142 | 143 | impl From for OwnedField { 144 | fn from(field: types::Field) -> Self { 145 | let id = if let Some(id) = field.id { 146 | Some(CString::new(id).expect("unable to create cstring for field id")) 147 | } else { 148 | None 149 | }; 150 | 151 | let field_type = match field.field_type { 152 | types::FieldType::Row(_) => FieldType_ROW, 153 | types::FieldType::Label(_) => FieldType_LABEL, 154 | types::FieldType::Text(_) => FieldType_TEXT, 155 | types::FieldType::Choice(_) => FieldType_CHOICE, 156 | types::FieldType::Unknown => panic!("unknown field type"), 157 | }; 158 | 159 | // TODO: clean up this match 160 | let specific: Box = match field.field_type { 161 | types::FieldType::Row(metadata) => { 162 | let owned_metadata: OwnedRowMetadata = metadata.into(); 163 | Box::new(owned_metadata) 164 | } 165 | types::FieldType::Label(metadata) => { 166 | let owned_metadata: OwnedLabelMetadata = metadata.into(); 167 | Box::new(owned_metadata) 168 | } 169 | types::FieldType::Text(metadata) => { 170 | let owned_metadata: OwnedTextMetadata = metadata.into(); 171 | Box::new(owned_metadata) 172 | } 173 | types::FieldType::Choice(metadata) => { 174 | let owned_metadata: OwnedChoiceMetadata = metadata.into(); 175 | Box::new(owned_metadata) 176 | } 177 | types::FieldType::Unknown => panic!("unknown field type"), 178 | }; 179 | 180 | Self { 181 | id, 182 | field_type, 183 | specific, 184 | } 185 | } 186 | } 187 | 188 | impl OwnedField { 189 | pub fn metadata(&self) -> FieldMetadata { 190 | let id_ptr = if let Some(id) = self.id.as_ref() { 191 | id.as_ptr() 192 | } else { 193 | null() 194 | }; 195 | 196 | FieldMetadata { 197 | id: id_ptr, 198 | fieldType: self.field_type, 199 | specific: self.specific.as_ptr(), 200 | } 201 | } 202 | } 203 | 204 | struct OwnedLabelMetadata { 205 | text: CString, 206 | _interop: Box, 207 | } 208 | 209 | impl Interoperable for OwnedLabelMetadata { 210 | fn as_ptr(&self) -> *const c_void { 211 | &(*self._interop) as *const LabelMetadata as *const c_void 212 | } 213 | } 214 | 215 | impl From for OwnedLabelMetadata { 216 | fn from(label_metadata: types::LabelMetadata) -> Self { 217 | let text = 218 | CString::new(label_metadata.text).expect("unable to convert label text to CString"); 219 | let _interop = Box::new(LabelMetadata { 220 | text: text.as_ptr(), 221 | }); 222 | Self { text, _interop } 223 | } 224 | } 225 | 226 | struct OwnedTextMetadata { 227 | default_text: CString, 228 | _interop: Box, 229 | } 230 | 231 | impl Interoperable for OwnedTextMetadata { 232 | fn as_ptr(&self) -> *const c_void { 233 | &(*self._interop) as *const TextMetadata as *const c_void 234 | } 235 | } 236 | 237 | impl From for OwnedTextMetadata { 238 | fn from(text_metadata: types::TextMetadata) -> Self { 239 | let default_text = CString::new(text_metadata.default_text) 240 | .expect("unable to convert default text to CString"); 241 | let _interop = Box::new(TextMetadata { 242 | defaultText: default_text.as_ptr(), 243 | multiline: if text_metadata.multiline { 1 } else { 0 }, 244 | }); 245 | Self { 246 | default_text, 247 | _interop, 248 | } 249 | } 250 | } 251 | 252 | struct OwnedChoiceMetadata { 253 | values: Vec, 254 | values_ptr_array: Vec<*const c_char>, 255 | default_value: CString, 256 | _interop: Box, 257 | } 258 | 259 | impl Interoperable for OwnedChoiceMetadata { 260 | fn as_ptr(&self) -> *const c_void { 261 | &(*self._interop) as *const ChoiceMetadata as *const c_void 262 | } 263 | } 264 | 265 | impl From for OwnedChoiceMetadata { 266 | fn from(metadata: types::ChoiceMetadata) -> Self { 267 | let values: Vec = metadata 268 | .values 269 | .into_iter() 270 | .map(|value| CString::new(value).expect("unable to convert choice value to string")) 271 | .collect(); 272 | 273 | let values_ptr_array: Vec<*const c_char> = 274 | values.iter().map(|value| value.as_ptr()).collect(); 275 | 276 | let choice_type = match metadata.choice_type { 277 | types::ChoiceType::Dropdown => ChoiceType_DROPDOWN, 278 | types::ChoiceType::List => ChoiceType_LIST, 279 | }; 280 | 281 | let default_value = CString::new(metadata.default_value) 282 | .expect("unable to convert default value to CString"); 283 | 284 | let _interop = Box::new(ChoiceMetadata { 285 | values: values_ptr_array.as_ptr(), 286 | valueSize: values.len() as c_int, 287 | choiceType: choice_type, 288 | defaultValue: default_value.as_ptr(), 289 | }); 290 | Self { 291 | values, 292 | values_ptr_array, 293 | default_value, 294 | _interop, 295 | } 296 | } 297 | } 298 | 299 | struct OwnedRowMetadata { 300 | fields: Vec, 301 | 302 | _metadata: Vec, 303 | _interop: Box, 304 | } 305 | 306 | impl Interoperable for OwnedRowMetadata { 307 | fn as_ptr(&self) -> *const c_void { 308 | &(*self._interop) as *const RowMetadata as *const c_void 309 | } 310 | } 311 | 312 | impl From for OwnedRowMetadata { 313 | fn from(row_metadata: types::RowMetadata) -> Self { 314 | let fields: Vec = row_metadata 315 | .fields 316 | .into_iter() 317 | .map(|field| field.into()) 318 | .collect(); 319 | 320 | let _metadata: Vec = 321 | fields.iter().map(|field| field.metadata()).collect(); 322 | 323 | let _interop = Box::new(RowMetadata { 324 | fields: _metadata.as_ptr(), 325 | fieldSize: _metadata.len() as c_int, 326 | }); 327 | 328 | Self { 329 | fields, 330 | _metadata, 331 | _interop, 332 | } 333 | } 334 | } 335 | } 336 | 337 | pub fn show(form: types::Form) -> HashMap { 338 | use crate::Interoperable; 339 | use std::os::raw::{c_char, c_void}; 340 | 341 | let owned_form: interop::OwnedForm = form.into(); 342 | let metadata: *const FormMetadata = owned_form.as_ptr() as *const FormMetadata; 343 | 344 | let mut value_map: HashMap = HashMap::new(); 345 | 346 | extern "C" fn callback( 347 | values: *const crate::interop::ValuePair, 348 | size: c_int, 349 | map: *mut c_void, 350 | ) { 351 | let values: &[crate::interop::ValuePair] = 352 | unsafe { std::slice::from_raw_parts(values, size as usize) }; 353 | let map = map as *mut HashMap; 354 | let map = unsafe { &mut (*map) }; 355 | for pair in values.iter() { 356 | unsafe { 357 | let id = CStr::from_ptr(pair.id); 358 | let value = CStr::from_ptr(pair.value); 359 | 360 | let id = id.to_string_lossy().to_string(); 361 | let value = value.to_string_lossy().to_string(); 362 | map.insert(id, value); 363 | } 364 | } 365 | } 366 | 367 | unsafe { 368 | // TODO: Nested rows should fail, add check 369 | crate::interop::interop_show_form( 370 | metadata, 371 | callback, 372 | &mut value_map as *mut HashMap as *mut c_void, 373 | ); 374 | } 375 | 376 | value_map 377 | } 378 | -------------------------------------------------------------------------------- /modulo-sys/src/interop.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_upper_case_globals)] 2 | #![allow(non_camel_case_types)] 3 | #![allow(non_snake_case)] 4 | include!(concat!(env!("OUT_DIR"), "/bindings.rs")); 5 | 6 | use std::os::raw::{c_char, c_int, c_void}; 7 | 8 | // Native bindings 9 | 10 | #[allow(improper_ctypes)] 11 | #[link(name = "modulosys", kind = "static")] 12 | extern "C" { 13 | // FORM 14 | pub(crate) fn interop_show_form( 15 | metadata: *const FormMetadata, 16 | callback: extern "C" fn(values: *const ValuePair, size: c_int, map: *mut c_void), 17 | map: *mut c_void, 18 | ); 19 | 20 | // SEARCH 21 | pub(crate) fn interop_show_search( 22 | metadata: *const SearchMetadata, 23 | search_callback: extern "C" fn( 24 | query: *const c_char, 25 | app: *const c_void, 26 | data: *const c_void, 27 | ), 28 | items: *const c_void, 29 | result_callback: extern "C" fn(id: *const c_char, result: *mut c_void), 30 | result: *mut c_void, 31 | ); 32 | 33 | pub(crate) fn update_items(app: *const c_void, items: *const SearchItem, itemCount: c_int); 34 | } 35 | -------------------------------------------------------------------------------- /modulo-sys/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod form; 2 | pub(crate) mod interop; 3 | pub mod search; 4 | 5 | use std::ffi::c_void; 6 | 7 | pub(crate) trait Interoperable { 8 | fn as_ptr(&self) -> *const c_void; 9 | } 10 | -------------------------------------------------------------------------------- /modulo-sys/src/search.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | use std::ffi::{CStr, CString}; 3 | use std::os::raw::{c_char, c_int, c_void}; 4 | 5 | pub mod types { 6 | #[derive(Debug)] 7 | pub struct SearchItem { 8 | pub id: String, 9 | pub label: String, 10 | //TODO pub search_text: String, 11 | } 12 | 13 | #[derive(Debug)] 14 | pub struct Search { 15 | pub title: String, 16 | pub icon: Option, 17 | pub items: Vec, 18 | } 19 | } 20 | 21 | #[allow(dead_code)] 22 | mod interop { 23 | use super::types; 24 | use crate::interop::*; 25 | use crate::Interoperable; 26 | use std::ffi::{c_void, CString}; 27 | use std::os::raw::{c_char, c_int}; 28 | use std::ptr::null; 29 | 30 | pub(crate) struct OwnedSearch { 31 | title: CString, 32 | icon_path: CString, 33 | items: Vec, 34 | pub(crate) interop_items: Vec, 35 | _interop: Box, 36 | } 37 | 38 | impl Interoperable for OwnedSearch { 39 | fn as_ptr(&self) -> *const c_void { 40 | &(*self._interop) as *const SearchMetadata as *const c_void 41 | } 42 | } 43 | 44 | impl From<&types::Search> for OwnedSearch { 45 | fn from(search: &types::Search) -> Self { 46 | let title = CString::new(search.title.clone()) 47 | .expect("unable to convert search title to CString"); 48 | 49 | let items: Vec = search.items.iter().map(|item| item.into()).collect(); 50 | 51 | let interop_items: Vec = 52 | items.iter().map(|item| item.to_search_item()).collect(); 53 | 54 | let icon_path = if let Some(icon_path) = search.icon.as_ref() { 55 | icon_path.clone() 56 | } else { 57 | "".to_owned() 58 | }; 59 | 60 | let icon_path = 61 | CString::new(icon_path).expect("unable to convert search icon to CString"); 62 | 63 | let icon_path_ptr = if search.icon.is_some() { 64 | icon_path.as_ptr() 65 | } else { 66 | std::ptr::null() 67 | }; 68 | 69 | let _interop = Box::new(SearchMetadata { 70 | iconPath: icon_path_ptr, 71 | windowTitle: title.as_ptr(), 72 | }); 73 | 74 | Self { 75 | title, 76 | items, 77 | icon_path, 78 | interop_items, 79 | _interop, 80 | } 81 | } 82 | } 83 | 84 | pub(crate) struct OwnedSearchItem { 85 | id: CString, 86 | label: CString, 87 | } 88 | 89 | impl OwnedSearchItem { 90 | fn to_search_item(&self) -> SearchItem { 91 | SearchItem { 92 | id: self.id.as_ptr(), 93 | label: self.label.as_ptr(), 94 | } 95 | } 96 | } 97 | 98 | impl From<&types::SearchItem> for OwnedSearchItem { 99 | fn from(item: &types::SearchItem) -> Self { 100 | let id = CString::new(item.id.clone()).expect("unable to convert item id to CString"); 101 | let label = 102 | CString::new(item.label.clone()).expect("unable to convert item label to CString"); 103 | 104 | Self { id, label } 105 | } 106 | } 107 | } 108 | 109 | struct SearchData { 110 | owned_search: interop::OwnedSearch, 111 | items: Vec, 112 | algorithm: Box) -> Vec>, 113 | } 114 | 115 | pub fn show( 116 | search: types::Search, 117 | algorithm: Box) -> Vec>, 118 | ) -> Option { 119 | use crate::interop::SearchMetadata; 120 | use crate::Interoperable; 121 | 122 | let owned_search: interop::OwnedSearch = (&search).into(); 123 | let metadata: *const SearchMetadata = owned_search.as_ptr() as *const SearchMetadata; 124 | 125 | let search_data = SearchData { 126 | owned_search, 127 | items: search.items, 128 | algorithm, 129 | }; 130 | 131 | extern "C" fn search_callback(query: *const c_char, app: *const c_void, data: *const c_void) { 132 | let query = unsafe { CStr::from_ptr(query) }; 133 | let query = query.to_string_lossy().to_string(); 134 | 135 | let search_data = data as *const SearchData; 136 | let search_data = unsafe { &*search_data }; 137 | 138 | let indexes = (*search_data.algorithm)(&query, &search_data.items); 139 | let items: Vec = indexes 140 | .into_iter() 141 | .map(|index| search_data.owned_search.interop_items[index]) 142 | .collect(); 143 | 144 | unsafe { 145 | crate::interop::update_items(app, items.as_ptr(), items.len() as c_int); 146 | } 147 | }; 148 | 149 | let mut result: Option = None; 150 | 151 | extern "C" fn result_callback(id: *const c_char, result: *mut c_void) { 152 | let id = unsafe { CStr::from_ptr(id) }; 153 | let id = id.to_string_lossy().to_string(); 154 | let result: *mut Option = result as *mut Option; 155 | unsafe { 156 | *result = Some(id); 157 | } 158 | } 159 | 160 | unsafe { 161 | crate::interop::interop_show_search( 162 | metadata, 163 | search_callback, 164 | &search_data as *const SearchData as *const c_void, 165 | result_callback, 166 | &mut result as *mut Option as *mut c_void, 167 | ); 168 | } 169 | 170 | println!("{:?}", result); 171 | 172 | result 173 | } 174 | -------------------------------------------------------------------------------- /modulo/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "modulo" 3 | version = "0.1.1" 4 | authors = ["Federico Terzi "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | modulo-sys = { path = "../modulo-sys" } 9 | lazy_static = "1.4.0" 10 | regex = "1.3.9" 11 | serde = { version = "1.0.114", features = ["derive"]} 12 | serde_json = "1.0.56" 13 | serde_yaml = "0.8.13" 14 | clap = "2.33.1" -------------------------------------------------------------------------------- /modulo/src/form/config.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Deserializer, Serialize}; 2 | use std::collections::HashMap; 3 | 4 | fn default_title() -> String { 5 | "modulo".to_owned() 6 | } 7 | 8 | fn default_icon() -> Option { 9 | None 10 | } 11 | 12 | fn default_fields() -> HashMap { 13 | HashMap::new() 14 | } 15 | 16 | #[derive(Debug, Serialize, Deserialize, Clone)] 17 | pub struct FormConfig { 18 | #[serde(default = "default_title")] 19 | pub title: String, 20 | 21 | #[serde(default = "default_icon")] 22 | pub icon: Option, 23 | 24 | pub layout: String, 25 | 26 | #[serde(default = "default_fields")] 27 | pub fields: HashMap, 28 | } 29 | 30 | #[derive(Debug, Serialize, Clone)] 31 | pub struct FieldConfig { 32 | pub field_type: FieldTypeConfig, 33 | } 34 | 35 | impl Default for FieldConfig { 36 | fn default() -> Self { 37 | Self { 38 | field_type: FieldTypeConfig::Text(TextFieldConfig { 39 | ..Default::default() 40 | }), 41 | } 42 | } 43 | } 44 | 45 | #[derive(Debug, Serialize, Deserialize, Clone)] 46 | pub enum FieldTypeConfig { 47 | Text(TextFieldConfig), 48 | Choice(ChoiceFieldConfig), 49 | List(ListFieldConfig), 50 | } 51 | 52 | #[derive(Debug, Serialize, Deserialize, Clone)] 53 | pub struct TextFieldConfig { 54 | pub default: String, 55 | pub multiline: bool, 56 | } 57 | 58 | impl Default for TextFieldConfig { 59 | fn default() -> Self { 60 | Self { 61 | default: "".to_owned(), 62 | multiline: false, 63 | } 64 | } 65 | } 66 | 67 | #[derive(Debug, Serialize, Deserialize, Clone)] 68 | pub struct ChoiceFieldConfig { 69 | pub values: Vec, 70 | pub default: String, 71 | } 72 | 73 | impl Default for ChoiceFieldConfig { 74 | fn default() -> Self { 75 | Self { 76 | values: Vec::new(), 77 | default: "".to_owned(), 78 | } 79 | } 80 | } 81 | 82 | #[derive(Debug, Serialize, Deserialize, Clone)] 83 | pub struct ListFieldConfig { 84 | pub values: Vec, 85 | pub default: String, 86 | } 87 | 88 | impl Default for ListFieldConfig { 89 | fn default() -> Self { 90 | Self { 91 | values: Vec::new(), 92 | default: "".to_owned(), 93 | } 94 | } 95 | } 96 | 97 | impl<'de> serde::Deserialize<'de> for FieldConfig { 98 | fn deserialize(deserializer: D) -> Result 99 | where 100 | D: Deserializer<'de>, 101 | { 102 | let auto_field = AutoFieldConfig::deserialize(deserializer)?; 103 | Ok(FieldConfig::from(&auto_field)) 104 | } 105 | } 106 | 107 | impl<'a> From<&'a AutoFieldConfig> for FieldConfig { 108 | fn from(other: &'a AutoFieldConfig) -> Self { 109 | let field_type = match other.field_type.as_ref() { 110 | "text" => { 111 | let mut config: TextFieldConfig = Default::default(); 112 | 113 | if let Some(default) = &other.default { 114 | config.default = default.clone(); 115 | } 116 | 117 | config.multiline = other.multiline; 118 | 119 | FieldTypeConfig::Text(config) 120 | } 121 | "choice" => { 122 | let mut config = ChoiceFieldConfig { 123 | values: other.values.clone(), 124 | ..Default::default() 125 | }; 126 | 127 | if let Some(default) = &other.default { 128 | config.default = default.clone(); 129 | } 130 | 131 | FieldTypeConfig::Choice(config) 132 | } 133 | "list" => { 134 | let mut config = ListFieldConfig { 135 | values: other.values.clone(), 136 | ..Default::default() 137 | }; 138 | 139 | if let Some(default) = &other.default { 140 | config.default = default.clone(); 141 | } 142 | 143 | FieldTypeConfig::List(config) 144 | } 145 | _ => { 146 | panic!("invalid field type: {}", other.field_type); 147 | } 148 | }; 149 | 150 | Self { field_type } 151 | } 152 | } 153 | 154 | fn default_type() -> String { 155 | "text".to_owned() 156 | } 157 | 158 | fn default_default() -> Option { 159 | None 160 | } 161 | 162 | fn default_multiline() -> bool { 163 | false 164 | } 165 | 166 | fn default_values() -> Vec { 167 | Vec::new() 168 | } 169 | 170 | #[derive(Debug, Serialize, Deserialize, Clone)] 171 | pub struct AutoFieldConfig { 172 | #[serde(rename = "type", default = "default_type")] 173 | pub field_type: String, 174 | 175 | #[serde(default = "default_default")] 176 | pub default: Option, 177 | 178 | #[serde(default = "default_multiline")] 179 | pub multiline: bool, 180 | 181 | #[serde(default = "default_values")] 182 | pub values: Vec, 183 | } 184 | -------------------------------------------------------------------------------- /modulo/src/form/generator.rs: -------------------------------------------------------------------------------- 1 | use super::config::{FieldConfig, FieldTypeConfig, FormConfig}; 2 | use super::parser::layout::Token; 3 | use modulo_sys::form::types::*; 4 | use std::collections::HashMap; 5 | 6 | pub fn generate(config: FormConfig) -> Form { 7 | let structure = super::parser::layout::parse_layout(&config.layout); 8 | build_form(config, structure) 9 | } 10 | 11 | fn create_field(token: &Token, field_map: &HashMap) -> Field { 12 | match token { 13 | Token::Text(text) => Field { 14 | field_type: FieldType::Label(LabelMetadata { text: text.clone() }), 15 | ..Default::default() 16 | }, 17 | Token::Field(name) => { 18 | let config = if let Some(config) = field_map.get(name) { 19 | config.clone() 20 | } else { 21 | Default::default() 22 | }; 23 | 24 | let field_type = match &config.field_type { 25 | FieldTypeConfig::Text(config) => FieldType::Text(TextMetadata { 26 | default_text: config.default.clone(), 27 | multiline: config.multiline, 28 | }), 29 | FieldTypeConfig::Choice(config) => FieldType::Choice(ChoiceMetadata { 30 | values: config.values.clone(), 31 | choice_type: ChoiceType::Dropdown, 32 | default_value: config.default.clone(), 33 | }), 34 | FieldTypeConfig::List(config) => FieldType::Choice(ChoiceMetadata { 35 | values: config.values.clone(), 36 | choice_type: ChoiceType::List, 37 | default_value: config.default.clone(), 38 | }), 39 | }; 40 | 41 | Field { 42 | id: Some(name.clone()), 43 | field_type, 44 | ..Default::default() 45 | } 46 | } 47 | } 48 | } 49 | 50 | fn build_form(form: FormConfig, structure: Vec>) -> Form { 51 | let field_map = form.fields; 52 | let mut fields = Vec::new(); 53 | 54 | for row in structure.iter() { 55 | let current_field = if row.len() == 1 { 56 | // Single field 57 | create_field(&row[0], &field_map) 58 | } else { 59 | // Row field 60 | let inner_fields = row 61 | .iter() 62 | .map(|token| create_field(token, &field_map)) 63 | .collect(); 64 | 65 | Field { 66 | field_type: FieldType::Row(RowMetadata { 67 | fields: inner_fields, 68 | }), 69 | ..Default::default() 70 | } 71 | }; 72 | 73 | fields.push(current_field) 74 | } 75 | 76 | Form { 77 | title: form.title, 78 | icon: form.icon, 79 | fields, 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /modulo/src/form/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod config; 2 | pub mod generator; 3 | pub mod parser; 4 | -------------------------------------------------------------------------------- /modulo/src/form/parser/layout.rs: -------------------------------------------------------------------------------- 1 | use super::split::*; 2 | use regex::Regex; 3 | 4 | lazy_static! { 5 | static ref FIELD_REGEX: Regex = Regex::new(r"\{\{(.*?)\}\}").unwrap(); 6 | } 7 | 8 | #[derive(Debug, Clone, PartialEq)] 9 | pub enum Token { 10 | Text(String), // Text 11 | Field(String), // id: String 12 | } 13 | 14 | pub fn parse_layout(layout: &str) -> Vec> { 15 | let mut rows = Vec::new(); 16 | 17 | for line in layout.lines() { 18 | let line = line.trim(); 19 | 20 | // Skip empty lines 21 | if line.is_empty() { 22 | continue; 23 | } 24 | 25 | let mut row: Vec = Vec::new(); 26 | 27 | let splitter = SplitCaptures::new(&FIELD_REGEX, line); 28 | 29 | // Get the individual tokens 30 | for state in splitter { 31 | match state { 32 | SplitState::Unmatched(text) => { 33 | if !text.is_empty() { 34 | row.push(Token::Text(text.to_owned())) 35 | } 36 | } 37 | SplitState::Captured(caps) => { 38 | if let Some(name) = caps.get(1) { 39 | let name = name.as_str().to_owned(); 40 | row.push(Token::Field(name)); 41 | } 42 | } 43 | } 44 | } 45 | 46 | rows.push(row); 47 | } 48 | 49 | rows 50 | } 51 | 52 | #[cfg(test)] 53 | mod tests { 54 | use super::*; 55 | 56 | #[test] 57 | fn test_parse_layout() { 58 | let layout = "Hey {{name}},\nHow are you?\n \nCheers"; 59 | let result = parse_layout(layout); 60 | assert_eq!( 61 | result, 62 | vec![ 63 | vec![ 64 | Token::Text("Hey ".to_owned()), 65 | Token::Field("name".to_owned()), 66 | Token::Text(",".to_owned()) 67 | ], 68 | vec![Token::Text("How are you?".to_owned())], 69 | vec![Token::Text("Cheers".to_owned())], 70 | ] 71 | ); 72 | } 73 | 74 | #[test] 75 | fn test_parse_layout_2() { 76 | let layout = "Hey {{name}} {{surname}},"; 77 | let result = parse_layout(layout); 78 | assert_eq!( 79 | result, 80 | vec![vec![ 81 | Token::Text("Hey ".to_owned()), 82 | Token::Field("name".to_owned()), 83 | Token::Text(" ".to_owned()), 84 | Token::Field("surname".to_owned()), 85 | Token::Text(",".to_owned()) 86 | ],] 87 | ); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /modulo/src/form/parser/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod layout; 2 | mod split; 3 | -------------------------------------------------------------------------------- /modulo/src/form/parser/split.rs: -------------------------------------------------------------------------------- 1 | // Taken from: https://github.com/rust-lang/regex/issues/330#issuecomment-274058261 2 | use regex::{CaptureMatches, Captures, Regex}; 3 | 4 | pub struct SplitCaptures<'r, 't> { 5 | finder: CaptureMatches<'r, 't>, 6 | text: &'t str, 7 | last: usize, 8 | caps: Option>, 9 | } 10 | 11 | impl<'r, 't> SplitCaptures<'r, 't> { 12 | pub fn new(re: &'r Regex, text: &'t str) -> SplitCaptures<'r, 't> { 13 | SplitCaptures { 14 | finder: re.captures_iter(text), 15 | text: text, 16 | last: 0, 17 | caps: None, 18 | } 19 | } 20 | } 21 | 22 | #[derive(Debug)] 23 | pub enum SplitState<'t> { 24 | Unmatched(&'t str), 25 | Captured(Captures<'t>), 26 | } 27 | 28 | impl<'r, 't> Iterator for SplitCaptures<'r, 't> { 29 | type Item = SplitState<'t>; 30 | 31 | fn next(&mut self) -> Option> { 32 | if let Some(caps) = self.caps.take() { 33 | return Some(SplitState::Captured(caps)); 34 | } 35 | match self.finder.next() { 36 | None => { 37 | if self.last >= self.text.len() { 38 | None 39 | } else { 40 | let s = &self.text[self.last..]; 41 | self.last = self.text.len(); 42 | Some(SplitState::Unmatched(s)) 43 | } 44 | } 45 | Some(caps) => { 46 | let m = caps.get(0).unwrap(); 47 | let unmatched = &self.text[self.last..m.start()]; 48 | self.last = m.end(); 49 | self.caps = Some(caps); 50 | Some(SplitState::Unmatched(unmatched)) 51 | } 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /modulo/src/main.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate lazy_static; 3 | use clap::{crate_version, App, Arg, ArgMatches, SubCommand}; 4 | 5 | mod form; 6 | mod search; 7 | 8 | fn main() { 9 | let matches = App::new("modulo") 10 | .version(crate_version!()) 11 | .author("Federico Terzi ") 12 | .about("TODO") // TODO 13 | .subcommand( 14 | SubCommand::with_name("form") 15 | .about("Display a customizable form") 16 | .arg( 17 | Arg::with_name("input_file") 18 | .short("i") 19 | .takes_value(true) 20 | .help("Input file or - for stdin"), 21 | ) 22 | .arg( 23 | Arg::with_name("json") 24 | .short("j") 25 | .required(false) 26 | .takes_value(false) 27 | .help("Interpret the input data as JSON"), 28 | ), 29 | ) 30 | .subcommand( 31 | SubCommand::with_name("search") 32 | .about("Display a search box") 33 | .arg( 34 | Arg::with_name("input_file") 35 | .short("i") 36 | .takes_value(true) 37 | .help("Input file or - for stdin"), 38 | ) 39 | .arg( 40 | Arg::with_name("json") 41 | .short("j") 42 | .required(false) 43 | .takes_value(false) 44 | .help("Interpret the input data as JSON"), 45 | ), 46 | ) 47 | .get_matches(); 48 | 49 | if let Some(matches) = matches.subcommand_matches("form") { 50 | form_main(matches); 51 | return; 52 | } 53 | 54 | if let Some(matches) = matches.subcommand_matches("search") { 55 | search_main(matches); 56 | return; 57 | } 58 | } 59 | 60 | fn form_main(matches: &ArgMatches) { 61 | let as_json: bool = matches.is_present("json"); 62 | 63 | let input_file = matches 64 | .value_of("input_file") 65 | .expect("missing input, please specify the -i option"); 66 | let data = if input_file == "-" { 67 | use std::io::Read; 68 | let mut buffer = String::new(); 69 | std::io::stdin() 70 | .read_to_string(&mut buffer) 71 | .expect("unable to obtain input from stdin"); 72 | buffer 73 | } else { 74 | let data = std::fs::read_to_string(input_file).expect("unable to read input file"); 75 | data 76 | }; 77 | 78 | let config: form::config::FormConfig = if !as_json { 79 | serde_yaml::from_str(&data).expect("unable to parse form configuration") 80 | } else { 81 | serde_json::from_str(&data).expect("unable to parse form configuration") 82 | }; 83 | 84 | let form = form::generator::generate(config); 85 | let values = modulo_sys::form::show(form); 86 | 87 | let output = serde_json::to_string(&values).expect("unable to encode values as JSON"); 88 | println!("{}", output); 89 | } 90 | 91 | fn search_main(matches: &ArgMatches) { 92 | let as_json: bool = matches.is_present("json"); 93 | 94 | let input_file = matches 95 | .value_of("input_file") 96 | .expect("missing input, please specify the -i option"); 97 | let data = if input_file == "-" { 98 | use std::io::Read; 99 | let mut buffer = String::new(); 100 | std::io::stdin() 101 | .read_to_string(&mut buffer) 102 | .expect("unable to obtain input from stdin"); 103 | buffer 104 | } else { 105 | let data = std::fs::read_to_string(input_file).expect("unable to read input file"); 106 | data 107 | }; 108 | 109 | let config: search::config::SearchConfig = if !as_json { 110 | serde_yaml::from_str(&data).expect("unable to parse search configuration") 111 | } else { 112 | serde_json::from_str(&data).expect("unable to parse search configuration") 113 | }; 114 | 115 | let algorithm = search::algorithm::get_algorithm(&config.algorithm); 116 | 117 | let search = search::generator::generate(config); 118 | let result = modulo_sys::search::show(search, algorithm); 119 | 120 | //let output = serde_json::to_string(&values).expect("unable to encode values as JSON"); 121 | //println!("{}", output); 122 | } 123 | -------------------------------------------------------------------------------- /modulo/src/search/algorithm.rs: -------------------------------------------------------------------------------- 1 | use modulo_sys::search::types::SearchItem; 2 | 3 | pub fn get_algorithm(name: &str) -> Box) -> Vec> { 4 | match name { 5 | "exact" => Box::new(exact_match), 6 | "iexact" => Box::new(case_insensitive_exact_match), 7 | "ikey" => Box::new(case_insensitive_keyword), 8 | _ => panic!("unknown search algorithm: {}", name), 9 | } 10 | } 11 | 12 | fn exact_match(query: &str, items: &Vec) -> Vec { 13 | items 14 | .iter() 15 | .enumerate() 16 | .filter(|(_, item)| item.label.contains(query)) 17 | .map(|(i, _)| i) 18 | .collect() 19 | } 20 | 21 | fn case_insensitive_exact_match(query: &str, items: &Vec) -> Vec { 22 | let lowercase_query = query.to_lowercase(); 23 | items 24 | .iter() 25 | .enumerate() 26 | .filter(|(_, item)| item.label.to_lowercase().contains(&lowercase_query)) 27 | .map(|(i, _)| i) 28 | .collect() 29 | } 30 | 31 | fn case_insensitive_keyword(query: &str, items: &Vec) -> Vec { 32 | let lowercase_query = query.to_lowercase(); 33 | let keywords: Vec<&str> = lowercase_query.split_whitespace().into_iter().collect(); 34 | items 35 | .iter() 36 | .enumerate() 37 | .filter(|(_, item)| { 38 | for keyword in keywords.iter() { 39 | if !item.label.to_lowercase().contains(keyword) { 40 | return false; 41 | } 42 | } 43 | 44 | true 45 | }) 46 | .map(|(i, _)| i) 47 | .collect() 48 | } 49 | -------------------------------------------------------------------------------- /modulo/src/search/config.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Deserializer, Serialize}; 2 | 3 | fn default_title() -> String { 4 | "modulo".to_owned() 5 | } 6 | 7 | fn default_icon() -> Option { 8 | None 9 | } 10 | 11 | fn default_items() -> Vec { 12 | Vec::new() 13 | } 14 | 15 | fn default_algorithm() -> String { 16 | "ikey".to_owned() 17 | } 18 | 19 | #[derive(Debug, Serialize, Deserialize, Clone)] 20 | pub struct SearchConfig { 21 | #[serde(default = "default_title")] 22 | pub title: String, 23 | 24 | #[serde(default = "default_icon")] 25 | pub icon: Option, 26 | 27 | #[serde(default = "default_items")] 28 | pub items: Vec, 29 | 30 | #[serde(default = "default_algorithm")] 31 | pub algorithm: String, 32 | } 33 | 34 | #[derive(Debug, Serialize, Deserialize, Clone)] 35 | pub struct SearchItem { 36 | pub id: String, 37 | pub label: String, 38 | } 39 | -------------------------------------------------------------------------------- /modulo/src/search/generator.rs: -------------------------------------------------------------------------------- 1 | use crate::search::config::SearchConfig; 2 | use modulo_sys::search::types; 3 | 4 | pub fn generate(config: SearchConfig) -> types::Search { 5 | let items = config 6 | .items 7 | .into_iter() 8 | .map(|item| types::SearchItem { 9 | id: item.id, 10 | label: item.label, 11 | }) 12 | .collect(); 13 | 14 | types::Search { 15 | title: config.title, 16 | items, 17 | icon: config.icon, 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /modulo/src/search/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod algorithm; 2 | pub mod config; 3 | pub mod generator; 4 | -------------------------------------------------------------------------------- /packaging/linux/icon.svg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/federico-terzi/modulo/b4f6d2c032ca75face8c078583b3a3dd641f93ab/packaging/linux/icon.svg -------------------------------------------------------------------------------- /packaging/linux/modulo.desktop: -------------------------------------------------------------------------------- 1 | [Desktop Entry] 2 | Name=modulo 3 | Exec=modulo 4 | Icon=icon 5 | Type=Application 6 | Categories=Utility; -------------------------------------------------------------------------------- /packaging/shasum.py: -------------------------------------------------------------------------------- 1 | import sys, glob, os 2 | import hashlib 3 | 4 | # BUF_SIZE is totally arbitrary, change for your app! 5 | BUF_SIZE = 65536 # lets read stuff in 64kb chunks! 6 | 7 | dirname = sys.argv[1] 8 | 9 | for n in glob.glob(dirname+"/*"): 10 | sha1 = hashlib.sha256() 11 | 12 | with open(n, 'rb') as f: 13 | while True: 14 | data = f.read(BUF_SIZE) 15 | if not data: 16 | break 17 | sha1.update(data) 18 | 19 | h = str(sha1.hexdigest()) 20 | 21 | print(n + " -> " + h) 22 | 23 | newfilename = os.path.basename(n) + ".sha256.txt" 24 | 25 | with open(os.path.join(dirname, newfilename), "w") as k: 26 | k.write(h) --------------------------------------------------------------------------------