├── .gitignore ├── CMakeLists.txt ├── COPYING ├── README.md ├── license.txt ├── maim.1 ├── modules ├── FindGLM.cmake ├── FindGLX.cmake ├── FindSLOP.cmake ├── FindWebP.cmake ├── FindXComposite.cmake ├── FindXFixes.cmake ├── FindXRandr.cmake └── FindXRender.cmake └── src ├── cxxopts.hpp ├── image.cpp ├── image.hpp ├── main.cpp ├── x.cpp └── x.hpp /.gitignore: -------------------------------------------------------------------------------- 1 | # These files are ignored since cmake generates them from cmdline.in 2 | src/cmdline.h 3 | 4 | # Ignore Cmake generated files 5 | CMakeFiles/* 6 | Makefile 7 | cmake_install.cmake 8 | CMakeCache.txt 9 | 10 | # Ignore output artifacts 11 | bin/maim 12 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required( VERSION 3.5.0 ) 2 | 3 | project(maim VERSION 5.8.0 LANGUAGES CXX) 4 | 5 | if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) 6 | set(CMAKE_INSTALL_PREFIX "/usr" CACHE PATH "..." FORCE) 7 | endif() 8 | 9 | include(GNUInstallDirs) 10 | 11 | add_definitions(-DMAIM_VERSION="v${PROJECT_VERSION}") 12 | 13 | set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/bin/") 14 | 15 | # Sources 16 | set( source 17 | src/x.cpp 18 | src/image.cpp 19 | src/main.cpp ) 20 | 21 | set( BIN_TARGET "${PROJECT_NAME}" ) 22 | 23 | # Executable 24 | add_executable( "${BIN_TARGET}" ${source} ) 25 | 26 | # Obtain library paths and make sure they exist. 27 | set( CMAKE_MODULE_PATH "${CMAKE_MODULE_PATH}" "${CMAKE_SOURCE_DIR}/modules" ) 28 | find_package( PNG REQUIRED ) 29 | find_package( JPEG REQUIRED ) 30 | find_package( WebP REQUIRED ) 31 | find_package( XRandr REQUIRED ) 32 | find_package( XRender REQUIRED ) 33 | find_package( XFixes REQUIRED ) 34 | find_package( XComposite REQUIRED ) 35 | find_package( X11 REQUIRED ) 36 | find_package( SLOP REQUIRED ) 37 | find_package( Threads REQUIRED ) 38 | find_package( GLM REQUIRED ) 39 | 40 | set_property(TARGET ${BIN_TARGET} PROPERTY CXX_STANDARD_REQUIRED ON) 41 | set_property(TARGET ${BIN_TARGET} PROPERTY CXX_STANDARD 17) 42 | set_property(TARGET ${BIN_TARGET} PROPERTY CXX_EXTENSIONS OFF) 43 | 44 | # Includes 45 | include_directories( ${XRANDR_INCLUDE_DIR} 46 | ${X11_INCLUDE_DIR} 47 | ${SLOP_INCLUDE_DIR} 48 | ${GLM_INCLUDE_DIR} 49 | ${XFIXES_INCLUDE_DIR} 50 | ${XCOMPOSITE_INCLUDE_DIR} 51 | ${JPEG_INCLUDE_DIR} 52 | ${XRANDR_INCLUDE_DIR} 53 | ${XRENDER_INCLUDE_DIR} 54 | ${PNG_INCLUDE_DIRS} 55 | ${WEBP_INCLUDE_DIR} ) 56 | 57 | # Libraries 58 | target_link_libraries( ${BIN_TARGET} 59 | ${CMAKE_THREAD_LIBS_INIT} 60 | ${X11_LIBRARIES} 61 | ${PNG_LIBRARIES} 62 | ${XFIXES_LIBRARY} 63 | ${XCOMPOSITE_LIBRARY} 64 | ${XRANDR_LIBRARY} 65 | ${JPEG_LIBRARIES} 66 | ${XRENDER_LIBRARY} 67 | ${SLOP_LIBRARIES} 68 | ${WEBP_LIBRARY} ) 69 | 70 | if( ${CMAKE_VERSION} VERSION_LESS 3.7 ) 71 | message( WARNING "CMake version is below 3.7, CMake version >= 3.7 is required for unicode support." ) 72 | else() 73 | find_package(ICU COMPONENTS uc) 74 | set( MAIM_UNICODE TRUE CACHE BOOL "To enable or disable unicode support." ) 75 | if ( MAIM_UNICODE AND ICU_FOUND ) 76 | # ICU is required for old nvidia drivers to work for whatever reason. 77 | add_definitions(-DCXXOPTS_USE_UNICODE) 78 | include_directories( ${ICU_INCLUDE_DIR} ) 79 | target_link_libraries( ${BIN_TARGET} ${ICU_UC_LIBRARIES} ) 80 | endif() 81 | endif() 82 | 83 | install( TARGETS ${BIN_TARGET} DESTINATION "${CMAKE_INSTALL_BINDIR}" ) 84 | install( FILES "${CMAKE_SOURCE_DIR}/maim.1" DESTINATION "${CMAKE_INSTALL_MANDIR}/man1" COMPONENT doc ) 85 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 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 | # maim 2 | maim (Make Image) is an utility that takes screenshots of your desktop. It's meant to overcome shortcomings of scrot and performs better in several ways. 3 | 4 | ## Features 5 | * Takes screenshots of your desktop, and saves it in png, jpg, or bmp format. 6 | * Takes screenshots of predetermined regions or windows, useful for automation. 7 | * Allows a user to select a region, or window, before taking a screenshot on the fly. 8 | 9 | ![screenshot with selection](http://i.imgur.com/ILZKJCT.png) 10 | * Blends the system cursor to the screenshot. 11 | ![screenshot with cursor](http://i.imgur.com/PD1bgBg.png) 12 | * Masks off-screen pixels to be transparent or black. 13 | 14 | ![screenshot with masked pixels](http://i.imgur.com/kMkcHlZ.png) 15 | * Maim cleanly pipes screenshots directly to standard output (unless otherwise specified), allowing for command chaining. 16 | * Maim supports anything slop does, even selection [shaders](https://github.com/naelstrof/slop#shaders)! 17 | 18 | ![slop animation](http://i.giphy.com/kfBLafeJfLs2Y.gif) 19 | 20 | 21 | ## Installation 22 | 23 | ### Install using your Package Manager (Preferred) 24 | * [ALT Linux: maim](https://packages.altlinux.org/ru/sisyphus/srpms/maim) 25 | * [Arch Linux: extra/maim](https://www.archlinux.org/packages/extra/x86_64/maim/) 26 | * [Debian: maim](https://tracker.debian.org/pkg/maim) 27 | * [Ubuntu: maim](https://packages.ubuntu.com/search?keywords=maim) 28 | * [Void Linux: maim](https://github.com/void-linux/void-packages/tree/master/srcpkgs/maim/template) 29 | * [FreeBSD: graphics/maim](http://www.freshports.org/graphics/maim/) 30 | * [NetBSD: x11/maim](http://pkgsrc.se/x11/maim) 31 | * [OpenBSD: graphics/maim](http://openports.se/graphics/maim) 32 | * [CRUX: maim](https://crux.nu/portdb/?a=search&q=maim) 33 | * [Gentoo: media-gfx/maim](https://packages.gentoo.org/packages/media-gfx/maim) 34 | * [NixOS: maim](https://github.com/NixOS/nixpkgs/blob/master/pkgs/tools/graphics/maim/default.nix) 35 | * [GNU Guix: maim](https://packages.guix.gnu.org/packages/maim/) 36 | * [Ravenports: maim](http://www.ravenports.com/catalog/bucket_B4/maim/standard/) 37 | * [Fedora: maim](https://src.fedoraproject.org/rpms/maim) 38 | * [Fedora EPEL (RHEL, CentOS): maim](https://src.fedoraproject.org/rpms/maim) 39 | * [Alpine Linux: maim](https://pkgs.alpinelinux.org/packages?name=maim&branch=edge&repo=&arch=&maintainer=) 40 | * Please make a package for maim on your favorite system, and make a pull request to add it to this list. 41 | 42 | ### Install using CMake (Requires CMake, git, libXrender, libXfixes, libGLM, libxcomposite, libxrandr, libxext, GLEW) 43 | ```bash 44 | git clone https://github.com/naelstrof/slop.git 45 | cd slop 46 | cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="/usr" ./ 47 | make && sudo make install 48 | cd .. 49 | git clone https://github.com/naelstrof/maim.git 50 | cd maim 51 | cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="/usr" ./ 52 | make && sudo make install 53 | ``` 54 | 55 | ## Examples 56 | Maim allows for a lot of unique and interesting functionalities. Here's an example of a few interactions. 57 | 58 | * This command will allow you to select an area on your screen, then copy the selection to your clipboard. This can be used to easily post images in mumble, discord, gimp-- or any other image supporting application. 59 | ```bash 60 | $ maim -s | xclip -selection clipboard -t image/png 61 | ``` 62 | 63 | * This messy command forces a user to select a window to screenshot, then applies a shadow effect using *imagemagick*, then saves it to shadow.png. It looks really nice on windows that support an alpha channel. 64 | ```bash 65 | $ maim -st 9999999 | convert - \( +clone -background black -shadow 80x3+5+5 \) +swap -background none -layers merge +repage shadow.png 66 | ``` 67 | 68 | * This command is a particular favorite of mine, invented by a friend. It simply prints the RGB values of the selected pixel. A basic color picker that has the additional ability to average out the pixel values of an area. If used cleverly with the geometry and window flag, the return color might warn you of a found counter-strike match... 69 | ```bash 70 | $ maim -st 0 | convert - -resize 1x1\! -format '%[pixel:p{0,0}]' info:- 71 | ``` 72 | 73 | * This is a basic, but useful command that simply screenshots the current active window. 74 | ```bash 75 | $ maim -i $(xdotool getactivewindow) ~/mypicture.jpg 76 | ``` 77 | 78 | * This is another basic command, but I find it necessary to describe the usefulness of date. This particular command creates a full screenshot, and names it as the number of seconds that passed since 1970. Guaranteed unique, already sorted, and easily read. 79 | ```bash 80 | $ maim ~/Pictures/$(date +%s).png 81 | ``` 82 | 83 | * This one overlays a still of your desktop, then allows you to crop it. Doesn't play well with multiple monitors, but I'm sure if it did it wouldn't look this pretty and simple. 84 | ```bash 85 | $ maim -u | feh -F - & maim -s -k cropped.png && kill $! 86 | ``` 87 | 88 | * Finally with the [help your friendly neighborhood scripter](https://github.com/tremby/imgur.sh), pictures can automatically be uploaded and their URLs copied to the clipboard with this basic command. 89 | ```bash 90 | $ maim -s /tmp/screenshot.png; imgur.sh /tmp/screenshot.png | xclip -selection clipboard 91 | ``` 92 | 93 | * The following command can be used to select a QR code (or click into a window 94 | where a QR code is present), decode it, print the text to the console and 95 | copy the text into the clipboard for further usage. 96 | 97 | ```bash 98 | $ maim -qs | zbarimg -q --raw - | xclip -selection clipboard -f 99 | ``` 100 | 101 | * Shortcut for [i3 window manager](https://github.com/i3/i3): 102 | * Enable light on the Thinkpad T430 laptop 103 | * Wait 5 seconds 104 | * Screenshot all displays 105 | * Save file like **~/screenshots/2022-dec-21--12-56-08_maim.png** 106 | * Disable light 107 | * Show i3 notification for 3 seconds: 108 | 109 | ```bash 110 | bindsym $mod+Shift+x exec "\ 111 | echo 1 > /sys/class/leds/platform\:\:micmute/brightness; \ 112 | sleep 5; \ 113 | maim --hidecursor ~/screenshots/$(date +%Y-%b-%d--%H-%M-%S_maim | tr A-Z a-z).png; \ 114 | echo 0 > /sys/class/leds/platform\:\:micmute/brightness; \ 115 | i3-nagbar --message 'Screenshot created' --type warning & \ 116 | sleep 3; pkill i3-nagbar" 117 | ``` 118 | -------------------------------------------------------------------------------- /license.txt: -------------------------------------------------------------------------------- 1 | Copyright (C) 2014 Dalton Nell, Maim Contributors (https://github.com/naelstrof/maim/graphs/contributors) 2 | 3 | This program is free software: you can redistribute it and/or modify 4 | it under the terms of the GNU General Public License as published by 5 | the Free Software Foundation, either version 3 of the License, or 6 | (at your option) any later version. 7 | 8 | This program is distributed in the hope that it will be useful, 9 | but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | GNU General Public License for more details. 12 | 13 | You should have received a copy of the GNU General Public License 14 | along with this program. If not, see . 15 | -------------------------------------------------------------------------------- /maim.1: -------------------------------------------------------------------------------- 1 | .\" Manpage for maim. 2 | .\" Contact naelstrof@gmail.com to correct errors or typos. 3 | .TH maim 1 2021-02-03 Linux "maim man page" 4 | .SH NAME 5 | maim \- capture screenshot of desktop and make image 6 | .SH SYNOPSIS 7 | maim [OPTIONS] [FILEPATH] 8 | .SH DESCRIPTION 9 | maim (make image) is an utility that takes a screenshot of your desktop, and encodes a png, jpg, bmp or webp image of it. By default it outputs the encoded image data directly to standard output. 10 | .SH OPTIONS 11 | .TP 12 | .BR \-h ", " \-\-help 13 | Print help and exit. 14 | .TP 15 | .BR \-v ", " \-\-version 16 | Print version and exit. 17 | .TP 18 | .BR \-x ", " \-\-xdisplay=\fIhostname:number.screen_number\fR 19 | Sets the xdisplay to use. 20 | .TP 21 | .BR \-f ", " \-\-format=\fISTRING\fR 22 | Sets the desired output format, by default maim will attempt to determine the desired output format automatically from the output file. If that fails it defaults to a lossless png format. Currently only supports `png`, `jpg`, `bmp`, and `webp`. 23 | .TP 24 | .BR \-i ", " \-\-window=\fIWINDOW\fR 25 | By default, maim captures the root window. This parameter overrides this and sets the desired window to capture. Allows for an integer, hex, or `root` for input. 26 | .TP 27 | .BR \-g ", " \-\-geometry=\fIGEOMETRY\fR 28 | Sets the region to capture, uses local coordinates from the given window. So -g 10x30-5+0 would represent the rectangle wxh+x+y where w=10, h=30, x=-5, and y=0. x and y are the upper left location of this rectangle. 29 | .TP 30 | .BR \-w ", " \-\-parent=\fIWINDOW\fR 31 | By default, maim assumes the --geometry values are in respect to the provided --window (or root if not provided). This parameter overrides this behavior by making the geometry be in respect to whatever window you provide to --parent. Allows for an integer, hex, or `root` for input. 32 | .TP 33 | .BR \-B ", " \-\-capturebackground 34 | By default, when capturing a window, maim will ignore anything beneath the specified window. This parameter overrides this and also captures elements underneath the window. 35 | .TP 36 | .BR \-d ", " \-\-delay=\fIFLOAT\fR 37 | Sets the time in seconds to wait before taking a screenshot. Prints a simple message to show how many seconds are left before a screenshot is taken. See \-\-quiet for muting this message. 38 | .TP 39 | .BR \-u ", " \-\-hidecursor 40 | By default maim super-imposes the cursor onto the image, you can disable that behavior with this flag. 41 | .TP 42 | .BR \-m ", " \-\-quality 43 | An integer from 1 to 10 that determines the compression quality. For lossy formats (jpg and webp), lower settings will produce smaller files with lower quality, while higher settings will increase quality at the cost of higher file size. A quality of 10 is lossless for webp. For png, lower settings will compress faster and produce larger files, while higher settings will compress slower, but produce smaller files. No effect on bmp images. 44 | .TP 45 | .BR \-s ", " \-\-select 46 | Enables an interactive selection mode where you may select the desired region or window before a screenshot is captured. Uses the settings below to determine the visuals and settings of slop. 47 | .SH SLOP OPTIONS 48 | .TP 49 | .BR \-b ", " \-\-bordersize=\fIFLOAT\fR 50 | Sets the selection rectangle's thickness. 51 | .TP 52 | .BR \-p ", " \-\-padding=\fIFLOAT\fR 53 | Sets the padding size for the selection, this can be negative. 54 | .TP 55 | .BR \-t ", " \-\-tolerance=\fIFLOAT\fR 56 | How far in pixels the mouse can move after clicking, and still be detected as a normal click instead of a click-and-drag. Setting this to 0 will disable window selections. Alternatively setting it to 9999999 would force a window selection. 57 | .TP 58 | .BR \-c ", " \-\-color=\fIFLOAT,FLOAT,FLOAT,FLOAT\fR 59 | Sets the selection rectangle's color. Supports RGB or RGBA input. Depending on the system's window manager/OpenGL support, the opacity may be ignored. 60 | .TP 61 | .BR \-r ", " \-\-shader=\fISTRING\fR 62 | This sets the vertex shader, and fragment shader combo to use when drawing the final framebuffer to the screen. This obviously only works when OpenGL is enabled. The shaders are loaded from ~/.config/maim. See https://github.com/naelstrof/slop for more information on how to create your own shaders. 63 | .TP 64 | .BR \-n ", " \-\-nodecorations=\fIINT\fR 65 | Sets the level of aggressiveness when trying to remove window decorations. `0' is off, `1' will try lightly to remove decorations, and `2' will recursively descend into the root tree until it gets the deepest available visible child under the mouse. Defaults to `0'. 66 | .TP 67 | .BR \-l ", " \-\-highlight 68 | Instead of outlining a selection, maim will highlight it instead. This is particularly useful if the color is set to an opacity lower than 1. 69 | .TP 70 | .BR \-D ", " \-\-nodrag 71 | Allows you to click twice to indicate a selection, rather than click-dragging. 72 | .TP 73 | .BR \-q ", " \-\-quiet 74 | Disable any unnecessary cerr output. Any warnings or info simply won't print. 75 | .TP 76 | .BR \-k ", " \-\-nokeyboard 77 | Disables the ability to cancel selections with the keyboard. 78 | .TP 79 | .BR \-o ", " \-\-noopengl 80 | Disables graphics hardware acceleration. 81 | .SH EXAMPLES 82 | Screenshot the active window and save it to the clipboard for quick pasting. 83 | .PP 84 | .nf 85 | .RS 86 | maim -i $(xdotool getactivewindow) | xclip -selection clipboard -t image/png 87 | .RE 88 | .fi 89 | .PP 90 | Save a desktop screenshot with a unique ordered timestamp in the Pictures folder. 91 | .PP 92 | .nf 93 | .RS 94 | maim ~/Pictures/$(date +%s).png 95 | .RE 96 | .fi 97 | .PP 98 | Save screenshot to the Pictures folder and add it to the clipboard at the same time. 99 | .PP 100 | .nf 101 | .RS 102 | maim | tee ~/Pictures/$(date +%s).png | xclip -selection clipboard -t image/png 103 | .RE 104 | .fi 105 | .PP 106 | Prompt for a region to screenshot. Add a fancy shadow to it, then save it to shadow.png. 107 | .PP 108 | .nf 109 | .RS 110 | maim -s | convert - \\( +clone -background black -shadow 80x3+5+5 \\) +swap -background none -layers merge +repage shadow.png 111 | .RE 112 | .fi 113 | .PP 114 | In scripts, here in i3 window manager: enable light on the Thinkpad T430 laptop, wait 5 seconds, screenshot all displays, save file like ~/screenshots/2022-dec-21--12-56-08_maim.png, disable light, show i3 notification for 3 seconds. 115 | .PP 116 | .nf 117 | .RS 118 | bindsym $mod+Shift+x exec "\ 119 | echo 1 > /sys/class/leds/platform\:\:micmute/brightness; \ 120 | sleep 5; \ 121 | maim --hidecursor ~/screenshots/$(date +%Y-%b-%d--%H-%M-%S_maim | tr A-Z a-z).png; \ 122 | echo 0 > /sys/class/leds/platform\:\:micmute/brightness; \ 123 | i3-nagbar --message 'Screenshot created' --type warning & \ 124 | sleep 3; pkill i3-nagbar" 125 | .RE 126 | .fi 127 | .PP 128 | .SH SEE ALSO 129 | .BR slop(1) 130 | .SH BUGS 131 | No known bugs. 132 | .SH AUTHOR 133 | Dalton Nell (naelstrof@gmail.com) 134 | -------------------------------------------------------------------------------- /modules/FindGLM.cmake: -------------------------------------------------------------------------------- 1 | # - Find GLM 2 | # Find the GLM libraries 3 | # 4 | # This module defines the following variables: 5 | # GLM_FOUND - 1 if GLM_INCLUDE_DIR is found, 0 otherwise 6 | # GLM_INCLUDE_DIR - where to find glm/glm.hpp 7 | # 8 | 9 | find_path( GLM_INCLUDE_DIR 10 | NAMES glm/glm.hpp 11 | PATH_SUFFIXES /usr/include /include 12 | DOC "The GLM include directory" ) 13 | 14 | if( GLM_INCLUDE_DIR ) 15 | set( GLM_FOUND 1 ) 16 | else() 17 | set( GLM_FOUND 0 ) 18 | endif() 19 | 20 | mark_as_advanced( GLM_INCLUDE_DIR ) 21 | -------------------------------------------------------------------------------- /modules/FindGLX.cmake: -------------------------------------------------------------------------------- 1 | # Try to find GLX. Once done, this will define: 2 | # 3 | # GLX_FOUND - variable which returns the result of the search 4 | # GLX_INCLUDE_DIRS - list of include directories 5 | # GLX_LIBRARIES - options for the linker 6 | 7 | #============================================================================= 8 | # Copyright 2012 Benjamin Eikel 9 | # 10 | # Distributed under the OSI-approved BSD License (the "License"); 11 | # see accompanying file Copyright.txt for details. 12 | # 13 | # This software is distributed WITHOUT ANY WARRANTY; without even the 14 | # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 15 | # See the License for more information. 16 | #============================================================================= 17 | # (To distribute this file outside of CMake, substitute the full 18 | # License text for the above reference.) 19 | 20 | find_package(PkgConfig) 21 | pkg_check_modules(PC_GLX QUIET glx) 22 | 23 | find_path(GLX_INCLUDE_DIR 24 | GL/glx.h 25 | HINTS ${PC_GLX_INCLUDEDIR} ${PC_GLX_INCLUDE_DIRS} 26 | ) 27 | find_library(GLX_LIBRARY 28 | GL 29 | HINTS ${PC_GLX_LIBDIR} ${PC_GLX_LIBRARY_DIRS} 30 | ) 31 | 32 | set(GLX_INCLUDE_DIRS ${GLX_INCLUDE_DIR}) 33 | set(GLX_LIBRARIES ${GLX_LIBRARY}) 34 | 35 | include(FindPackageHandleStandardArgs) 36 | find_package_handle_standard_args(GLX DEFAULT_MSG 37 | GLX_INCLUDE_DIR 38 | GLX_LIBRARY 39 | ) 40 | 41 | mark_as_advanced( 42 | GLX_INCLUDE_DIR 43 | GLX_LIBRARY 44 | ) 45 | -------------------------------------------------------------------------------- /modules/FindSLOP.cmake: -------------------------------------------------------------------------------- 1 | # - Find SLOP 2 | # Find the SLOP libraries 3 | # 4 | # This module defines the following variables: 5 | # SLOP_FOUND - 1 if SLOP_INCLUDE_DIR & SLOP_LIBRARY are found, 0 otherwise 6 | # SLOP_INCLUDE_DIR - where to find Xlib.h, etc. 7 | # SLOP_LIBRARY - the X11 library 8 | # 9 | 10 | 11 | find_path( SLOP_INCLUDE_DIR 12 | NAMES slop.hpp 13 | PATH_SUFFIXES /usr/include /include 14 | DOC "The SLOP include directory" ) 15 | 16 | find_library( SLOP_LIBRARIES 17 | NAMES slopy slopy.so slop slop.so 18 | PATHS /usr/lib /lib 19 | DOC "The SLOP library" ) 20 | 21 | FIND_PACKAGE(X11 REQUIRED) 22 | FIND_PACKAGE(GLX REQUIRED) 23 | list(APPEND SLOP_LIBRARIES 24 | ${X11_LIBRARIES} 25 | ${GLX_LIBRARY} 26 | ) 27 | 28 | if( SLOP_INCLUDE_DIR AND SLOP_LIBRARY ) 29 | set( SLOP_FOUND 1 ) 30 | else() 31 | set( SLOP_FOUND 0 ) 32 | endif() 33 | 34 | mark_as_advanced( SLOP_INCLUDE_DIR SLOP_LIBRARY ) 35 | -------------------------------------------------------------------------------- /modules/FindWebP.cmake: -------------------------------------------------------------------------------- 1 | # - Find WebP 2 | # Find the WebP libraries 3 | # 4 | # This module defines the following variables: 5 | # WEBP_FOUND - 1 if WEBP_INCLUDE_DIR & WEBP_LIBRARY are found, 0 otherwise 6 | # WEBP_INCLUDE_DIR - where to find webp/encode.h, etc. 7 | # WEBP_LIBRARY - the libwebp library 8 | 9 | find_path( WEBP_INCLUDE_DIR 10 | NAMES webp/encode.h 11 | PATH_SUFFIXES /usr/include /include 12 | DOC "The libwebp include directory" ) 13 | 14 | find_library( WEBP_LIBRARY 15 | NAMES libwebp.so 16 | PATHS /usr/lib /lib 17 | DOC "The libwebp library" ) 18 | 19 | if( WEBP_INCLUDE_DIR AND WEBP_LIBRARY ) 20 | set( WEBP_FOUND 1 ) 21 | else() 22 | set( WEBP_FOUND 0 ) 23 | endif() 24 | 25 | mark_as_advanced( WEBP_INCLUDE_DIR WEBP_LIBRARY ) 26 | -------------------------------------------------------------------------------- /modules/FindXComposite.cmake: -------------------------------------------------------------------------------- 1 | # - Find XComposite 2 | # Find the XComposite libraries 3 | # 4 | # This module defines the following variables: 5 | # XCOMPOSITE_FOUND - 1 if XCOMPOSITE_INCLUDE_DIR & XCOMPOSITE_LIBRARY are found, 0 otherwise 6 | # XCOMPOSITE_INCLUDE_DIR - where to find Xlib.h, etc. 7 | # XCOMPOSITE_LIBRARY - the X11 library 8 | # 9 | 10 | find_path( XCOMPOSITE_INCLUDE_DIR 11 | NAMES X11/extensions/Xcomposite.h 12 | PATH_SUFFIXES X11/extensions 13 | DOC "The XComposite include directory" ) 14 | 15 | find_library( XCOMPOSITE_LIBRARY 16 | NAMES Xcomposite 17 | PATHS /usr/lib /lib 18 | DOC "The XComposite library" ) 19 | 20 | if( XCOMPOSITE_INCLUDE_DIR AND XCOMPOSITE_LIBRARY ) 21 | set( XCOMPOSITE_FOUND 1 ) 22 | else() 23 | set( XCOMPOSITE_FOUND 0 ) 24 | endif() 25 | 26 | mark_as_advanced( XCOMPOSITE_INCLUDE_DIR XCOMPOSITE_LIBRARY ) 27 | -------------------------------------------------------------------------------- /modules/FindXFixes.cmake: -------------------------------------------------------------------------------- 1 | # - Find XFixes 2 | # Find the XFixes libraries 3 | # 4 | # This module defines the following variables: 5 | # XFIXES_FOUND - 1 if XFIXES_INCLUDE_DIR & XFIXES_LIBRARY are found, 0 otherwise 6 | # XFIXES_INCLUDE_DIR - where to find Xlib.h, etc. 7 | # XFIXES_LIBRARY - the X11 library 8 | # 9 | 10 | find_path( XFIXES_INCLUDE_DIR 11 | NAMES X11/extensions/Xfixes.h 12 | PATH_SUFFIXES X11/extensions 13 | DOC "The XFixes include directory" ) 14 | 15 | find_library( XFIXES_LIBRARY 16 | NAMES Xfixes 17 | PATHS /usr/lib /lib 18 | DOC "The XFixes library" ) 19 | 20 | if( XFIXES_INCLUDE_DIR AND XFIXES_LIBRARY ) 21 | set( XFIXES_FOUND 1 ) 22 | else() 23 | set( XFIXES_FOUND 0 ) 24 | endif() 25 | 26 | mark_as_advanced( XFIXES_INCLUDE_DIR XFIXES_LIBRARY ) 27 | -------------------------------------------------------------------------------- /modules/FindXRandr.cmake: -------------------------------------------------------------------------------- 1 | # - Find XRandr 2 | # Find the XRandr libraries 3 | # 4 | # This module defines the following variables: 5 | # XRANDR_FOUND - 1 if XRANDR_INCLUDE_DIR & XRANDR_LIBRARY are found, 0 otherwise 6 | # XRANDR_INCLUDE_DIR - where to find Xlib.h, etc. 7 | # XRANDR_LIBRARY - the X11 library 8 | # 9 | 10 | find_path( XRANDR_INCLUDE_DIR 11 | NAMES X11/extensions/Xrandr.h 12 | PATH_SUFFIXES X11/extensions 13 | DOC "The XRandr include directory" ) 14 | 15 | find_library( XRANDR_LIBRARY 16 | NAMES Xrandr 17 | PATHS /usr/lib /lib 18 | DOC "The XRandr library" ) 19 | 20 | if( XRANDR_INCLUDE_DIR AND XRANDR_LIBRARY ) 21 | set( XRANDR_FOUND 1 ) 22 | else() 23 | set( XRANDR_FOUND 0 ) 24 | endif() 25 | 26 | mark_as_advanced( XRANDR_INCLUDE_DIR XRANDR_LIBRARY ) 27 | -------------------------------------------------------------------------------- /modules/FindXRender.cmake: -------------------------------------------------------------------------------- 1 | # - Find XRender 2 | # Find the XRender libraries 3 | # 4 | # This module defines the following variables: 5 | # XRENDER_FOUND - true if XRENDER_INCLUDE_DIR & XRENDER_LIBRARY are found 6 | # XRENDER_LIBRARIES - Set when Xrender_LIBRARY is found 7 | # XRENDER_INCLUDE_DIRS - Set when Xrender_INCLUDE_DIR is found 8 | # 9 | # XRENDER_INCLUDE_DIR - where to find Xrender.h, etc. 10 | # XRENDER_LIBRARY - the Xrender library 11 | # 12 | 13 | #============================================================================= 14 | # Copyright 2013 Corey Clayton 15 | # 16 | # Licensed under the Apache License, Version 2.0 (the "License"); 17 | # you may not use this file except in compliance with the License. 18 | # You may obtain a copy of the License at 19 | # 20 | # http://www.apache.org/licenses/LICENSE-2.0 21 | # 22 | # Unless required by applicable law or agreed to in writing, software 23 | # distributed under the License is distributed on an "AS IS" BASIS, 24 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 25 | # See the License for the specific language governing permissions and 26 | # limitations under the License. 27 | #============================================================================= 28 | 29 | find_path(XRENDER_INCLUDE_DIR NAMES X11/extensions/Xrender.h 30 | PATHS /opt/X11/include 31 | DOC "The Xrender include directory") 32 | 33 | find_library(XRENDER_LIBRARY NAMES Xrender 34 | PATHS /opt/X11/lib 35 | DOC "The Xrender library") 36 | 37 | include(FindPackageHandleStandardArgs) 38 | FIND_PACKAGE_HANDLE_STANDARD_ARGS(Xrender DEFAULT_MSG XRENDER_LIBRARY XRENDER_INCLUDE_DIR) 39 | 40 | if(XRENDER_FOUND) 41 | 42 | set(XRENDER_LIBRARIES ${XRENDER_LIBRARY}) 43 | set(XRENDER_INCLUDE_DIRS ${XRENDER_INCLUDE_DIR}) 44 | 45 | endif() 46 | 47 | mark_as_advanced(XRENDER_INCLUDE_DIR XRENDER_LIBRARY) 48 | -------------------------------------------------------------------------------- /src/cxxopts.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright (c) 2014, 2015, 2016 Jarryd Beck 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | 23 | */ 24 | 25 | #ifndef CXX_OPTS_HPP 26 | #define CXX_OPTS_HPP 27 | 28 | #if defined(__GNUC__) 29 | #pragma GCC diagnostic push 30 | #pragma GCC diagnostic ignored "-Wnon-virtual-dtor" 31 | #endif 32 | 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | 44 | //when we ask cxxopts to use Unicode, help strings are processed using ICU, 45 | //which results in the correct lengths being computed for strings when they 46 | //are formatted for the help output 47 | //it is necessary to make sure that can be found by the 48 | //compiler, and that icu-uc is linked in to the binary. 49 | 50 | #ifdef CXXOPTS_USE_UNICODE 51 | #include 52 | 53 | namespace cxxopts 54 | { 55 | typedef icu::UnicodeString String; 56 | 57 | inline 58 | String 59 | toLocalString(std::string s) 60 | { 61 | return icu::UnicodeString::fromUTF8(s); 62 | } 63 | 64 | class UnicodeStringIterator : public 65 | std::iterator 66 | { 67 | public: 68 | 69 | UnicodeStringIterator(const icu::UnicodeString* s, int32_t pos) 70 | : s(s) 71 | , i(pos) 72 | { 73 | } 74 | 75 | value_type 76 | operator*() const 77 | { 78 | return s->char32At(i); 79 | } 80 | 81 | bool 82 | operator==(const UnicodeStringIterator& rhs) const 83 | { 84 | return s == rhs.s && i == rhs.i; 85 | } 86 | 87 | bool 88 | operator!=(const UnicodeStringIterator& rhs) const 89 | { 90 | return !(*this == rhs); 91 | } 92 | 93 | UnicodeStringIterator& 94 | operator++() 95 | { 96 | ++i; 97 | return *this; 98 | } 99 | 100 | UnicodeStringIterator 101 | operator+(int32_t v) 102 | { 103 | return UnicodeStringIterator(s, i + v); 104 | } 105 | 106 | private: 107 | const icu::UnicodeString* s; 108 | int32_t i; 109 | }; 110 | 111 | inline 112 | String& 113 | stringAppend(String&s, String a) 114 | { 115 | return s.append(std::move(a)); 116 | } 117 | 118 | inline 119 | String& 120 | stringAppend(String& s, int n, UChar32 c) 121 | { 122 | for (int i = 0; i != n; ++i) 123 | { 124 | s.append(c); 125 | } 126 | 127 | return s; 128 | } 129 | 130 | template 131 | String& 132 | stringAppend(String& s, Iterator begin, Iterator end) 133 | { 134 | while (begin != end) 135 | { 136 | s.append(*begin); 137 | ++begin; 138 | } 139 | 140 | return s; 141 | } 142 | 143 | inline 144 | size_t 145 | stringLength(const String& s) 146 | { 147 | return s.length(); 148 | } 149 | 150 | inline 151 | std::string 152 | toUTF8String(const String& s) 153 | { 154 | std::string result; 155 | s.toUTF8String(result); 156 | 157 | return result; 158 | } 159 | 160 | inline 161 | bool 162 | empty(const String& s) 163 | { 164 | return s.isEmpty(); 165 | } 166 | } 167 | 168 | namespace std 169 | { 170 | cxxopts::UnicodeStringIterator 171 | begin(const icu::UnicodeString& s) 172 | { 173 | return cxxopts::UnicodeStringIterator(&s, 0); 174 | } 175 | 176 | cxxopts::UnicodeStringIterator 177 | end(const icu::UnicodeString& s) 178 | { 179 | return cxxopts::UnicodeStringIterator(&s, s.length()); 180 | } 181 | } 182 | 183 | //ifdef CXXOPTS_USE_UNICODE 184 | #else 185 | 186 | namespace cxxopts 187 | { 188 | typedef std::string String; 189 | 190 | template 191 | T 192 | toLocalString(T&& t) 193 | { 194 | return t; 195 | } 196 | 197 | inline 198 | size_t 199 | stringLength(const String& s) 200 | { 201 | return s.length(); 202 | } 203 | 204 | inline 205 | String& 206 | stringAppend(String&s, String a) 207 | { 208 | return s.append(std::move(a)); 209 | } 210 | 211 | inline 212 | String& 213 | stringAppend(String& s, size_t n, char c) 214 | { 215 | return s.append(n, c); 216 | } 217 | 218 | template 219 | String& 220 | stringAppend(String& s, Iterator begin, Iterator end) 221 | { 222 | return s.append(begin, end); 223 | } 224 | 225 | template 226 | std::string 227 | toUTF8String(T&& t) 228 | { 229 | return std::forward(t); 230 | } 231 | 232 | inline 233 | bool 234 | empty(const std::string& s) 235 | { 236 | return s.empty(); 237 | } 238 | } 239 | 240 | //ifdef CXXOPTS_USE_UNICODE 241 | #endif 242 | 243 | namespace cxxopts 244 | { 245 | class Value : public std::enable_shared_from_this 246 | { 247 | public: 248 | 249 | virtual void 250 | parse(const std::string& text) const = 0; 251 | 252 | virtual void 253 | parse() const = 0; 254 | 255 | virtual bool 256 | has_arg() const = 0; 257 | 258 | virtual bool 259 | has_default() const = 0; 260 | 261 | virtual bool 262 | is_container() const = 0; 263 | 264 | virtual bool 265 | has_implicit() const = 0; 266 | 267 | virtual std::string 268 | get_default_value() const = 0; 269 | 270 | virtual std::string 271 | get_implicit_value() const = 0; 272 | 273 | virtual std::shared_ptr 274 | default_value(const std::string& value) = 0; 275 | 276 | virtual std::shared_ptr 277 | implicit_value(const std::string& value) = 0; 278 | }; 279 | 280 | class OptionException : public std::exception 281 | { 282 | public: 283 | OptionException(const std::string& message) 284 | : m_message(message) 285 | { 286 | } 287 | 288 | virtual const char* 289 | what() const noexcept 290 | { 291 | return m_message.c_str(); 292 | } 293 | 294 | private: 295 | std::string m_message; 296 | }; 297 | 298 | class OptionSpecException : public OptionException 299 | { 300 | public: 301 | 302 | OptionSpecException(const std::string& message) 303 | : OptionException(message) 304 | { 305 | } 306 | }; 307 | 308 | class OptionParseException : public OptionException 309 | { 310 | public: 311 | OptionParseException(const std::string& message) 312 | : OptionException(message) 313 | { 314 | } 315 | }; 316 | 317 | class option_exists_error : public OptionSpecException 318 | { 319 | public: 320 | option_exists_error(const std::string& option) 321 | : OptionSpecException(u8"Option ‘" + option + u8"’ already exists") 322 | { 323 | } 324 | }; 325 | 326 | class invalid_option_format_error : public OptionSpecException 327 | { 328 | public: 329 | invalid_option_format_error(const std::string& format) 330 | : OptionSpecException(u8"Invalid option format ‘" + format + u8"’") 331 | { 332 | } 333 | }; 334 | 335 | class option_not_exists_exception : public OptionParseException 336 | { 337 | public: 338 | option_not_exists_exception(const std::string& option) 339 | : OptionParseException(u8"Option ‘" + option + u8"’ does not exist") 340 | { 341 | } 342 | }; 343 | 344 | class missing_argument_exception : public OptionParseException 345 | { 346 | public: 347 | missing_argument_exception(const std::string& option) 348 | : OptionParseException(u8"Option ‘" + option + u8"’ is missing an argument") 349 | { 350 | } 351 | }; 352 | 353 | class option_requires_argument_exception : public OptionParseException 354 | { 355 | public: 356 | option_requires_argument_exception(const std::string& option) 357 | : OptionParseException(u8"Option ‘" + option + u8"’ requires an argument") 358 | { 359 | } 360 | }; 361 | 362 | class option_not_has_argument_exception : public OptionParseException 363 | { 364 | public: 365 | option_not_has_argument_exception 366 | ( 367 | const std::string& option, 368 | const std::string& arg 369 | ) 370 | : OptionParseException( 371 | u8"Option ‘" + option + u8"’ does not take an argument, but argument‘" 372 | + arg + "’ given") 373 | { 374 | } 375 | }; 376 | 377 | class option_not_present_exception : public OptionParseException 378 | { 379 | public: 380 | option_not_present_exception(const std::string& option) 381 | : OptionParseException(u8"Option ‘" + option + u8"’ not present") 382 | { 383 | } 384 | }; 385 | 386 | class argument_incorrect_type : public OptionParseException 387 | { 388 | public: 389 | argument_incorrect_type 390 | ( 391 | const std::string& arg 392 | ) 393 | : OptionParseException( 394 | u8"Argument ‘" + arg + u8"’ failed to parse" 395 | ) 396 | { 397 | } 398 | }; 399 | 400 | namespace values 401 | { 402 | template 403 | void 404 | parse_value(const std::string& text, T& value) 405 | { 406 | std::istringstream is(text); 407 | if (!(is >> value)) 408 | { 409 | throw argument_incorrect_type(text); 410 | } 411 | 412 | if (is.rdbuf()->in_avail() != 0) 413 | { 414 | throw argument_incorrect_type(text); 415 | } 416 | } 417 | 418 | inline 419 | void 420 | parse_value(const std::string& /*text*/, bool& value) 421 | { 422 | //TODO recognise on, off, yes, no, enable, disable 423 | //so that we can write --long=yes explicitly 424 | value = true; 425 | } 426 | 427 | inline 428 | void 429 | parse_value(const std::string& text, std::string& value) 430 | { 431 | value = text; 432 | } 433 | 434 | template 435 | void 436 | parse_value(const std::string& text, std::vector& value) 437 | { 438 | T v; 439 | parse_value(text, v); 440 | value.push_back(v); 441 | } 442 | 443 | template 444 | struct value_has_arg 445 | { 446 | static constexpr bool value = true; 447 | }; 448 | 449 | template <> 450 | struct value_has_arg 451 | { 452 | static constexpr bool value = false; 453 | }; 454 | 455 | template 456 | struct type_is_container 457 | { 458 | static constexpr bool value = false; 459 | }; 460 | 461 | template 462 | struct type_is_container> 463 | { 464 | static constexpr bool value = true; 465 | }; 466 | 467 | template 468 | class standard_value : public Value 469 | { 470 | public: 471 | standard_value() 472 | : m_result(std::make_shared()) 473 | , m_store(m_result.get()) 474 | { 475 | } 476 | 477 | standard_value(T* t) 478 | : m_store(t) 479 | { 480 | } 481 | 482 | void 483 | parse(const std::string& text) const 484 | { 485 | parse_value(text, *m_store); 486 | } 487 | 488 | bool 489 | is_container() const 490 | { 491 | return type_is_container::value; 492 | } 493 | 494 | void 495 | parse() const 496 | { 497 | parse_value(m_default_value, *m_store); 498 | } 499 | 500 | bool 501 | has_arg() const 502 | { 503 | return value_has_arg::value; 504 | } 505 | 506 | bool 507 | has_default() const 508 | { 509 | return m_default; 510 | } 511 | 512 | bool 513 | has_implicit() const 514 | { 515 | return m_implicit; 516 | } 517 | 518 | virtual std::shared_ptr 519 | default_value(const std::string& value){ 520 | m_default = true; 521 | m_default_value = value; 522 | return shared_from_this(); 523 | } 524 | 525 | virtual std::shared_ptr 526 | implicit_value(const std::string& value){ 527 | m_implicit = true; 528 | m_implicit_value = value; 529 | return shared_from_this(); 530 | } 531 | 532 | std::string 533 | get_default_value() const 534 | { 535 | return m_default_value; 536 | } 537 | 538 | std::string 539 | get_implicit_value() const 540 | { 541 | return m_implicit_value; 542 | } 543 | 544 | const T& 545 | get() const 546 | { 547 | if (m_store == nullptr) 548 | { 549 | return *m_result; 550 | } 551 | else 552 | { 553 | return *m_store; 554 | } 555 | } 556 | 557 | protected: 558 | std::shared_ptr m_result; 559 | T* m_store; 560 | bool m_default = false; 561 | std::string m_default_value; 562 | bool m_implicit = false; 563 | std::string m_implicit_value; 564 | }; 565 | } 566 | 567 | template 568 | std::shared_ptr 569 | value() 570 | { 571 | return std::make_shared>(); 572 | } 573 | 574 | template 575 | std::shared_ptr 576 | value(T& t) 577 | { 578 | return std::make_shared>(&t); 579 | } 580 | 581 | class OptionAdder; 582 | 583 | class OptionDetails 584 | { 585 | public: 586 | OptionDetails 587 | ( 588 | const String& description, 589 | std::shared_ptr value 590 | ) 591 | : m_desc(description) 592 | , m_value(value) 593 | , m_count(0) 594 | { 595 | } 596 | 597 | const String& 598 | description() const 599 | { 600 | return m_desc; 601 | } 602 | 603 | bool 604 | has_arg() const 605 | { 606 | return m_value->has_arg(); 607 | } 608 | 609 | void 610 | parse(const std::string& text) 611 | { 612 | m_value->parse(text); 613 | ++m_count; 614 | } 615 | 616 | void 617 | parse_default() 618 | { 619 | m_value->parse(); 620 | } 621 | 622 | int 623 | count() const 624 | { 625 | return m_count; 626 | } 627 | 628 | const Value& value() const { 629 | return *m_value; 630 | } 631 | 632 | template 633 | const T& 634 | as() const 635 | { 636 | #ifdef CXXOPTS_NO_RTTI 637 | return static_cast&>(*m_value).get(); 638 | #else 639 | return dynamic_cast&>(*m_value).get(); 640 | #endif 641 | } 642 | 643 | private: 644 | String m_desc; 645 | std::shared_ptr m_value; 646 | int m_count; 647 | }; 648 | 649 | struct HelpOptionDetails 650 | { 651 | std::string s; 652 | std::string l; 653 | String desc; 654 | bool has_arg; 655 | bool has_default; 656 | std::string default_value; 657 | bool has_implicit; 658 | std::string implicit_value; 659 | std::string arg_help; 660 | bool is_container; 661 | }; 662 | 663 | struct HelpGroupDetails 664 | { 665 | std::string name; 666 | std::string description; 667 | std::vector options; 668 | }; 669 | 670 | class Options 671 | { 672 | public: 673 | 674 | Options(std::string program, std::string help_string = "") 675 | : m_program(std::move(program)) 676 | , m_help_string(toLocalString(std::move(help_string))) 677 | , m_positional_help("positional parameters") 678 | , m_next_positional(m_positional.end()) 679 | { 680 | } 681 | 682 | inline 683 | Options& 684 | positional_help(const std::string& help_text) 685 | { 686 | m_positional_help = std::move(help_text); 687 | return *this; 688 | } 689 | 690 | inline 691 | void 692 | parse(int& argc, char**& argv); 693 | 694 | inline 695 | OptionAdder 696 | add_options(std::string group = ""); 697 | 698 | inline 699 | void 700 | add_option 701 | ( 702 | const std::string& group, 703 | const std::string& s, 704 | const std::string& l, 705 | std::string desc, 706 | std::shared_ptr value, 707 | std::string arg_help 708 | ); 709 | 710 | int 711 | count(const std::string& o) const 712 | { 713 | auto iter = m_options.find(o); 714 | if (iter == m_options.end()) 715 | { 716 | return 0; 717 | } 718 | 719 | return iter->second->count(); 720 | } 721 | 722 | const OptionDetails& 723 | operator[](const std::string& option) const 724 | { 725 | auto iter = m_options.find(option); 726 | 727 | if (iter == m_options.end()) 728 | { 729 | throw option_not_present_exception(option); 730 | } 731 | 732 | return *iter->second; 733 | } 734 | 735 | //parse positional arguments into the given option 736 | inline 737 | void 738 | parse_positional(std::string option); 739 | 740 | inline 741 | void 742 | parse_positional(std::vector options); 743 | 744 | inline 745 | std::string 746 | help(const std::vector& groups = {""}) const; 747 | 748 | inline 749 | const std::vector 750 | groups() const; 751 | 752 | inline 753 | const HelpGroupDetails& 754 | group_help(const std::string& group) const; 755 | 756 | private: 757 | 758 | inline 759 | void 760 | add_one_option 761 | ( 762 | const std::string& option, 763 | std::shared_ptr details 764 | ); 765 | 766 | inline 767 | bool 768 | consume_positional(std::string a); 769 | 770 | inline 771 | void 772 | add_to_option(const std::string& option, const std::string& arg); 773 | 774 | inline 775 | void 776 | parse_option 777 | ( 778 | std::shared_ptr value, 779 | const std::string& name, 780 | const std::string& arg = "" 781 | ); 782 | 783 | inline 784 | void 785 | checked_parse_arg 786 | ( 787 | int argc, 788 | char* argv[], 789 | int& current, 790 | std::shared_ptr value, 791 | const std::string& name 792 | ); 793 | 794 | inline 795 | String 796 | help_one_group(const std::string& group) const; 797 | 798 | inline 799 | void 800 | generate_group_help(String& result, const std::vector& groups) const; 801 | 802 | inline 803 | void 804 | generate_all_groups_help(String& result) const; 805 | 806 | std::string m_program; 807 | String m_help_string; 808 | std::string m_positional_help; 809 | 810 | std::map> m_options; 811 | std::vector m_positional; 812 | std::vector::iterator m_next_positional; 813 | std::unordered_set m_positional_set; 814 | 815 | //mapping from groups to help options 816 | std::map m_help; 817 | }; 818 | 819 | class OptionAdder 820 | { 821 | public: 822 | 823 | OptionAdder(Options& options, std::string group) 824 | : m_options(options), m_group(std::move(group)) 825 | { 826 | } 827 | 828 | inline 829 | OptionAdder& 830 | operator() 831 | ( 832 | const std::string& opts, 833 | const std::string& desc, 834 | std::shared_ptr value 835 | = ::cxxopts::value(), 836 | std::string arg_help = "" 837 | ); 838 | 839 | private: 840 | Options& m_options; 841 | std::string m_group; 842 | }; 843 | 844 | } 845 | 846 | namespace cxxopts 847 | { 848 | 849 | namespace 850 | { 851 | 852 | constexpr int OPTION_LONGEST = 30; 853 | constexpr int OPTION_DESC_GAP = 2; 854 | 855 | std::basic_regex option_matcher 856 | ("--([[:alnum:]][-_[:alnum:]]+)(=(.*))?|-([[:alnum:]]+)"); 857 | 858 | std::basic_regex option_specifier 859 | ("(([[:alnum:]]),)?([[:alnum:]][-_[:alnum:]]+)"); 860 | 861 | String 862 | format_option 863 | ( 864 | const HelpOptionDetails& o 865 | ) 866 | { 867 | auto& s = o.s; 868 | auto& l = o.l; 869 | 870 | String result = " "; 871 | 872 | if (s.size() > 0) 873 | { 874 | result += "-" + toLocalString(s) + ","; 875 | } 876 | else 877 | { 878 | result += " "; 879 | } 880 | 881 | if (l.size() > 0) 882 | { 883 | result += " --" + toLocalString(l); 884 | } 885 | 886 | if (o.has_arg) 887 | { 888 | auto arg = o.arg_help.size() > 0 ? toLocalString(o.arg_help) : "arg"; 889 | 890 | if (o.has_implicit) 891 | { 892 | result += " [=" + arg + "(=" + toLocalString(o.implicit_value) + ")]"; 893 | } 894 | else 895 | { 896 | result += " " + arg; 897 | } 898 | } 899 | 900 | return result; 901 | } 902 | 903 | String 904 | format_description 905 | ( 906 | const HelpOptionDetails& o, 907 | size_t start, 908 | size_t width 909 | ) 910 | { 911 | auto desc = o.desc; 912 | 913 | if (o.has_default) 914 | { 915 | desc += toLocalString(" (default: " + o.default_value + ")"); 916 | } 917 | 918 | String result; 919 | 920 | auto current = std::begin(desc); 921 | auto startLine = current; 922 | auto lastSpace = current; 923 | 924 | auto size = size_t{}; 925 | 926 | while (current != std::end(desc)) 927 | { 928 | if (*current == ' ') 929 | { 930 | lastSpace = current; 931 | } 932 | 933 | if (size > width) 934 | { 935 | if (lastSpace == startLine) 936 | { 937 | stringAppend(result, startLine, current + 1); 938 | stringAppend(result, "\n"); 939 | stringAppend(result, start, ' '); 940 | startLine = current + 1; 941 | lastSpace = startLine; 942 | } 943 | else 944 | { 945 | stringAppend(result, startLine, lastSpace); 946 | stringAppend(result, "\n"); 947 | stringAppend(result, start, ' '); 948 | startLine = lastSpace + 1; 949 | } 950 | size = 0; 951 | } 952 | else 953 | { 954 | ++size; 955 | } 956 | 957 | ++current; 958 | } 959 | 960 | //append whatever is left 961 | stringAppend(result, startLine, current); 962 | 963 | return result; 964 | } 965 | } 966 | 967 | OptionAdder 968 | Options::add_options(std::string group) 969 | { 970 | return OptionAdder(*this, std::move(group)); 971 | } 972 | 973 | OptionAdder& 974 | OptionAdder::operator() 975 | ( 976 | const std::string& opts, 977 | const std::string& desc, 978 | std::shared_ptr value, 979 | std::string arg_help 980 | ) 981 | { 982 | std::match_results result; 983 | std::regex_match(opts.c_str(), result, option_specifier); 984 | 985 | if (result.empty()) 986 | { 987 | throw invalid_option_format_error(opts); 988 | } 989 | 990 | const auto& s = result[2]; 991 | const auto& l = result[3]; 992 | 993 | m_options.add_option(m_group, s.str(), l.str(), desc, value, 994 | std::move(arg_help)); 995 | 996 | return *this; 997 | } 998 | 999 | void 1000 | Options::parse_option 1001 | ( 1002 | std::shared_ptr value, 1003 | const std::string& /*name*/, 1004 | const std::string& arg 1005 | ) 1006 | { 1007 | value->parse(arg); 1008 | } 1009 | 1010 | void 1011 | Options::checked_parse_arg 1012 | ( 1013 | int argc, 1014 | char* argv[], 1015 | int& current, 1016 | std::shared_ptr value, 1017 | const std::string& name 1018 | ) 1019 | { 1020 | if (current + 1 >= argc) 1021 | { 1022 | if (value->value().has_implicit()) 1023 | { 1024 | parse_option(value, name, value->value().get_implicit_value()); 1025 | } 1026 | else 1027 | { 1028 | throw missing_argument_exception(name); 1029 | } 1030 | } 1031 | else 1032 | { 1033 | if (argv[current + 1][0] == '-' && value->value().has_implicit()) 1034 | { 1035 | parse_option(value, name, value->value().get_implicit_value()); 1036 | } 1037 | else 1038 | { 1039 | parse_option(value, name, argv[current + 1]); 1040 | ++current; 1041 | } 1042 | } 1043 | } 1044 | 1045 | void 1046 | Options::add_to_option(const std::string& option, const std::string& arg) 1047 | { 1048 | auto iter = m_options.find(option); 1049 | 1050 | if (iter == m_options.end()) 1051 | { 1052 | throw option_not_exists_exception(option); 1053 | } 1054 | 1055 | parse_option(iter->second, option, arg); 1056 | } 1057 | 1058 | bool 1059 | Options::consume_positional(std::string a) 1060 | { 1061 | while (m_next_positional != m_positional.end()) 1062 | { 1063 | auto iter = m_options.find(*m_next_positional); 1064 | if (iter != m_options.end()) 1065 | { 1066 | if (!iter->second->value().is_container()) 1067 | { 1068 | if (iter->second->count() == 0) 1069 | { 1070 | add_to_option(*m_next_positional, a); 1071 | ++m_next_positional; 1072 | return true; 1073 | } 1074 | else 1075 | { 1076 | ++m_next_positional; 1077 | continue; 1078 | } 1079 | } 1080 | else 1081 | { 1082 | add_to_option(*m_next_positional, a); 1083 | return true; 1084 | } 1085 | } 1086 | ++m_next_positional; 1087 | } 1088 | 1089 | return false; 1090 | } 1091 | 1092 | void 1093 | Options::parse_positional(std::string option) 1094 | { 1095 | parse_positional(std::vector{option}); 1096 | } 1097 | 1098 | void 1099 | Options::parse_positional(std::vector options) 1100 | { 1101 | m_positional = std::move(options); 1102 | m_next_positional = m_positional.begin(); 1103 | 1104 | m_positional_set.insert(m_positional.begin(), m_positional.end()); 1105 | } 1106 | 1107 | void 1108 | Options::parse(int& argc, char**& argv) 1109 | { 1110 | int current = 1; 1111 | 1112 | int nextKeep = 1; 1113 | 1114 | bool consume_remaining = false; 1115 | 1116 | while (current != argc) 1117 | { 1118 | if (strcmp(argv[current], "--") == 0) 1119 | { 1120 | consume_remaining = true; 1121 | ++current; 1122 | break; 1123 | } 1124 | 1125 | std::match_results result; 1126 | std::regex_match(argv[current], result, option_matcher); 1127 | 1128 | if (result.empty()) 1129 | { 1130 | //not a flag 1131 | 1132 | //if true is returned here then it was consumed, otherwise it is 1133 | //ignored 1134 | if (consume_positional(argv[current])) 1135 | { 1136 | } 1137 | else 1138 | { 1139 | argv[nextKeep] = argv[current]; 1140 | ++nextKeep; 1141 | } 1142 | //if we return from here then it was parsed successfully, so continue 1143 | } 1144 | else 1145 | { 1146 | //short or long option? 1147 | if (result[4].length() != 0) 1148 | { 1149 | const std::string& s = result[4]; 1150 | 1151 | for (std::size_t i = 0; i != s.size(); ++i) 1152 | { 1153 | std::string name(1, s[i]); 1154 | auto iter = m_options.find(name); 1155 | 1156 | if (iter == m_options.end()) 1157 | { 1158 | throw option_not_exists_exception(name); 1159 | } 1160 | 1161 | auto value = iter->second; 1162 | 1163 | //if no argument then just add it 1164 | if (!value->has_arg()) 1165 | { 1166 | parse_option(value, name); 1167 | } 1168 | else 1169 | { 1170 | //it must be the last argument 1171 | if (i + 1 == s.size()) 1172 | { 1173 | checked_parse_arg(argc, argv, current, value, name); 1174 | } 1175 | else if (value->value().has_implicit()) 1176 | { 1177 | parse_option(value, name, value->value().get_implicit_value()); 1178 | } 1179 | else 1180 | { 1181 | //error 1182 | throw option_requires_argument_exception(name); 1183 | } 1184 | } 1185 | } 1186 | } 1187 | else if (result[1].length() != 0) 1188 | { 1189 | const std::string& name = result[1]; 1190 | 1191 | auto iter = m_options.find(name); 1192 | 1193 | if (iter == m_options.end()) 1194 | { 1195 | throw option_not_exists_exception(name); 1196 | } 1197 | 1198 | auto opt = iter->second; 1199 | 1200 | //equals provided for long option? 1201 | if (result[3].length() != 0) 1202 | { 1203 | //parse the option given 1204 | 1205 | //but if it doesn't take an argument, this is an error 1206 | if (!opt->has_arg()) 1207 | { 1208 | throw option_not_has_argument_exception(name, result[3]); 1209 | } 1210 | 1211 | parse_option(opt, name, result[3]); 1212 | } 1213 | else 1214 | { 1215 | if (opt->has_arg()) 1216 | { 1217 | //parse the next argument 1218 | checked_parse_arg(argc, argv, current, opt, name); 1219 | } 1220 | else 1221 | { 1222 | //parse with empty argument 1223 | parse_option(opt, name); 1224 | } 1225 | } 1226 | } 1227 | 1228 | } 1229 | 1230 | ++current; 1231 | } 1232 | 1233 | for (auto& opt : m_options) 1234 | { 1235 | auto& detail = opt.second; 1236 | auto& value = detail->value(); 1237 | 1238 | if(!detail->count() && value.has_default()){ 1239 | detail->parse_default(); 1240 | } 1241 | } 1242 | 1243 | if (consume_remaining) 1244 | { 1245 | while (current < argc) 1246 | { 1247 | if (!consume_positional(argv[current])) { 1248 | break; 1249 | } 1250 | ++current; 1251 | } 1252 | 1253 | //adjust argv for any that couldn't be swallowed 1254 | while (current != argc) { 1255 | argv[nextKeep] = argv[current]; 1256 | ++nextKeep; 1257 | ++current; 1258 | } 1259 | } 1260 | 1261 | argc = nextKeep; 1262 | 1263 | } 1264 | 1265 | void 1266 | Options::add_option 1267 | ( 1268 | const std::string& group, 1269 | const std::string& s, 1270 | const std::string& l, 1271 | std::string desc, 1272 | std::shared_ptr value, 1273 | std::string arg_help 1274 | ) 1275 | { 1276 | auto stringDesc = toLocalString(std::move(desc)); 1277 | auto option = std::make_shared(stringDesc, value); 1278 | 1279 | if (s.size() > 0) 1280 | { 1281 | add_one_option(s, option); 1282 | } 1283 | 1284 | if (l.size() > 0) 1285 | { 1286 | add_one_option(l, option); 1287 | } 1288 | 1289 | //add the help details 1290 | auto& options = m_help[group]; 1291 | 1292 | options.options.emplace_back(HelpOptionDetails{s, l, stringDesc, 1293 | value->has_arg(), 1294 | value->has_default(), value->get_default_value(), 1295 | value->has_implicit(), value->get_implicit_value(), 1296 | std::move(arg_help), 1297 | value->is_container()}); 1298 | } 1299 | 1300 | void 1301 | Options::add_one_option 1302 | ( 1303 | const std::string& option, 1304 | std::shared_ptr details 1305 | ) 1306 | { 1307 | auto in = m_options.emplace(option, details); 1308 | 1309 | if (!in.second) 1310 | { 1311 | throw option_exists_error(option); 1312 | } 1313 | } 1314 | 1315 | String 1316 | Options::help_one_group(const std::string& g) const 1317 | { 1318 | typedef std::vector> OptionHelp; 1319 | 1320 | auto group = m_help.find(g); 1321 | if (group == m_help.end()) 1322 | { 1323 | return ""; 1324 | } 1325 | 1326 | OptionHelp format; 1327 | 1328 | size_t longest = 0; 1329 | 1330 | String result; 1331 | 1332 | if (!g.empty()) 1333 | { 1334 | result += toLocalString(" " + g + " options:\n"); 1335 | } 1336 | 1337 | for (const auto& o : group->second.options) 1338 | { 1339 | if (o.is_container && m_positional_set.find(o.l) != m_positional_set.end()) 1340 | { 1341 | continue; 1342 | } 1343 | 1344 | auto s = format_option(o); 1345 | longest = std::max(longest, stringLength(s)); 1346 | format.push_back(std::make_pair(s, String())); 1347 | } 1348 | 1349 | longest = std::min(longest, static_cast(OPTION_LONGEST)); 1350 | 1351 | //widest allowed description 1352 | auto allowed = size_t{76} - longest - OPTION_DESC_GAP; 1353 | 1354 | auto fiter = format.begin(); 1355 | for (const auto& o : group->second.options) 1356 | { 1357 | if (o.is_container && m_positional_set.find(o.l) != m_positional_set.end()) 1358 | { 1359 | continue; 1360 | } 1361 | 1362 | auto d = format_description(o, longest + OPTION_DESC_GAP, allowed); 1363 | 1364 | result += fiter->first; 1365 | if (stringLength(fiter->first) > longest) 1366 | { 1367 | result += '\n'; 1368 | result += toLocalString(std::string(longest + OPTION_DESC_GAP, ' ')); 1369 | } 1370 | else 1371 | { 1372 | result += toLocalString(std::string(longest + OPTION_DESC_GAP - 1373 | stringLength(fiter->first), 1374 | ' ')); 1375 | } 1376 | result += d; 1377 | result += '\n'; 1378 | 1379 | ++fiter; 1380 | } 1381 | 1382 | return result; 1383 | } 1384 | 1385 | void 1386 | Options::generate_group_help(String& result, const std::vector& groups) const 1387 | { 1388 | for (std::size_t i = 0; i < groups.size(); ++i) 1389 | { 1390 | String const& group_help = help_one_group(groups[i]); 1391 | if (empty(group_help)) continue; 1392 | result += group_help; 1393 | if (i < groups.size() - 1) 1394 | { 1395 | result += '\n'; 1396 | } 1397 | } 1398 | } 1399 | 1400 | void 1401 | Options::generate_all_groups_help(String& result) const 1402 | { 1403 | std::vector groups; 1404 | groups.reserve(m_help.size()); 1405 | 1406 | for (auto& group : m_help) 1407 | { 1408 | groups.push_back(group.first); 1409 | } 1410 | 1411 | generate_group_help(result, groups); 1412 | } 1413 | 1414 | std::string 1415 | Options::help(const std::vector& groups) const 1416 | { 1417 | String result = m_help_string + "\nUsage:\n " + 1418 | toLocalString(m_program) + " [OPTION...]"; 1419 | 1420 | if (m_positional.size() > 0) { 1421 | result += " " + toLocalString(m_positional_help); 1422 | } 1423 | 1424 | result += "\n\n"; 1425 | 1426 | if (groups.size() == 0) 1427 | { 1428 | generate_all_groups_help(result); 1429 | } 1430 | else 1431 | { 1432 | generate_group_help(result, groups); 1433 | } 1434 | 1435 | return toUTF8String(result); 1436 | } 1437 | 1438 | const std::vector 1439 | Options::groups() const 1440 | { 1441 | std::vector g; 1442 | 1443 | std::transform( 1444 | m_help.begin(), 1445 | m_help.end(), 1446 | std::back_inserter(g), 1447 | [] (const std::map::value_type& pair) 1448 | { 1449 | return pair.first; 1450 | } 1451 | ); 1452 | 1453 | return g; 1454 | } 1455 | 1456 | const HelpGroupDetails& 1457 | Options::group_help(const std::string& group) const 1458 | { 1459 | return m_help.at(group); 1460 | } 1461 | 1462 | } 1463 | 1464 | #if defined(__GNU__) 1465 | #pragma GCC diagnostic pop 1466 | #endif 1467 | 1468 | #endif //CXX_OPTS_HPP 1469 | -------------------------------------------------------------------------------- /src/image.cpp: -------------------------------------------------------------------------------- 1 | #include "image.hpp" 2 | 3 | ARGBImage::~ARGBImage() { 4 | delete[] data; 5 | } 6 | 7 | ARGBImage::ARGBImage( XImage* image, glm::ivec2 iloc, glm::ivec4 selectionrect, int channels, X11* x11 ) { 8 | this->imagex = iloc.x; 9 | this->imagey = iloc.y; 10 | this->channels = channels; 11 | glm::ivec2 spos = glm::ivec2( selectionrect.x, selectionrect.y ); 12 | offset = spos-iloc; 13 | long long int alpha_mask = ~(image->red_mask|image->green_mask|image->blue_mask); 14 | long long int roffset = get_shift(image->red_mask); 15 | long long int goffset = get_shift(image->green_mask); 16 | long long int boffset = get_shift(image->blue_mask); 17 | long long int aoffset = get_shift(alpha_mask); 18 | width = selectionrect.z; 19 | height = selectionrect.w; 20 | data = new unsigned char[width*height*channels]; 21 | // Clear necessary stuff 22 | // Top rect 23 | for ( int y = 0; y < glm::min(-offset.y,(int)height);y++ ) { 24 | for ( int x = 0; x < width;x++ ) { 25 | for ( int c = 0; c < channels;c++ ) { 26 | data[(y*width+x)*channels+c] = 0; 27 | } 28 | } 29 | } 30 | // Left rect 31 | for ( int y = 0; y < height;y++ ) { 32 | for ( int x = 0; x < glm::min(-offset.x,(int)width);x++ ) { 33 | for ( int c = 0; c < channels;c++ ) { 34 | data[(y*width+x)*channels+c] = 0; 35 | } 36 | } 37 | } 38 | // Bot rect 39 | for ( int y=-offset.y+image->height; ywidth; xwidth); 59 | int minh = glm::min( (int)(offset.y+height), image->height ); 60 | 61 | // Loop only through the intersecting parts, copying everything. 62 | // Also check if we have any useful alpha data. 63 | switch( channels ) { 64 | case 4: 65 | if ( aoffset >= image->depth ) { 66 | for(int y = maxy; y < minh; y++) { 67 | for(int x = maxx; x < minw; x++) { 68 | // This is where we just have RGB but require an RGBA image. 69 | computeRGBAPixel( data, image, x, y, roffset, goffset, boffset, width, offset ); 70 | } 71 | } 72 | } else { 73 | for(int y = maxy; y < minh; y++) { 74 | for(int x = maxx; x < minw; x++) { 75 | computeRGBAPixel( data, image, x, y, roffset, goffset, boffset, aoffset, width, offset ); 76 | } 77 | } 78 | } 79 | break; 80 | case 3: 81 | for(int y = maxy; y < minh; y++) { 82 | for(int x = maxx; x < minw; x++) { 83 | computeRGBPixel( data, image, x, y, roffset, goffset, boffset, width, offset ); 84 | } 85 | } 86 | break; 87 | default: 88 | throw new std::invalid_argument("Invalid number of channels provided to image."); 89 | } 90 | } 91 | 92 | void png_write_ostream(png_structp png_ptr, png_bytep data, png_size_t length) 93 | { 94 | std::ostream *stream = (std::ostream*)png_get_io_ptr(png_ptr); //Get pointer to ostream 95 | stream->write((char*)data,length); //Write requested amount of data 96 | } 97 | 98 | void png_flush_ostream(png_structp png_ptr) 99 | { 100 | std::ostream *stream = (std::ostream*)png_get_io_ptr(png_ptr); //Get pointer to ostream 101 | stream->flush(); 102 | } 103 | 104 | void user_error_fn(png_structp png_ptr, png_const_charp error_msg) 105 | { 106 | throw new std::runtime_error(error_msg); 107 | } 108 | 109 | void user_warning_fn(png_structp png_ptr, png_const_charp warning_msg) 110 | { 111 | std::cerr << warning_msg << "\n"; 112 | } 113 | 114 | void ARGBImage::writePNG( std::ostream& streamout, int quality ) { 115 | if ( quality > 10 || quality < 1 ) { 116 | throw new std::invalid_argument("Quality argument must be between 1 and 10"); 117 | } 118 | png_structp png = NULL; 119 | png_infop info = NULL; 120 | png_bytep *rows = new png_bytep[height]; 121 | 122 | png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); 123 | if(!png) throw new std::runtime_error( "Failed to write png image" ); 124 | info = png_create_info_struct(png); 125 | if(!info) throw new std::runtime_error( "Failed to write png image" ); 126 | png_set_error_fn(png, png_get_error_ptr(png), user_error_fn, user_warning_fn); 127 | png_set_write_fn(png, &streamout, png_write_ostream, png_flush_ostream); 128 | png_set_compression_level(png, quality-1); 129 | if ( channels == 4 ) { 130 | png_set_IHDR(png, info, width, height, 131 | 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, 132 | PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); 133 | } else { 134 | png_set_IHDR(png, info, width, height, 135 | 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, 136 | PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); 137 | } 138 | for( int i=0;inext_output_byte - out_buffer ); 204 | delete[] out_buffer; 205 | } 206 | 207 | void ARGBImage::writeBMP( std::ostream& streamout ) { 208 | int padding = (4 - (width * channels % 4)) % 4; 209 | int rowSize = width * channels + padding; 210 | int imageSize = height * rowSize; 211 | int fileSize = 54 + imageSize; 212 | 213 | unsigned char header [14] = { 214 | 'B', 'M', 215 | (unsigned char)fileSize, (unsigned char)(fileSize >> 8), 216 | (unsigned char)(fileSize >> 16), (unsigned char)(fileSize >> 24), 217 | // Reserved 218 | 0, 0, 0, 0, 219 | // Offset to start of image data 220 | 54, 0, 0, 0, 221 | }; 222 | 223 | unsigned char infoHeader [40] = { 224 | // Size of header 225 | 40, 0, 0, 0, 226 | (unsigned char)width, (unsigned char)(width >> 8), 227 | (unsigned char)(width >> 16), (unsigned char)(width >> 24), 228 | (unsigned char)height, (unsigned char)(height >> 8), 229 | (unsigned char)(height >> 16), (unsigned char)(height >> 24), 230 | // 1 Colour plane 231 | 1, 0, 232 | // 8 bits per channel 233 | (unsigned char)(8 * channels), 0, 234 | // No compression 235 | 0, 0, 0, 0, 236 | // Size of image including padding 237 | (unsigned char)imageSize, (unsigned char)(imageSize >> 8), 238 | (unsigned char)(imageSize >> 16), (unsigned char)(imageSize >> 24), 239 | // 72 DPI for printing as pixels/metre 240 | 0x13, 0x0B, 0, 0, 241 | 0x13, 0x0B, 0, 0, 242 | // 0 Palette colours, 0 important colours 243 | 0, 0, 0, 0, 244 | 0, 0, 0, 0, 245 | }; 246 | 247 | streamout.write( (const char*)header, 14 ); 248 | streamout.write( (const char*)infoHeader, 40 ); 249 | 250 | unsigned char* imageData = new unsigned char[imageSize]; 251 | 252 | for (int y = 0; y < height; y++) { 253 | for (int x = 0; x < width; x++) { 254 | // BMP is bottom to top and uses BGR/BGRA 255 | int outOffset = y*rowSize + x*channels; 256 | int inOffset = ((height-y-1)*width + x)*channels; 257 | imageData[outOffset] = data[inOffset + 2]; 258 | imageData[outOffset + 1] = data[inOffset + 1]; 259 | imageData[outOffset + 2] = data[inOffset]; 260 | if (channels == 4) { 261 | imageData[outOffset + 3] = data[inOffset+3]; 262 | } 263 | } 264 | 265 | for (int p = 0; p < padding; p++) { 266 | imageData[y*rowSize + width*channels + p] = 0; 267 | } 268 | } 269 | 270 | streamout.write( (const char*)imageData, imageSize ); 271 | delete[] imageData; 272 | } 273 | 274 | void ARGBImage::writeWEBP( std::ostream& streamout, int quality ) { 275 | // assume 4 channels 276 | if (channels != 4) { 277 | throw new std::runtime_error("WebP tried to save image with more than 4 channels"); 278 | } 279 | 280 | size_t size; 281 | uint8_t* out; 282 | if (quality == 10) { 283 | // encode lossless at highest quality 284 | size = WebPEncodeLosslessRGBA(data, width, height, width * 4, &out); 285 | } 286 | else { 287 | // otherwise, encode lossy 288 | size = WebPEncodeRGBA(data, width, height, width * 4, quality * 10.0f, &out); 289 | } 290 | 291 | if (size == 0) { 292 | throw new std::runtime_error("Failed to encode webp image"); 293 | } 294 | else { 295 | streamout.write((const char*)out, size); 296 | WebPFree(out); 297 | } 298 | } 299 | 300 | bool ARGBImage::intersect( XRRCrtcInfo* a, glm::vec4 b ) { 301 | if (a->x < b.x + b.z && 302 | a->x + a->width > b.x && 303 | a->y < b.y + b.w && 304 | a->height + a->y > b.y) { 305 | return true; 306 | } 307 | return false; 308 | } 309 | 310 | bool ARGBImage::containsCompletely( XRRCrtcInfo* a, glm::vec4 b ) { 311 | if ( b.x >= a->x && b.y >= a->y && b.x+b.z <= a->x+a->width && b.y+b.w <= a->y+a->height ) { 312 | return true; 313 | } 314 | return false; 315 | } 316 | 317 | void ARGBImage::mask(X11* x11) { 318 | if ( !x11->haveXRR ) { 319 | return; 320 | } 321 | std::vector physicalMonitors = x11->getCRTCS(); 322 | // Make sure a masking needs to happen, it's not a perfect detection, 323 | // but will detect most situations where a masking actually needs to happen. 324 | for ( int i=0;ifreeCRTCS(physicalMonitors); 329 | return; 330 | } 331 | } 332 | } 333 | unsigned char* copy = new unsigned char[width*height*channels]; 334 | // Zero out our copy 335 | memset( copy, 0, width*height*channels ); 336 | 337 | for ( int i=0;iy-imagey); yy+m->height-imagey);y++ ) { 345 | int start = (y*width + glm::max(0, m->x-imagex))*channels; 346 | int end = (y*width + glm::min(width,m->x+m->width-imagex))*channels; 347 | memcpy( copy+start, data+start, end-start ); 348 | } 349 | } 350 | x11->freeCRTCS(physicalMonitors); 351 | delete[] data; 352 | data = copy; 353 | } 354 | 355 | void ARGBImage::blendCursor( X11* x11 ) { 356 | if ( !x11->haveXFixes ) { 357 | return; 358 | } 359 | XFixesCursorImage* xcursor = XFixesGetCursorImage( x11->display ); 360 | if ( !xcursor ) { 361 | return; 362 | } 363 | // 64bit -> 32bit conversion 364 | unsigned char pixels[xcursor->width * xcursor->height * 4]; 365 | for ( unsigned int i=0;iwidth*xcursor->height;i++ ) { 366 | ((unsigned int*)pixels)[ i ] = (unsigned int)xcursor->pixels[ i ]; 367 | } 368 | xcursor->y -= xcursor->yhot + offset.x; 369 | xcursor->x -= xcursor->xhot + offset.y; 370 | for ( int y = glm::max(0,xcursor->y-imagey); yy+xcursor->height-imagey);y++ ) { 371 | for ( int x = glm::max(0,xcursor->x-imagex); x < glm::min((int)width,xcursor->x+xcursor->width-imagex);x++ ) { 372 | int cx = x-(xcursor->x-imagex); 373 | int cy = y-(xcursor->y-imagey); 374 | float alpha = (float)pixels[(cy*xcursor->width+cx)*4+3]/255.f; 375 | data[(y*width+x)*channels] = data[(y*width+x)*channels]*(1-alpha) + pixels[(cy*xcursor->width+cx)*4+2]*alpha; 376 | data[(y*width+x)*channels+1] = data[(y*width+x)*channels+1]*(1-alpha) + pixels[(cy*xcursor->width+cx)*4+1]*alpha; 377 | data[(y*width+x)*channels+2] = data[(y*width+x)*channels+2]*(1-alpha) + pixels[(cy*xcursor->width+cx)*4]*alpha; 378 | // If the original image has alpha, we need to override it. 379 | if ( channels == 4 ) { 380 | data[(y*width+x)*channels+3] = glm::min(data[(y*width+x)*channels+3]+pixels[(cy*xcursor->width+cx)*4+3],255); 381 | } 382 | } 383 | } 384 | } 385 | -------------------------------------------------------------------------------- /src/image.hpp: -------------------------------------------------------------------------------- 1 | /* image.hpp: image helper 2 | * 3 | * Copyright (C) 2014: Dalton Nell, Maim Contributors (https://github.com/naelstrof/slop/graphs/contributors). 4 | * 5 | * This file is part of Maim. 6 | * 7 | * Maim is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * Maim is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with Maim. If not, see . 19 | */ 20 | 21 | #ifndef N_IMAGE_H_ 22 | #define N_IMAGE_H_ 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | 34 | #include "x.hpp" 35 | 36 | static inline unsigned char computeRGBPixel(unsigned char* data, XImage* image, int x, int y, int roffset, int goffset, int boffset, int width, glm::ivec2 offset ) { 37 | int curpixel = ((y-offset.y)*width+((x-offset.x)))*3; 38 | unsigned int real = XGetPixel(image, x, y); 39 | data[curpixel] = (unsigned char)((real & image->red_mask) >> roffset); 40 | data[curpixel+1] = (unsigned char)((real & image->green_mask) >> goffset); 41 | data[curpixel+2] = (unsigned char)((real & image->blue_mask) >> boffset); 42 | return *data; 43 | } 44 | 45 | static inline unsigned char computeRGBAPixel(unsigned char* data, XImage* image, int x, int y, int roffset, int goffset, int boffset, int aoffset, int width, glm::ivec2 offset ) { 46 | int curpixel = ((y-offset.y)*width+(x-offset.x))*4; 47 | //unsigned int real = ((unsigned int*)image->data)[curpixel/4]; 48 | unsigned int real = XGetPixel(image, x, y); 49 | data[curpixel] = (unsigned char)((real & image->red_mask) >> roffset); 50 | data[curpixel+1] = (unsigned char)((real & image->green_mask) >> goffset); 51 | data[curpixel+2] = (unsigned char)((real & image->blue_mask) >> boffset); 52 | data[curpixel+3] = (unsigned char)(real >> aoffset); 53 | return *data; 54 | } 55 | 56 | static inline unsigned char computeRGBAPixel(unsigned char* data, XImage* image, int x, int y, int roffset, int goffset, int boffset, int width, glm::ivec2 offset ) { 57 | int curpixel = ((y-offset.y)*width+((x-offset.x)))*4; 58 | //unsigned int real = ((unsigned int*)image->data)[curpixel/4]; 59 | unsigned int real = XGetPixel(image, x, y); 60 | data[curpixel] = (unsigned char)((real & image->red_mask) >> roffset); 61 | data[curpixel+1] = (unsigned char)((real & image->green_mask) >> goffset); 62 | data[curpixel+2] = (unsigned char)((real & image->blue_mask) >> boffset); 63 | data[curpixel+3] = 255; 64 | return *data; 65 | } 66 | 67 | static inline int get_shift (int mask) { 68 | int shift = 0; 69 | while (mask) { 70 | if (mask & 1) { break; } 71 | shift++; 72 | mask >>= 1; 73 | } 74 | return shift; 75 | } 76 | 77 | class ARGBImage { 78 | private: 79 | unsigned char* data; 80 | unsigned int width; 81 | unsigned int height; 82 | unsigned int channels; 83 | int imagex, imagey; 84 | glm::ivec2 offset; 85 | bool intersect( XRRCrtcInfo* a, glm::vec4 b ); 86 | bool containsCompletely( XRRCrtcInfo* a, glm::vec4 b ); 87 | public: 88 | void blendCursor( X11* x11 ); 89 | void mask(X11* x11); 90 | ARGBImage( XImage* image, glm::ivec2 imageloc, glm::ivec4 selectionrect, int channels, X11* x11 ); 91 | ~ARGBImage(); 92 | void writePNG( std::ostream& streamout, int quality ); 93 | void writeJPEG( std::ostream& streamout, int quality ); 94 | void writeBMP( std::ostream& streamout ); 95 | void writeWEBP( std::ostream& streamout, int quality ); 96 | }; 97 | 98 | #endif 99 | -------------------------------------------------------------------------------- /src/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #include "cxxopts.hpp" 12 | #include "x.hpp" 13 | #include "image.hpp" 14 | 15 | class MaimOptions { 16 | public: 17 | MaimOptions(); 18 | std::string savepath; 19 | std::string format; 20 | Window window; 21 | Window parent; 22 | glm::vec4 geometry; 23 | float delay; 24 | int quality; 25 | bool select; 26 | bool hideCursor; 27 | bool geometryGiven; 28 | bool quiet; 29 | bool windowGiven; 30 | bool parentGiven; 31 | bool formatGiven; 32 | bool version; 33 | bool help; 34 | bool savepathGiven; 35 | bool captureBackground; 36 | }; 37 | 38 | MaimOptions::MaimOptions() { 39 | savepath = ""; 40 | window = None; 41 | parent = None; 42 | quality = 7; 43 | quiet = false; 44 | delay = 0; 45 | format = "png"; 46 | select = false; 47 | parentGiven = false; 48 | hideCursor = false; 49 | geometryGiven = false; 50 | savepathGiven = false; 51 | windowGiven = false; 52 | formatGiven = false; 53 | captureBackground = false; 54 | } 55 | 56 | Window parseWindow( std::string win, X11* x11 ) { 57 | if ( win == "root" ) { 58 | return x11->root; 59 | } 60 | Window retwin; 61 | std::string::size_type sz; 62 | try { 63 | retwin = std::stoi(win,&sz,0); 64 | } catch ( ... ) { 65 | try { 66 | retwin = std::stoul(win,&sz,16); 67 | } catch ( ... ) { 68 | throw new std::invalid_argument("Unable to parse value " + win + " as a window. Expecting integer, hex, or `root`."); 69 | } 70 | } 71 | return retwin; 72 | } 73 | 74 | glm::vec4 parseColor( std::string value ) { 75 | std::string valuecopy = value; 76 | const auto check_char = [&] (char c) { 77 | if (c != ',') { 78 | throw new std::invalid_argument("Unable to parse value `" + valuecopy + "` as a color. You need to use commas as separators."); 79 | } 80 | }; 81 | glm::vec4 found; 82 | std::string::size_type sz; 83 | try { 84 | found[0] = std::stof(value,&sz); 85 | check_char(value.at(sz)); 86 | value = value.substr(sz+1); 87 | found[1] = std::stof(value,&sz); 88 | check_char(value.at(sz)); 89 | value = value.substr(sz+1); 90 | found[2] = std::stof(value,&sz); 91 | if ( value.size() != sz ) { 92 | check_char(value.at(sz)); 93 | value = value.substr(sz+1); 94 | found[3] = std::stof(value,&sz); 95 | if ( value.size() != sz ) { 96 | throw "dur"; 97 | } 98 | } else { 99 | found[3] = 1; 100 | } 101 | } catch (std::invalid_argument* const e) { 102 | throw e; 103 | } catch ( ... ) { 104 | throw new std::invalid_argument("Unable to parse value `" + valuecopy + "` as a color. Should be in the format r,g,b or r,g,b,a. Like 1,1,1,1."); 105 | } 106 | return found; 107 | } 108 | 109 | glm::vec4 parseGeometry( std::string value ) { 110 | glm::vec4 found; 111 | std::string valuecopy = value; 112 | std::string::size_type sz = 0; 113 | glm::vec2 dim(0,0); 114 | int curpos = 0; 115 | glm::vec2 pos(0,0); 116 | try { 117 | if ( std::count(value.begin(), value.end(), '+') > 2 ) { 118 | throw "dur"; 119 | } 120 | if ( std::count(value.begin(), value.end(), '-') > 2 ) { 121 | throw "dur"; 122 | } 123 | if ( std::count(value.begin(), value.end(), 'x') > 1 ) { 124 | throw "dur"; 125 | } 126 | while( value != "" ) { 127 | switch( value[0] ) { 128 | case 'x': 129 | dim.y = std::stof(value.substr(1),&sz); 130 | sz++; 131 | break; 132 | case '+': 133 | pos[curpos++] = std::stof(value.substr(1), &sz); 134 | sz++; 135 | break; 136 | case '-': 137 | pos[curpos++] = -std::stof(value.substr(1), &sz); 138 | sz++; 139 | break; 140 | default: 141 | dim.x = std::stof(value,&sz); 142 | break; 143 | } 144 | value = value.substr(sz); 145 | } 146 | } catch ( ... ) { 147 | throw new std::invalid_argument("Unable to parse value `" + valuecopy + "` as a geometry. Should be in the format wxh+x+y, +x+y, or wxh. Like 600x400+10+20."); 148 | } 149 | found.x = pos.x; 150 | found.y = pos.y; 151 | found.z = dim.x; 152 | found.w = dim.y; 153 | return found; 154 | } 155 | 156 | MaimOptions* getMaimOptions( cxxopts::Options& options, X11* x11 ) { 157 | MaimOptions* foo = new MaimOptions(); 158 | foo->parentGiven = options.count("parent") > 0; 159 | if ( foo->parentGiven ) { 160 | foo->parent = parseWindow( options["parent"].as(), x11 ); 161 | } 162 | foo->windowGiven = options.count("window") > 0; 163 | if ( foo->windowGiven ) { 164 | foo->window = parseWindow( options["window"].as(), x11 ); 165 | } 166 | foo->geometryGiven = options.count("geometry") > 0; 167 | if ( foo->geometryGiven ) { 168 | foo->geometry = parseGeometry( options["geometry"].as() ); 169 | } 170 | if ( options.count( "delay" ) > 0 ) { 171 | foo->delay = options["delay"].as(); 172 | } 173 | if ( options.count( "hidecursor" ) > 0 ) { 174 | foo->hideCursor = options["hidecursor"].as(); 175 | } 176 | if ( options.count( "select" ) > 0 ) { 177 | foo->select = options["select"].as(); 178 | } 179 | if ( options.count( "quiet" ) > 0 ) { 180 | foo->quiet = options["quiet"].as(); 181 | } 182 | if ( options.count( "format" ) > 0 ) { 183 | foo->quiet = options["quiet"].as(); 184 | } 185 | foo->formatGiven = options.count("format") > 0; 186 | if ( foo->formatGiven ) { 187 | foo->format = options["format"].as(); 188 | if ( foo->format != "png" && foo->format != "jpg" && foo->format != "jpeg" && foo->format != "bmp" && foo->format != "webp" ) { 189 | throw new std::invalid_argument("Unknown format type: `" + foo->format + "`, only `png`, `jpg`, or `bmp` is allowed." ); 190 | } 191 | } 192 | if ( options.count( "quality" ) > 0 ) { 193 | foo->quality = options["quality"].as(); 194 | if ( foo->quality > 10 || foo->quality < 1 ) { 195 | throw new std::invalid_argument("Quality argument must be between 1 and 10"); 196 | } 197 | } 198 | if ( options.count( "capturebackground" ) > 0 ) { 199 | foo->captureBackground = options["capturebackground"].as(); 200 | } 201 | auto& positional = options["positional"].as>(); 202 | foo->savepathGiven = positional.size() > 0; 203 | //std::cerr << positional[0] << "\n"; 204 | if ( foo->savepathGiven ) { 205 | foo->savepath = positional[0]; 206 | } 207 | return foo; 208 | } 209 | 210 | slop::SlopOptions* getSlopOptions( cxxopts::Options& options ) { 211 | slop::SlopOptions* foo = new slop::SlopOptions(); 212 | if ( options.count( "bordersize" ) > 0 ) { 213 | foo->border = options["bordersize"].as(); 214 | } 215 | if ( options.count( "padding" ) > 0 ) { 216 | foo->padding = options["padding"].as(); 217 | } 218 | if ( options.count( "tolerance" ) > 0 ) { 219 | foo->tolerance = options["tolerance"].as(); 220 | } 221 | glm::vec4 color = glm::vec4( foo->r, foo->g, foo->b, foo->a ); 222 | if ( options.count( "color" ) > 0 ) { 223 | color = parseColor( options["color"].as() ); 224 | } 225 | foo->r = color.r; 226 | foo->g = color.g; 227 | foo->b = color.b; 228 | foo->a = color.a; 229 | if ( options.count( "nokeyboard" ) > 0 ) { 230 | foo->nokeyboard = options["nokeyboard"].as(); 231 | } 232 | if ( options.count( "noopengl" ) > 0 ) { 233 | foo->noopengl = options["noopengl"].as(); 234 | } 235 | if ( options.count( "xdisplay" ) > 0 ) { 236 | std::string xdisplay = options["xdisplay"].as(); 237 | char* cxdisplay = new char[xdisplay.length()+1]; 238 | memcpy( cxdisplay, xdisplay.c_str(), xdisplay.length() ); 239 | cxdisplay[xdisplay.length()]='\0'; 240 | foo->xdisplay = cxdisplay; 241 | } 242 | if ( options.count( "shader" ) > 0 ) { 243 | std::string shaders = options["shader"].as(); 244 | char* cshaders = new char[shaders.length()+1]; 245 | memcpy( cshaders, shaders.c_str(), shaders.length() ); 246 | cshaders[shaders.length()]='\0'; 247 | foo->shaders = cshaders; 248 | } 249 | if ( options.count( "quiet" ) > 0 ) { 250 | foo->quiet = options["quiet"].as(); 251 | } 252 | if ( options.count( "highlight" ) > 0 ) { 253 | foo->highlight = options["highlight"].as(); 254 | } 255 | if ( options.count( "nodrag" ) > 0 ) { 256 | foo->nodrag = options["nodrag"].as(); 257 | } 258 | if ( options.count( "nodecorations" ) > 0 ) { 259 | foo->nodecorations = options["nodecorations"].as(); 260 | if ( foo->nodecorations < 0 || foo->nodecorations > 2 ) { 261 | throw new std::invalid_argument( "--nodecorations must be between 0 and 2. Or be used as a flag." ); 262 | } 263 | } 264 | return foo; 265 | } 266 | 267 | const auto HELP_MESSAGE = R"MULTI_STRING( 268 | maim - make image 269 | 270 | SYNOPSIS 271 | maim [OPTIONS] [FILEPATH] 272 | 273 | DESCRIPTION 274 | maim (make image) is an utility that takes a screenshot of your desktop, 275 | and encodes a png, jpg, bmp or webp image of it. By default it outputs 276 | the encoded image data directly to standard output. 277 | 278 | OPTIONS 279 | -h, --help 280 | Print help and exit. 281 | 282 | -v, --version 283 | Print version and exit. 284 | 285 | -x, --xdisplay=hostname:number.screen_number 286 | Sets the xdisplay to use. 287 | 288 | -f, --format=STRING 289 | Sets the desired output format, by default maim will attempt to 290 | determine the desired output format automatically from the output 291 | file. If that fails it defaults to a lossless png format. Cur‐ 292 | rently supports `png`, `jpg`, `bmp` and `webp`. 293 | 294 | -i, --window=INT 295 | Sets the desired window to capture, defaults to the root window. 296 | 297 | -g, --geometry=GEOMETRY 298 | Sets the region to capture, uses local coordinates from the given 299 | window. So -g 10x30-5+0 would represent the rectangle wxh+x+y where 300 | w=10, h=30, x=-5, and y=0. x and y are the upper left location of 301 | this rectangle. 302 | 303 | -d, --delay=FLOAT 304 | Sets the time in seconds to wait before taking a screenshot. 305 | Prints a simple message to show how many seconds are left before a 306 | screenshot is taken. See --quiet for muting this message. 307 | 308 | -u, --hidecursor 309 | By default maim super-imposes the cursor onto the image, you can 310 | disable that behavior with this flag. 311 | 312 | -m, --quality 313 | An integer from 1 to 10 that determines the compression quality. 314 | For lossy formats (jpg and webp), lower settings will produce 315 | smaller files with lower quality, while higher settings will inc- 316 | rease quality at the cost of higher file size. A quality of 10 is 317 | lossless for webp. 318 | For png, lower settings will compress faster and produce larger 319 | files, while higher settings will compress slower, but produce 320 | smaller files. No effect on bmp images. 321 | 322 | -s, --select 323 | Enables an interactive selection mode where you may select the 324 | desired region or window before a screenshot is captured. Uses the 325 | settings below to determine the visuals and settings of slop. 326 | 327 | -w, --parent=WINDOW 328 | By default, maim assumes the --geometry values are in respect to 329 | the provided --window (or root if not provided). This parameter 330 | overrides this behavior by making the geometry be in respect to 331 | whatever window you provide to --parent. Allows for an integer, 332 | hex, or `root` for input. 333 | 334 | -B, --capturebackground 335 | By default, when capturing a window, maim will ignore anything 336 | beneath the specified window. This parameter overrides this and 337 | also captures elements underneath the window. 338 | 339 | SLOP OPTIONS 340 | -b, --bordersize=FLOAT 341 | Sets the selection rectangle's thickness. 342 | 343 | -p, --padding=FLOAT 344 | Sets the padding size for the selection, this can be negative. 345 | 346 | -t, --tolerance=FLOAT 347 | How far in pixels the mouse can move after clicking, and still be 348 | detected as a normal click instead of a click-and-drag. Setting 349 | this to 0 will disable window selections. Alternatively setting it 350 | to 9999999 would force a window selection. 351 | 352 | 353 | -D, --nodrag 354 | Select region with two clicks instead of click and drag 355 | 356 | -c, --color=FLOAT,FLOAT,FLOAT,FLOAT 357 | Sets the selection rectangle's color. Supports RGB or RGBA input. 358 | Depending on the system's window manager/OpenGL support, the opac‐ 359 | ity may be ignored. 360 | 361 | -r, --shader=STRING 362 | This sets the vertex shader, and fragment shader combo to use when 363 | drawing the final framebuffer to the screen. This obviously only 364 | works when OpenGL is enabled. The shaders are loaded from ~/.con‐ 365 | fig/maim. See https://github.com/naelstrof/slop for more informa‐ 366 | tion on how to create your own shaders. 367 | 368 | -n, --nodecorations=INT 369 | Sets the level of aggressiveness when trying to remove window 370 | decorations. `0' is off, `1' will try lightly to remove decora‐ 371 | tions, and `2' will recursively descend into the root tree until 372 | it gets the deepest available visible child under the mouse. 373 | Defaults to `0'. 374 | 375 | -l, --highlight 376 | Instead of outlining a selection, maim will highlight it instead. 377 | This is particularly useful if the color is set to an opacity 378 | lower than 1. 379 | 380 | -q, --quiet 381 | Disable any unnecessary cerr output. Any warnings or info simply 382 | won't print. 383 | 384 | -k, --nokeyboard 385 | Disables the ability to cancel selections with the keyboard. 386 | 387 | -o, --noopengl 388 | Disables graphics hardware acceleration. 389 | 390 | EXAMPLES 391 | Screenshot the active window and save it to the clipboard for quick past‐ 392 | ing. 393 | 394 | maim -i $(xdotool getactivewindow) | xclip -selection clipboard -t image/png 395 | 396 | Save a desktop screenshot with a unique ordered timestamp in the Pictures 397 | folder. 398 | 399 | maim ~/Pictures/$(date +%s).png 400 | 401 | Prompt for a region to screenshot. Add a fancy shadow to it, then save it 402 | to shadow.png. 403 | 404 | maim -s | convert - \( +clone -background black -shadow 80x3+5+5 \) +swap \ 405 | -background none -layers merge +repage shadow.png)MULTI_STRING"; 406 | 407 | int app( int argc, char** argv ) { 408 | // Use cxxopts to parse options, we pass them into a MaimOptions and SlopOptions object so we can swap out cxxopts if it's bad or whatever. 409 | cxxopts::Options options("maim", "Screenshot application."); 410 | options.add_options() 411 | ("h,help", "Print help and exit.") 412 | ("v,version", "Print version and exit.") 413 | ("x,xdisplay", "Sets the xdisplay to use", cxxopts::value()) 414 | ("f,format", "Sets the desired output format, by default maim will attempt to determine the desired output format automatically from the output file. If that fails it defaults to a lossless png format. Supports `png`, `jpg`, `bmp` and `webp`.", cxxopts::value()) 415 | ("i,window", "Sets the desired window to capture, defaults to the root window. Allows for an integer, hex, or `root` for input.", cxxopts::value()) 416 | ("g,geometry", "Sets the region to capture, uses local coordinates from the given window. So -g10x30-5+0 would represent the rectangle wxh+x+y where w=10, h=30, x=-5, and y=0. x and y are the upper left location of this rectangle.", cxxopts::value()) 417 | ("w,parent", "By default, maim assumes the --geometry values are in respect to the provided --window (or root if not provided). This parameter overrides this behavior by making the geometry be in respect to whatever window you provide to --parent. Allows for an integer, hex, or `root` for input.", cxxopts::value()) 418 | ("B,capturebackground", "By default, when capturing a window, maim will ignore anything beneath the specified window. This parameter overrides this and also captures elements underneath the window.") 419 | ("d,delay", "Sets the time in seconds to wait before taking a screenshot. Prints a simple message to show how many seconds are left before a screenshot is taken. See --quiet for muting this message.", cxxopts::value()->implicit_value("5")) 420 | ("u,hidecursor", "By default maim super-imposes the cursor onto the image, you can disable that behavior with this flag.") 421 | ("m,quality", "An integer from 1 to 10 that determines the compression quality. For lossy formats (jpg and webp), lower settings will produce smaller files with lower quality, while higher settings will increase quality at the cost of higher file size. A quality of 10 is lossless for webp. For png, lower settings will compress faster and produce larger files, while higher settings will compress slower, but produce smaller files. No effect on bmp images.", cxxopts::value()) 422 | ("s,select", "Enables an interactive selection mode where you may select the desired region or window before a screenshot is captured. Uses the settings below to determine the visuals and settings of slop.") 423 | ("b,bordersize", "Sets the selection rectangle's thickness.", cxxopts::value()) 424 | ("p,padding", "Sets the padding size for the selection, this can be negative.", cxxopts::value()) 425 | ("t,tolerance", "How far in pixels the mouse can move after clicking, and still be detected as a normal click instead of a click-and-drag. Setting this to 0 will disable window selections. Alternatively setting it to 9999999 would force a window selection.", cxxopts::value()) 426 | ("D,nodrag", "Select region with two clicks instead of click and drag") 427 | ("c,color", "Sets the selection rectangle's color. Supports RGB or RGBA input. Depending on the system's window manager/OpenGL support, the opacity may be ignored.", cxxopts::value()) 428 | ("r,shader", "This sets the vertex shader, and fragment shader combo to use when drawing the final framebuffer to the screen. This obviously only works when OpenGL is enabled. The shaders are loaded from ~/.config/maim. See https://github.com/naelstrof/slop for more information on how to create your own shaders.", cxxopts::value()) 429 | ("n,nodecorations", "Sets the level of aggressiveness when trying to remove window decroations. `0' is off, `1' will try lightly to remove decorations, and `2' will recursively descend into the root tree until it gets the deepest available visible child under the mouse. Defaults to `0'.", cxxopts::value()->implicit_value("1")) 430 | ("l,highlight", "Instead of outlining a selection, maim will highlight it instead. This is particularly useful if the color is set to an opacity lower than 1.") 431 | ("q,quiet", "Disable any unnecessary cerr output. Any warnings or info simply won't print.") 432 | ("k,nokeyboard", "Disables the ability to cancel selections with the keyboard.") 433 | ("o,noopengl", "Disables graphics hardware acceleration.") 434 | ("positional", "Positional parameters", cxxopts::value>()) 435 | ; 436 | options.parse_positional("positional"); 437 | options.parse(argc, argv); 438 | 439 | // Version checks and help menu don't require X11, and in fact will fail if running 440 | // in a headless environment. 441 | if ( options.count( "version" ) > 0 ) { 442 | std::cout << MAIM_VERSION << "\n"; 443 | return 0; 444 | } 445 | 446 | if ( options.count( "help" ) > 0 ) { 447 | std::cout << HELP_MESSAGE << std::endl; 448 | return 0; 449 | } 450 | 451 | slop::SlopOptions* slopOptions = getSlopOptions( options ); 452 | // Boot up x11 453 | X11* x11 = new X11(slopOptions->xdisplay); 454 | MaimOptions* maimOptions = getMaimOptions( options, x11 ); 455 | slop::SlopSelection selection(0,0,0,0,0,true); 456 | 457 | // Check if output is a tty before dumping binary data to it 458 | if ( isatty( fileno( stdout ) ) && !maimOptions->savepathGiven ) { 459 | std::cout << "Please provide an output path or redirect stdout to a file." << std::endl; 460 | std::cout << "Run maim --help for more information." << std::endl; 461 | return 0; 462 | } 463 | 464 | if ( maimOptions->select ) { 465 | if ( maimOptions->windowGiven || maimOptions->parentGiven || maimOptions->geometryGiven ) { 466 | throw new std::invalid_argument( "Interactive mode (--select) doesn't support the following parameters: --window, --parent, --geometry." ); 467 | } 468 | selection = SlopSelect(slopOptions); 469 | if ( selection.cancelled ) { 470 | if ( !maimOptions->quiet ) { 471 | std::cerr << "Selection was cancelled by keystroke or right-click.\n"; 472 | } 473 | return 1; 474 | } 475 | } 476 | 477 | if ( !maimOptions->formatGiven && maimOptions->savepathGiven && maimOptions->savepath.find_last_of(".") != std::string::npos ) { 478 | maimOptions->format = maimOptions->savepath.substr(maimOptions->savepath.find_last_of(".")+1); 479 | if ( maimOptions->format != "png" && maimOptions->format != "jpg" && maimOptions->format != "jpeg" && maimOptions->format != "bmp" && maimOptions->format != "webp") { 480 | throw new std::invalid_argument("Unknown format type: `" + maimOptions->format + "`, only `png`, `jpg`, `bmp` or `webp` is allowed." ); 481 | } 482 | } 483 | if ( !maimOptions->windowGiven ) { 484 | maimOptions->window = x11->root; 485 | } else { 486 | XWindowAttributes attr; 487 | XGetWindowAttributes(x11->display, maimOptions->window, &attr); 488 | if (attr.backing_store == NotUseful && attr.width == 1 && attr.height == 1) { 489 | Window root, parent; 490 | parent = None; 491 | Window* children; 492 | unsigned int nchildren; 493 | Window selectedWindow; 494 | XQueryTree( x11->display, maimOptions->window, &root, &parent, &children, &nchildren ); 495 | if ( parent != None ) { 496 | maimOptions->window = parent; 497 | } 498 | } 499 | } 500 | if ( !maimOptions->parentGiven ) { 501 | maimOptions->parent = maimOptions->window; 502 | } else if ( !maimOptions->geometryGiven ) { 503 | throw new std::invalid_argument( "Relative mode (--parent) requires --geometry." ); 504 | } 505 | if ( !maimOptions->geometryGiven ) { 506 | Window junk; 507 | glm::ivec4 geometry = getWindowGeometry( x11, maimOptions->window ); 508 | XTranslateCoordinates(x11->display, x11->root, maimOptions->window, geometry.x, geometry.y, &geometry.x, &geometry.y, &junk); 509 | maimOptions->geometry = geometry; 510 | } 511 | 512 | if ( !maimOptions->select ) { 513 | selection.x = maimOptions->geometry.x; 514 | selection.y = maimOptions->geometry.y; 515 | selection.w = maimOptions->geometry.z; 516 | selection.h = maimOptions->geometry.w; 517 | selection.id = maimOptions->window; 518 | } 519 | 520 | if ( maimOptions->captureBackground ) { 521 | selection.id = x11->root; 522 | } 523 | 524 | std::ostream* out; 525 | if ( maimOptions->savepathGiven ) { 526 | std::ofstream* file = new std::ofstream(); 527 | file->open(maimOptions->savepath.c_str()); 528 | if ( !file->is_open() ) { 529 | throw new std::runtime_error( "Failed to open file for writing: `" + maimOptions->savepath + "`." ); 530 | } 531 | out = file; 532 | } else { 533 | out = &std::cout; 534 | } 535 | 536 | // Then we grab the pixel buffer of the provided window/selection. 537 | if ( maimOptions->delay ) { 538 | if ( !maimOptions->quiet ) { 539 | std::cerr << "Snapshotting in..."; 540 | } 541 | while ( maimOptions->delay > 0 ) { 542 | std::this_thread::sleep_for(std::chrono::milliseconds(glm::clamp(glm::min(1000,(int)(maimOptions->delay*1000)),0,1000))); 543 | maimOptions->delay-=1; 544 | if ( !maimOptions->quiet ) { 545 | if ( maimOptions->delay <= 0 ) { 546 | std::cerr << "☺"; 547 | } else { 548 | std::cerr << maimOptions->delay << " "; 549 | } 550 | } 551 | } 552 | if ( !maimOptions->quiet ) { 553 | std::cerr << "\n"; 554 | } 555 | } 556 | // Localize to our parent 557 | int px, py; 558 | Window junk; 559 | XTranslateCoordinates( x11->display, maimOptions->parent, x11->root, (int)selection.x, (int)selection.y, &px, &py, &junk); 560 | glm::ivec2 imageloc; 561 | // Snapshot the image 562 | XImage* image = x11->getImage( selection.id, px, py, selection.w, selection.h, imageloc); 563 | 564 | int num_channels; 565 | if ( maimOptions->format == "png" || maimOptions->format == "webp" ) { 566 | // Convert it to an ARGB format, clipping it to the selection 567 | num_channels = 4; 568 | } else { 569 | // Otherwise (jpeg/bmp), convert to RGB, also clipping it to the selection 570 | num_channels = 3; 571 | } 572 | 573 | ARGBImage convert(image, imageloc, glm::vec4(px, py, selection.w, selection.h), num_channels, x11 ); 574 | 575 | if ( !maimOptions->hideCursor ) { 576 | convert.blendCursor( x11 ); 577 | } 578 | // Mask it if we're taking a picture of root 579 | if ( selection.id == x11->root ) { 580 | convert.mask(x11); 581 | } 582 | 583 | // then output it into into the desired format 584 | if (maimOptions->format == "png") { 585 | convert.writePNG(*out, maimOptions->quality ); 586 | } else if ( maimOptions->format == "jpg" || maimOptions->format == "jpeg" ) { 587 | convert.writeJPEG(*out, maimOptions->quality ); 588 | } else if ( maimOptions->format == "bmp" ) { 589 | convert.writeBMP(*out); 590 | } else if ( maimOptions->format == "webp" ) { 591 | convert.writeWEBP(*out, maimOptions->quality); 592 | } 593 | 594 | XDestroyImage( image ); 595 | 596 | if ( maimOptions->savepathGiven ) { 597 | std::ofstream* file = (std::ofstream*)out; 598 | file->close(); 599 | delete (std::ofstream*)out; 600 | } 601 | delete x11; 602 | delete maimOptions; 603 | if ( options.count( "xdisplay" ) > 0 ) { 604 | delete slopOptions->xdisplay; 605 | } 606 | if ( options.count( "shader" ) > 0 ) { 607 | delete slopOptions->shaders; 608 | } 609 | delete slopOptions; 610 | 611 | return 0; 612 | } 613 | 614 | int main( int argc, char** argv ) { 615 | try { 616 | return app( argc, argv ); 617 | } catch ( const cxxopts::OptionException& e) { 618 | std::cerr << e.what() << std::endl; 619 | std::cerr << "Try \"maim --help\" for more information." << std::endl; 620 | return 1; 621 | } catch( std::exception* e ) { 622 | std::cerr << "Maim encountered an error:\n" << e->what() << "\n"; 623 | return 1; 624 | } // let the operating system handle any other kind of exception. 625 | return 1; 626 | } 627 | -------------------------------------------------------------------------------- /src/x.cpp: -------------------------------------------------------------------------------- 1 | #include "x.hpp" 2 | 3 | static char _x_err = 0; 4 | static int 5 | TmpXError(Display * d, XErrorEvent * ev) { 6 | _x_err = 1; 7 | return 0; 8 | } 9 | 10 | glm::ivec4 getWindowGeometry( X11* x11, Window win ) { 11 | // First lets check for if we're a window manager frame. 12 | Window root, parent; 13 | Window* children; 14 | unsigned int num_children; 15 | XQueryTree( x11->display, win, &root, &parent, &children, &num_children); 16 | 17 | // To do that, we check if our top level child happens to have the _NET_FRAME_EXTENTS atom. 18 | unsigned char *data; 19 | Atom type_return; 20 | unsigned long nitems_return; 21 | unsigned long bytes_after_return; 22 | int format_return; 23 | bool window_frame = false; 24 | Window actualWindow = win; 25 | if ( win != x11->root && num_children > 0 && XGetWindowProperty( x11->display, children[num_children-1], 26 | XInternAtom( x11->display, "_NET_FRAME_EXTENTS", False), 27 | 0, LONG_MAX, False, XA_CARDINAL, &type_return, 28 | &format_return, &nitems_return, &bytes_after_return, 29 | &data) == Success ) { 30 | if ((type_return == XA_CARDINAL) && (format_return == 32) && (nitems_return == 4) && (data)) { 31 | actualWindow = children[num_children-1]; 32 | window_frame = true; 33 | } 34 | } 35 | XFree( children ); 36 | 37 | // If we're a window frame, we actually get the dimensions of the child window, then add the _NET_FRAME_EXTENTS to it. 38 | // (then add the border width of the window frame after that.) 39 | if ( window_frame ) { 40 | // First lets grab the border width. 41 | XWindowAttributes frameattr; 42 | XGetWindowAttributes( x11->display, win, &frameattr ); 43 | // Then lets grab the dims of the child window. 44 | XWindowAttributes attr; 45 | XGetWindowAttributes( x11->display, actualWindow, &attr ); 46 | unsigned int width = attr.width; 47 | unsigned int height = attr.height; 48 | // We combine both border widths. 49 | unsigned int border = attr.border_width+frameattr.border_width; 50 | int x, y; 51 | // Gotta translate them into root coords, we can adjust for the border width here. 52 | Window junk; 53 | XTranslateCoordinates( x11->display, actualWindow, attr.root, -border, -border, &x, &y, &junk ); 54 | width += border*2; 55 | height += border*2; 56 | // Now uh, remember that _NET_FRAME_EXTENTS stuff? That's the window frame information. 57 | // We HAVE to do this because mutter likes to mess with window sizes with shadows and stuff. 58 | unsigned long* ldata = (unsigned long*)data; 59 | width += ldata[0] + ldata[1]; 60 | height += ldata[2] + ldata[3]; 61 | x -= ldata[0]; 62 | y -= ldata[2]; 63 | XFree( data ); 64 | return glm::vec4( x, y, width, height ); 65 | } else { 66 | // Either the WM is malfunctioning, or the window secified isn't a window manager frame. 67 | // so we just rely on X. 68 | XWindowAttributes attr; 69 | XGetWindowAttributes( x11->display, win, &attr ); 70 | unsigned int width = attr.width; 71 | unsigned int height = attr.height; 72 | // We combine both border widths. 73 | unsigned int border = attr.border_width; 74 | int x, y; 75 | // Gotta translate them into root coords, we can adjust for the border width here. 76 | Window junk; 77 | XTranslateCoordinates( x11->display, win, attr.root, -border, -border, &x, &y, &junk ); 78 | width += border*2; 79 | height += border*2; 80 | return glm::vec4( x, y, width, height ); 81 | } 82 | } 83 | 84 | std::vector X11::getCRTCS() { 85 | std::vector monitors; 86 | if ( !res ) { 87 | return monitors; 88 | } 89 | for ( int i=0;incrtc;i++ ) { 90 | monitors.push_back( XRRGetCrtcInfo( display, res, res->crtcs[ i ] ) ); 91 | } 92 | return monitors; 93 | } 94 | 95 | void X11::freeCRTCS( std::vector monitors ) { 96 | for ( unsigned int i=0;idisplay, this->root, draw, x, y, &localx, &localy, &junk); 156 | 157 | if ( haveXComposite ) { 158 | // We redirect all the pixmaps offscreen, so that they won't be corrupted if obscured. 159 | for ( int i = 0; i < ScreenCount( display ); i++ ) { 160 | XCompositeRedirectSubwindows( display, RootWindow( display, i ), CompositeRedirectAutomatic ); 161 | } 162 | // We don't have to worry about undoing the redirect, since as soon as maim closes X knows to undo it. 163 | } 164 | if ( haveXRender && haveXFixes ) { 165 | return getImageUsingXRender( draw, localx, localy, w, h ); 166 | } 167 | // This stuff doesn't work very well... 168 | //if ( haveXShm ) { 169 | //XErrorHandler ph = XSetErrorHandler(TmpXError); 170 | //XImage* check = getImageUsingXShm( draw, localx, localy, w, h ); 171 | //XSetErrorHandler(ph); 172 | //if ( !_x_err && check != None ) { 173 | //return check; 174 | //} 175 | //} 176 | return XGetImage( display, draw, localx, localy, w, h, AllPlanes, ZPixmap ); 177 | } 178 | 179 | XImage* X11::getImageUsingXRender( Window draw, int localx, int localy, int w, int h ) { 180 | // We use XRender to grab the drawable, since it'll save it in a format we like. 181 | XWindowAttributes attr; 182 | XGetWindowAttributes( display, draw, &attr ); 183 | XRenderPictFormat *format = XRenderFindVisualFormat( display, attr.visual ); 184 | bool hasAlpha = ( format->type == PictTypeDirect && format->direct.alphaMask ); 185 | XRenderPictureAttributes pa; 186 | pa.subwindow_mode = IncludeInferiors; 187 | Picture picture = XRenderCreatePicture( display, draw, format, CPSubwindowMode, &pa ); 188 | if ( draw != root ) { 189 | XserverRegion region = findRegion( draw ); 190 | // Also we use XRender because of this neato function here. 191 | XFixesSetPictureClipRegion( display, picture, 0, 0, region ); 192 | XFixesDestroyRegion( display, region ); 193 | } 194 | 195 | Pixmap pixmap = XCreatePixmap(display, root, w, h, 32); 196 | XRenderPictureAttributes pa2; 197 | 198 | XRenderPictFormat *format2 = XRenderFindStandardFormat(display, PictStandardARGB32); 199 | Picture pixmapPicture = XRenderCreatePicture( display, pixmap, format2, 0, &pa2 ); 200 | XRenderColor c; 201 | c.red = 0x0000; 202 | c.green = 0x0000; 203 | c.blue = 0x0000; 204 | c.alpha = 0x0000; 205 | XRenderFillRectangle (display, PictOpSrc, pixmapPicture, &c, 0, 0, w, h); 206 | XRenderComposite(display, hasAlpha ? PictOpOver : PictOpSrc, picture, 0, 207 | pixmapPicture, localx, localy, 0, 0, 0, 0, 208 | w, h); 209 | XImage* temp = XGetImage( display, pixmap, 0, 0, w, h, AllPlanes, ZPixmap ); 210 | temp->red_mask = format2->direct.redMask << format2->direct.red; 211 | temp->green_mask = format2->direct.greenMask << format2->direct.green; 212 | temp->blue_mask = format2->direct.blueMask << format2->direct.blue; 213 | temp->depth = format2->depth; 214 | return temp; 215 | } 216 | 217 | bool X11::hasClipping( Window d ) { 218 | int bShaped, xbs, ybs, cShaped, xcs, ycs; 219 | unsigned int wbs, hbs, wcs, hcs; 220 | XShapeQueryExtents ( display, d, &bShaped, &xbs, &ybs, &wbs, &hbs, &cShaped, &xcs, &ycs, &wcs, &hcs ); 221 | return bShaped; 222 | } 223 | 224 | XserverRegion X11::findRegion( Window d ) { 225 | XserverRegion rootRegion = XFixesCreateRegionFromWindow( display, d, WindowRegionBounding ); 226 | glm::vec4 rootgeo = getWindowGeometry( this, d ); 227 | XFixesTranslateRegion( display, rootRegion, rootgeo.x, rootgeo.y ); // Regions are in respect to the root window by default. 228 | unionClippingRegions( rootRegion, d ); 229 | unionBorderRegions( rootRegion, d ); 230 | return rootRegion; 231 | } 232 | 233 | void X11::unionBorderRegions( XserverRegion rootRegion, Window d ) { 234 | glm::vec4 bordergeo = getWindowGeometry( this, d ); 235 | XRectangle* rects = new XRectangle[1]; 236 | rects[0].x = bordergeo.x; 237 | rects[0].y = bordergeo.y; 238 | rects[0].width = bordergeo.z; 239 | rects[0].height = bordergeo.w; 240 | XserverRegion borderRegionRect = XFixesCreateRegion( display, rects, 1 ); 241 | XWindowAttributes attr; 242 | XGetWindowAttributes( display, d, &attr ); 243 | rects[0].x += attr.border_width; 244 | rects[0].y += attr.border_width; 245 | rects[0].width -= attr.border_width*2; 246 | rects[0].height -= attr.border_width*2; 247 | XserverRegion regionRect = XFixesCreateRegion( display, rects, 1 ); 248 | XFixesSubtractRegion( display, regionRect, borderRegionRect, regionRect ); 249 | delete[] rects; 250 | XFixesUnionRegion( display, rootRegion, rootRegion, regionRect ); 251 | XFixesDestroyRegion( display, regionRect ); 252 | XFixesDestroyRegion( display, borderRegionRect ); 253 | } 254 | 255 | void X11::unionClippingRegions( XserverRegion rootRegion, Window child ) { 256 | Window root, parent; 257 | Window* children; 258 | unsigned int num_children; 259 | XQueryTree( display, child, &root, &parent, &children, &num_children); 260 | for ( unsigned int i=0;ibytes_per_line * xim->height, IPC_CREAT | 0777); 303 | /* if the get succeeds */ 304 | if (thing.shmid != -1) { 305 | /* set the params for the shm segment */ 306 | thing.readOnly = False; 307 | thing.shmaddr = xim->data = (char*)shmat(thing.shmid, 0, 0); 308 | /* get the shm addr for this data chunk */ 309 | if (xim->data != (char *)-1) { 310 | XShmAttach(display, &thing); 311 | XShmGetImage(display, draw, xim, localx, localy, AllPlanes); 312 | return xim; 313 | //shmdt(thing.shmaddr); 314 | } 315 | /* get failed - out of shm id's or shm segment too big ? */ 316 | /* remove the shm id we created */ 317 | shmctl(thing.shmid, IPC_RMID, 0); 318 | shmdt(thing.shmaddr); 319 | } 320 | return None; 321 | } 322 | -------------------------------------------------------------------------------- /src/x.hpp: -------------------------------------------------------------------------------- 1 | /* x.hpp: initializes x11 2 | * 3 | * Copyright (C) 2014: Dalton Nell, Maim Contributors (https://github.com/naelstrof/slop/graphs/contributors). 4 | * 5 | * This file is part of Maim. 6 | * 7 | * Maim is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * Maim is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with Maim. If not, see . 19 | */ 20 | 21 | #ifndef N_X_H_ 22 | #define N_X_H_ 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | //#include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | 39 | class X11 { 40 | private: 41 | bool hasClipping( Window d ); 42 | XserverRegion findRegion( Window d ); 43 | void unionClippingRegions( XserverRegion rootRegion, Window child ); 44 | void unionBorderRegions( XserverRegion rootRegion, Window d ); 45 | XImage* getImageUsingXRender( Window draw, int localx, int localy, int w, int h ); 46 | XImage* getImageUsingXShm( Window draw, int localx, int localy, int w, int h ); 47 | public: 48 | bool haveXComposite; 49 | bool haveXRender; 50 | bool haveXShm; 51 | bool haveXFixes; 52 | bool haveXRR; 53 | X11( std::string displayName ); 54 | ~X11(); 55 | Display* display; 56 | Visual* visual; 57 | Screen* screen; 58 | Window root; 59 | XImage* getImage( Window d, int x, int y, int w, int h, glm::ivec2& imageloc ); 60 | XRRScreenResources* res; 61 | std::vector getCRTCS(); 62 | void freeCRTCS( std::vector monitors ); 63 | }; 64 | 65 | glm::ivec4 getWindowGeometry( X11* x11, Window win ); 66 | 67 | #endif 68 | --------------------------------------------------------------------------------