pax_global_header00006660000000000000000000000064135514613730014522gustar00rootroot0000000000000052 comment=9a3ff205841c583a7eef23de6da499a0d45bcfa8 maim-5.5.3/000077500000000000000000000000001355146137300124575ustar00rootroot00000000000000maim-5.5.3/.gitignore000066400000000000000000000003201355146137300144420ustar00rootroot00000000000000# These files are ignored since cmake generates them from cmdline.in src/cmdline.h # Ignore Cmake generated files CMakeFiles/* Makefile cmake_install.cmake CMakeCache.txt # Ignore output artifacts bin/maim maim-5.5.3/CMakeLists.txt000066400000000000000000000053471355146137300152300ustar00rootroot00000000000000cmake_minimum_required( VERSION 3.1.3 ) project(maim VERSION 5.5.3 LANGUAGES CXX) if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE "Debug") endif() if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "/usr" CACHE PATH "..." FORCE) endif() include(GNUInstallDirs) add_definitions(-DMAIM_VERSION="v${PROJECT_VERSION}") set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/bin/") # Sources set( source src/x.cpp src/image.cpp src/main.cpp ) set( BIN_TARGET "${PROJECT_NAME}" ) # Executable add_executable( "${BIN_TARGET}" ${source} ) # Obtain library paths and make sure they exist. set( CMAKE_MODULE_PATH "${CMAKE_MODULE_PATH}" "${CMAKE_SOURCE_DIR}/modules" ) find_package( PNG REQUIRED ) find_package( JPEG REQUIRED ) find_package( XRandr REQUIRED ) find_package( XRender REQUIRED ) find_package( XFixes REQUIRED ) find_package( XComposite REQUIRED ) find_package( X11 REQUIRED ) find_package( SLOP REQUIRED ) find_package( Threads REQUIRED ) set_property(TARGET ${BIN_TARGET} PROPERTY CXX_STANDARD_REQUIRED ON) set_property(TARGET ${BIN_TARGET} PROPERTY CXX_STANDARD 11) set_property(TARGET ${BIN_TARGET} PROPERTY CXX_EXTENSIONS OFF) # Includes include_directories( ${XRANDR_INCLUDE_DIR} ${X11_INCLUDE_DIR} ${SLOP_INCLUDE_DIR} ${XFIXES_INCLUDE_DIR} ${XCOMPOSITE_INCLUDE_DIR} ${JPEG_INCLUDE_DIR} ${XRANDR_INCLUDE_DIR} ${XRENDER_INCLUDE_DIR} ${PNG_INCLUDE_DIRS} ) # Libraries target_link_libraries( ${BIN_TARGET} ${CMAKE_THREAD_LIBS_INIT} ${X11_LIBRARIES} ${PNG_LIBRARIES} ${XFIXES_LIBRARY} ${XCOMPOSITE_LIBRARY} ${XRANDR_LIBRARY} ${JPEG_LIBRARIES} ${XRENDER_LIBRARY} ${SLOP_LIBRARIES} ) if( ${CMAKE_VERSION} VERSION_LESS 3.7 ) message( WARNING "CMake version is below 3.7, CMake version >= 3.7 is required for unicode support." ) else() find_package(ICU COMPONENTS uc) set( MAIM_UNICODE TRUE CACHE BOOL "To enable or disable unicode support." ) if ( MAIM_UNICODE AND ICU_FOUND ) # ICU is required for old nvidia drivers to work for whatever reason. add_definitions(-DCXXOPTS_USE_UNICODE) include_directories( ${ICU_INCLUDE_DIR} ) target_link_libraries( ${BIN_TARGET} ${ICU_UC_LIBRARIES} ) endif() endif() install( TARGETS ${BIN_TARGET} DESTINATION "${CMAKE_INSTALL_BINDIR}" ) install( FILES "${CMAKE_SOURCE_DIR}/maim.1" DESTINATION "${CMAKE_INSTALL_MANDIR}/man1" COMPONENT doc ) maim-5.5.3/COPYING000066400000000000000000001045131355146137300135160ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . maim-5.5.3/README.md000066400000000000000000000110361355146137300137370ustar00rootroot00000000000000# maim maim (Make Image) is a utility that takes screenshots of your desktop. It's meant to overcome shortcomings of scrot and performs better in several ways. ## Features * Takes screenshots of your desktop, and saves it in png or jpg format. * Takes screenshots predetermined regions or windows, useful for automation. * Allows a users to select a region, or window, before taking a screenshot on the fly. ![screenshot with selection](http://i.imgur.com/ILZKJCT.png) * Blends the system cursor to the screenshot. ![screenshot with cursor](http://i.imgur.com/PD1bgBg.png) * Masks off-screen pixels to be transparent or black. ![screenshot with masked pixels](http://i.imgur.com/kMkcHlZ.png) * Maim cleanly pipes screenshots directly to standard output (unless otherwise specified). Allowing for command chaining. * Maim supports anything slop does, even selection [shaders](https://github.com/naelstrof/slop#shaders)! ![slop animation](http://i.giphy.com/kfBLafeJfLs2Y.gif) ## Installation ### Install using your Package Manager (Preferred) * [Arch Linux: community/maim](https://www.archlinux.org/packages/community/x86_64/maim/) * [Debian: maim](https://tracker.debian.org/pkg/maim) * [Void Linux: maim](https://github.com/voidlinux/void-packages/blob/24ac22af44018e2598047e5ef7fd3522efa79db5/srcpkgs/maim/template) * [FreeBSD: graphics/maim](http://www.freshports.org/graphics/maim/) * [NetBSD: x11/maim](http://pkgsrc.se/x11/maim) * [OpenBSD: graphics/maim](http://openports.se/graphics/maim) * [CRUX: 6c37/maim](https://github.com/6c37/crux-ports/tree/3.3/maim) * [Gentoo: media-gfx/maim](https://packages.gentoo.org/packages/media-gfx/maim) * [NixOS: maim](https://github.com/NixOS/nixpkgs/blob/master/pkgs/tools/graphics/maim/default.nix) * [GNU Guix: maim](https://www.gnu.org/software/guix/packages/#maim) * [Ravenports: maim](http://www.ravenports.com/catalog/bucket_B4/maim/standard/) * [Fedora: maim-copr](https://copr.fedorainfracloud.org/coprs/shymega/maim-copr/) * Please make a package for maim on your favorite system, and make a pull request to add it to this list. ### Install using CMake (Requires CMake, git, libXrender, libXfixes, libGLM, libxcomposite, libxrandr) ```bash git clone https://github.com/naelstrof/slop.git cd slop cmake -DCMAKE_INSTALL_PREFIX="/usr" ./ make && sudo make install cd .. git clone https://github.com/naelstrof/maim.git cd maim cmake -DCMAKE_INSTALL_PREFIX="/usr" ./ make && sudo make install ``` ## Examples Maim allows for a lot of unique and interesting functionalities. Here's an example of a few interactions. * 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. ```bash $ maim -s | xclip -selection clipboard -t image/png ``` * 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. ```bash $ maim -st 9999999 | convert - \( +clone -background black -shadow 80x3+5+5 \) +swap -background none -layers merge +repage shadow.png ``` * 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... ```bash $ maim -st 0 | convert - -resize 1x1\! -format '%[pixel:p{0,0}]' info:- ``` * This is a basic, but useful command that simply screenshots the current active window. ```bash $ maim -i $(xdotool getactivewindow) ~/mypicture.jpg ``` * 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. ```bash $ maim ~/Pictures/$(date +%s).png ``` * 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. ```bash $ maim | feh - -x & maim -s cropped.png ``` * 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. ```bash $ maim -s /tmp/screenshot.png; imgur.sh /tmp/screenshot.png | xclip -selection clipboard ``` maim-5.5.3/license.txt000066400000000000000000000013171355146137300146440ustar00rootroot00000000000000Copyright (C) 2014 Dalton Nell, Maim Contributors (https://github.com/naelstrof/maim/graphs/contributors) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . maim-5.5.3/maim.1000066400000000000000000000121201355146137300134600ustar00rootroot00000000000000.\" Manpage for maim. .\" Contact naelstrof@gmail.com to correct errors or typos. .TH maim 1 2017-03-21 Linux "maim man page" .SH NAME maim \- make image .SH SYNOPSIS maim [OPTIONS] [FILEPATH] .SH DESCRIPTION maim (make image) is an utility that takes a screenshot of your desktop, and encodes a png or jpg image of it. By default it outputs the encoded image data directly to standard output. .SH OPTIONS .TP .BR \-h ", " \-\-help Print help and exit. .TP .BR \-v ", " \-\-version Print version and exit. .TP .BR \-x ", " \-\-xdisplay=\fIhostname:number.screen_number\fR Sets the xdisplay to use. .TP .BR \-f ", " \-\-format=\fISTRING\fR 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` or `jpg`. .TP .BR \-i ", " \-\-window=\fIWINDOW\fR Sets the desired window to capture, defaults to the root window. Allows for an integer, hex, or `root` for input. .TP .BR \-g ", " \-\-geometry=\fIGEOMETRY\fR 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. .TP .BR \-w ", " \-\-parent=\fIWINDOW\fR 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. .TP .BR \-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. .TP .BR \-d ", " \-\-delay=\fIFLOAT\fR 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. .TP .BR \-u ", " \-\-hidecursor By default maim super-imposes the cursor onto the image, you can disable that behavior with this flag. .TP .BR \-m ", " \-\-quality An integer from 1 to 10 that determines the compression quality. 1 is the highest (and lossiest) compression available for the provided format. For example a setting of `1` with png (a lossless format) would increase filesize and decrease decoding time. While a setting of `1` on a jpeg would create a pixel mush. .TP .BR \-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. .SH SLOP OPTIONS .TP .BR \-b ", " \-\-bordersize=\fIFLOAT\fR Sets the selection rectangle's thickness. .TP .BR \-p ", " \-\-padding=\fIFLOAT\fR Sets the padding size for the selection, this can be negative. .TP .BR \-t ", " \-\-tolerance=\fIFLOAT\fR 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. .TP .BR \-c ", " \-\-color=\fIFLOAT,FLOAT,FLOAT,FLOAT\fR 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. .TP .BR \-r ", " \-\-shader=\fISTRING\fR 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. .TP .BR \-n ", " \-\-nodecorations=\fIINT\fR 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'. .TP .BR \-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. .TP .BR \-q ", " \-\-quiet Disable any unnecessary cerr output. Any warnings or info simply won't print. .TP .BR \-k ", " \-\-nokeyboard Disables the ability to cancel selections with the keyboard. .TP .BR \-o ", " \-\-noopengl Disables graphics hardware acceleration. .SH EXAMPLES Screenshot the active window and save it to the clipboard for quick pasting. .PP .nf .RS maim -i $(xdotool getactivewindow) | xclip -selection clipboard -t image/png .RE .fi .PP Save a desktop screenshot with a unique ordered timestamp in the Pictures folder. .PP .nf .RS maim ~/Pictures/$(date +%s).png .RE .fi .PP Prompt for a region to screenshot. Add a fancy shadow to it, then save it to shadow.png. .PP .nf .RS maim -s | convert - \\( +clone -background black -shadow 80x3+5+5 \\) +swap -background none -layers merge +repage shadow.png .RE .fi .PP .SH SEE ALSO .BR slop(1) .SH BUGS No known bugs. .SH AUTHOR Dalton Nell (naelstrof@gmail.com) maim-5.5.3/modules/000077500000000000000000000000001355146137300141275ustar00rootroot00000000000000maim-5.5.3/modules/FindGLX.cmake000066400000000000000000000024421355146137300163660ustar00rootroot00000000000000# Try to find GLX. Once done, this will define: # # GLX_FOUND - variable which returns the result of the search # GLX_INCLUDE_DIRS - list of include directories # GLX_LIBRARIES - options for the linker #============================================================================= # Copyright 2012 Benjamin Eikel # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= # (To distribute this file outside of CMake, substitute the full # License text for the above reference.) find_package(PkgConfig) pkg_check_modules(PC_GLX QUIET glx) find_path(GLX_INCLUDE_DIR GL/glx.h HINTS ${PC_GLX_INCLUDEDIR} ${PC_GLX_INCLUDE_DIRS} ) find_library(GLX_LIBRARY GL HINTS ${PC_GLX_LIBDIR} ${PC_GLX_LIBRARY_DIRS} ) set(GLX_INCLUDE_DIRS ${GLX_INCLUDE_DIR}) set(GLX_LIBRARIES ${GLX_LIBRARY}) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(GLX DEFAULT_MSG GLX_INCLUDE_DIR GLX_LIBRARY ) mark_as_advanced( GLX_INCLUDE_DIR GLX_LIBRARY ) maim-5.5.3/modules/FindSLOP.cmake000066400000000000000000000015241355146137300165110ustar00rootroot00000000000000# - Find SLOP # Find the SLOP libraries # # This module defines the following variables: # SLOP_FOUND - 1 if SLOP_INCLUDE_DIR & SLOP_LIBRARY are found, 0 otherwise # SLOP_INCLUDE_DIR - where to find Xlib.h, etc. # SLOP_LIBRARY - the X11 library # find_path( SLOP_INCLUDE_DIR NAMES slop.hpp PATH_SUFFIXES /usr/include /include DOC "The SLOP include directory" ) find_library( SLOP_LIBRARIES NAMES slopy slopy.so slop slop.so PATHS /usr/lib /lib DOC "The SLOP library" ) FIND_PACKAGE(X11 REQUIRED) FIND_PACKAGE(GLX REQUIRED) list(APPEND SLOP_LIBRARIES ${X11_LIBRARIES} ${GLX_LIBRARY} ) if( SLOP_INCLUDE_DIR AND SLOP_LIBRARY ) set( SLOP_FOUND 1 ) else() set( SLOP_FOUND 0 ) endif() mark_as_advanced( SLOP_INCLUDE_DIR SLOP_LIBRARY ) maim-5.5.3/modules/FindXComposite.cmake000066400000000000000000000014661355146137300200330ustar00rootroot00000000000000# - Find XComposite # Find the XComposite libraries # # This module defines the following variables: # XCOMPOSITE_FOUND - 1 if XCOMPOSITE_INCLUDE_DIR & XCOMPOSITE_LIBRARY are found, 0 otherwise # XCOMPOSITE_INCLUDE_DIR - where to find Xlib.h, etc. # XCOMPOSITE_LIBRARY - the X11 library # find_path( XCOMPOSITE_INCLUDE_DIR NAMES X11/extensions/Xcomposite.h PATH_SUFFIXES X11/extensions DOC "The XComposite include directory" ) find_library( XCOMPOSITE_LIBRARY NAMES Xcomposite PATHS /usr/lib /lib DOC "The XComposite library" ) if( XCOMPOSITE_INCLUDE_DIR AND XCOMPOSITE_LIBRARY ) set( XCOMPOSITE_FOUND 1 ) else() set( XCOMPOSITE_FOUND 0 ) endif() mark_as_advanced( XCOMPOSITE_INCLUDE_DIR XCOMPOSITE_LIBRARY ) maim-5.5.3/modules/FindXFixes.cmake000066400000000000000000000013521355146137300171410ustar00rootroot00000000000000# - Find XFixes # Find the XFixes libraries # # This module defines the following variables: # XFIXES_FOUND - 1 if XFIXES_INCLUDE_DIR & XFIXES_LIBRARY are found, 0 otherwise # XFIXES_INCLUDE_DIR - where to find Xlib.h, etc. # XFIXES_LIBRARY - the X11 library # find_path( XFIXES_INCLUDE_DIR NAMES X11/extensions/Xfixes.h PATH_SUFFIXES X11/extensions DOC "The XFixes include directory" ) find_library( XFIXES_LIBRARY NAMES Xfixes PATHS /usr/lib /lib DOC "The XFixes library" ) if( XFIXES_INCLUDE_DIR AND XFIXES_LIBRARY ) set( XFIXES_FOUND 1 ) else() set( XFIXES_FOUND 0 ) endif() mark_as_advanced( XFIXES_INCLUDE_DIR XFIXES_LIBRARY ) maim-5.5.3/modules/FindXRandr.cmake000066400000000000000000000013521355146137300171310ustar00rootroot00000000000000# - Find XRandr # Find the XRandr libraries # # This module defines the following variables: # XRANDR_FOUND - 1 if XRANDR_INCLUDE_DIR & XRANDR_LIBRARY are found, 0 otherwise # XRANDR_INCLUDE_DIR - where to find Xlib.h, etc. # XRANDR_LIBRARY - the X11 library # find_path( XRANDR_INCLUDE_DIR NAMES X11/extensions/Xrandr.h PATH_SUFFIXES X11/extensions DOC "The XRandr include directory" ) find_library( XRANDR_LIBRARY NAMES Xrandr PATHS /usr/lib /lib DOC "The XRandr library" ) if( XRANDR_INCLUDE_DIR AND XRANDR_LIBRARY ) set( XRANDR_FOUND 1 ) else() set( XRANDR_FOUND 0 ) endif() mark_as_advanced( XRANDR_INCLUDE_DIR XRANDR_LIBRARY ) maim-5.5.3/modules/FindXRender.cmake000066400000000000000000000032571355146137300173100ustar00rootroot00000000000000# - Find XRender # Find the XRender libraries # # This module defines the following variables: # XRENDER_FOUND - true if XRENDER_INCLUDE_DIR & XRENDER_LIBRARY are found # XRENDER_LIBRARIES - Set when Xrender_LIBRARY is found # XRENDER_INCLUDE_DIRS - Set when Xrender_INCLUDE_DIR is found # # XRENDER_INCLUDE_DIR - where to find Xrender.h, etc. # XRENDER_LIBRARY - the Xrender library # #============================================================================= # Copyright 2013 Corey Clayton # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #============================================================================= find_path(XRENDER_INCLUDE_DIR NAMES X11/extensions/Xrender.h PATHS /opt/X11/include DOC "The Xrender include directory") find_library(XRENDER_LIBRARY NAMES Xrender PATHS /opt/X11/lib DOC "The Xrender library") include(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(Xrender DEFAULT_MSG XRENDER_LIBRARY XRENDER_INCLUDE_DIR) if(XRENDER_FOUND) set(XRENDER_LIBRARIES ${XRENDER_LIBRARY}) set(XRENDER_INCLUDE_DIRS ${XRENDER_INCLUDE_DIR}) endif() mark_as_advanced(XRENDER_INCLUDE_DIR XRENDER_LIBRARY) maim-5.5.3/src/000077500000000000000000000000001355146137300132465ustar00rootroot00000000000000maim-5.5.3/src/cxxopts.hpp000066400000000000000000000675121355146137300155020ustar00rootroot00000000000000/* Copyright (c) 2014, 2015, 2016 Jarryd Beck Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef CXX_OPTS_HPP #define CXX_OPTS_HPP #if defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wnon-virtual-dtor" #endif #include #include #include #include #include #include #include #include #include #include //when we ask cxxopts to use Unicode, help strings are processed using ICU, //which results in the correct lengths being computed for strings when they //are formatted for the help output //it is necessary to make sure that can be found by the //compiler, and that icu-uc is linked in to the binary. #ifdef CXXOPTS_USE_UNICODE #include namespace cxxopts { typedef icu::UnicodeString String; inline String toLocalString(std::string s) { return icu::UnicodeString::fromUTF8(s); } class UnicodeStringIterator : public std::iterator { public: UnicodeStringIterator(const icu::UnicodeString* s, int32_t pos) : s(s) , i(pos) { } value_type operator*() const { return s->char32At(i); } bool operator==(const UnicodeStringIterator& rhs) const { return s == rhs.s && i == rhs.i; } bool operator!=(const UnicodeStringIterator& rhs) const { return !(*this == rhs); } UnicodeStringIterator& operator++() { ++i; return *this; } UnicodeStringIterator operator+(int32_t v) { return UnicodeStringIterator(s, i + v); } private: const icu::UnicodeString* s; int32_t i; }; inline String& stringAppend(String&s, String a) { return s.append(std::move(a)); } inline String& stringAppend(String& s, int n, UChar32 c) { for (int i = 0; i != n; ++i) { s.append(c); } return s; } template String& stringAppend(String& s, Iterator begin, Iterator end) { while (begin != end) { s.append(*begin); ++begin; } return s; } inline size_t stringLength(const String& s) { return s.length(); } inline std::string toUTF8String(const String& s) { std::string result; s.toUTF8String(result); return result; } inline bool empty(const String& s) { return s.isEmpty(); } } namespace std { cxxopts::UnicodeStringIterator begin(const icu::UnicodeString& s) { return cxxopts::UnicodeStringIterator(&s, 0); } cxxopts::UnicodeStringIterator end(const icu::UnicodeString& s) { return cxxopts::UnicodeStringIterator(&s, s.length()); } } //ifdef CXXOPTS_USE_UNICODE #else namespace cxxopts { typedef std::string String; template T toLocalString(T&& t) { return t; } inline size_t stringLength(const String& s) { return s.length(); } inline String& stringAppend(String&s, String a) { return s.append(std::move(a)); } inline String& stringAppend(String& s, size_t n, char c) { return s.append(n, c); } template String& stringAppend(String& s, Iterator begin, Iterator end) { return s.append(begin, end); } template std::string toUTF8String(T&& t) { return std::forward(t); } inline bool empty(const std::string& s) { return s.empty(); } } //ifdef CXXOPTS_USE_UNICODE #endif namespace cxxopts { class Value : public std::enable_shared_from_this { public: virtual void parse(const std::string& text) const = 0; virtual void parse() const = 0; virtual bool has_arg() const = 0; virtual bool has_default() const = 0; virtual bool is_container() const = 0; virtual bool has_implicit() const = 0; virtual std::string get_default_value() const = 0; virtual std::string get_implicit_value() const = 0; virtual std::shared_ptr default_value(const std::string& value) = 0; virtual std::shared_ptr implicit_value(const std::string& value) = 0; }; class OptionException : public std::exception { public: OptionException(const std::string& message) : m_message(message) { } virtual const char* what() const noexcept { return m_message.c_str(); } private: std::string m_message; }; class OptionSpecException : public OptionException { public: OptionSpecException(const std::string& message) : OptionException(message) { } }; class OptionParseException : public OptionException { public: OptionParseException(const std::string& message) : OptionException(message) { } }; class option_exists_error : public OptionSpecException { public: option_exists_error(const std::string& option) : OptionSpecException(u8"Option ‘" + option + u8"’ already exists") { } }; class invalid_option_format_error : public OptionSpecException { public: invalid_option_format_error(const std::string& format) : OptionSpecException(u8"Invalid option format ‘" + format + u8"’") { } }; class option_not_exists_exception : public OptionParseException { public: option_not_exists_exception(const std::string& option) : OptionParseException(u8"Option ‘" + option + u8"’ does not exist") { } }; class missing_argument_exception : public OptionParseException { public: missing_argument_exception(const std::string& option) : OptionParseException(u8"Option ‘" + option + u8"’ is missing an argument") { } }; class option_requires_argument_exception : public OptionParseException { public: option_requires_argument_exception(const std::string& option) : OptionParseException(u8"Option ‘" + option + u8"’ requires an argument") { } }; class option_not_has_argument_exception : public OptionParseException { public: option_not_has_argument_exception ( const std::string& option, const std::string& arg ) : OptionParseException( u8"Option ‘" + option + u8"’ does not take an argument, but argument‘" + arg + "’ given") { } }; class option_not_present_exception : public OptionParseException { public: option_not_present_exception(const std::string& option) : OptionParseException(u8"Option ‘" + option + u8"’ not present") { } }; class argument_incorrect_type : public OptionParseException { public: argument_incorrect_type ( const std::string& arg ) : OptionParseException( u8"Argument ‘" + arg + u8"’ failed to parse" ) { } }; namespace values { template void parse_value(const std::string& text, T& value) { std::istringstream is(text); if (!(is >> value)) { throw argument_incorrect_type(text); } if (is.rdbuf()->in_avail() != 0) { throw argument_incorrect_type(text); } } inline void parse_value(const std::string& /*text*/, bool& value) { //TODO recognise on, off, yes, no, enable, disable //so that we can write --long=yes explicitly value = true; } inline void parse_value(const std::string& text, std::string& value) { value = text; } template void parse_value(const std::string& text, std::vector& value) { T v; parse_value(text, v); value.push_back(v); } template struct value_has_arg { static constexpr bool value = true; }; template <> struct value_has_arg { static constexpr bool value = false; }; template struct type_is_container { static constexpr bool value = false; }; template struct type_is_container> { static constexpr bool value = true; }; template class standard_value : public Value { public: standard_value() : m_result(std::make_shared()) , m_store(m_result.get()) { } standard_value(T* t) : m_store(t) { } void parse(const std::string& text) const { parse_value(text, *m_store); } bool is_container() const { return type_is_container::value; } void parse() const { parse_value(m_default_value, *m_store); } bool has_arg() const { return value_has_arg::value; } bool has_default() const { return m_default; } bool has_implicit() const { return m_implicit; } virtual std::shared_ptr default_value(const std::string& value){ m_default = true; m_default_value = value; return shared_from_this(); } virtual std::shared_ptr implicit_value(const std::string& value){ m_implicit = true; m_implicit_value = value; return shared_from_this(); } std::string get_default_value() const { return m_default_value; } std::string get_implicit_value() const { return m_implicit_value; } const T& get() const { if (m_store == nullptr) { return *m_result; } else { return *m_store; } } protected: std::shared_ptr m_result; T* m_store; bool m_default = false; std::string m_default_value; bool m_implicit = false; std::string m_implicit_value; }; } template std::shared_ptr value() { return std::make_shared>(); } template std::shared_ptr value(T& t) { return std::make_shared>(&t); } class OptionAdder; class OptionDetails { public: OptionDetails ( const String& description, std::shared_ptr value ) : m_desc(description) , m_value(value) , m_count(0) { } const String& description() const { return m_desc; } bool has_arg() const { return m_value->has_arg(); } void parse(const std::string& text) { m_value->parse(text); ++m_count; } void parse_default() { m_value->parse(); } int count() const { return m_count; } const Value& value() const { return *m_value; } template const T& as() const { #ifdef CXXOPTS_NO_RTTI return static_cast&>(*m_value).get(); #else return dynamic_cast&>(*m_value).get(); #endif } private: String m_desc; std::shared_ptr m_value; int m_count; }; struct HelpOptionDetails { std::string s; std::string l; String desc; bool has_arg; bool has_default; std::string default_value; bool has_implicit; std::string implicit_value; std::string arg_help; bool is_container; }; struct HelpGroupDetails { std::string name; std::string description; std::vector options; }; class Options { public: Options(std::string program, std::string help_string = "") : m_program(std::move(program)) , m_help_string(toLocalString(std::move(help_string))) , m_positional_help("positional parameters") , m_next_positional(m_positional.end()) { } inline Options& positional_help(const std::string& help_text) { m_positional_help = std::move(help_text); return *this; } inline void parse(int& argc, char**& argv); inline OptionAdder add_options(std::string group = ""); inline void add_option ( const std::string& group, const std::string& s, const std::string& l, std::string desc, std::shared_ptr value, std::string arg_help ); int count(const std::string& o) const { auto iter = m_options.find(o); if (iter == m_options.end()) { return 0; } return iter->second->count(); } const OptionDetails& operator[](const std::string& option) const { auto iter = m_options.find(option); if (iter == m_options.end()) { throw option_not_present_exception(option); } return *iter->second; } //parse positional arguments into the given option inline void parse_positional(std::string option); inline void parse_positional(std::vector options); inline std::string help(const std::vector& groups = {""}) const; inline const std::vector groups() const; inline const HelpGroupDetails& group_help(const std::string& group) const; private: inline void add_one_option ( const std::string& option, std::shared_ptr details ); inline bool consume_positional(std::string a); inline void add_to_option(const std::string& option, const std::string& arg); inline void parse_option ( std::shared_ptr value, const std::string& name, const std::string& arg = "" ); inline void checked_parse_arg ( int argc, char* argv[], int& current, std::shared_ptr value, const std::string& name ); inline String help_one_group(const std::string& group) const; inline void generate_group_help(String& result, const std::vector& groups) const; inline void generate_all_groups_help(String& result) const; std::string m_program; String m_help_string; std::string m_positional_help; std::map> m_options; std::vector m_positional; std::vector::iterator m_next_positional; std::unordered_set m_positional_set; //mapping from groups to help options std::map m_help; }; class OptionAdder { public: OptionAdder(Options& options, std::string group) : m_options(options), m_group(std::move(group)) { } inline OptionAdder& operator() ( const std::string& opts, const std::string& desc, std::shared_ptr value = ::cxxopts::value(), std::string arg_help = "" ); private: Options& m_options; std::string m_group; }; } namespace cxxopts { namespace { constexpr int OPTION_LONGEST = 30; constexpr int OPTION_DESC_GAP = 2; std::basic_regex option_matcher ("--([[:alnum:]][-_[:alnum:]]+)(=(.*))?|-([[:alnum:]]+)"); std::basic_regex option_specifier ("(([[:alnum:]]),)?([[:alnum:]][-_[:alnum:]]+)"); String format_option ( const HelpOptionDetails& o ) { auto& s = o.s; auto& l = o.l; String result = " "; if (s.size() > 0) { result += "-" + toLocalString(s) + ","; } else { result += " "; } if (l.size() > 0) { result += " --" + toLocalString(l); } if (o.has_arg) { auto arg = o.arg_help.size() > 0 ? toLocalString(o.arg_help) : "arg"; if (o.has_implicit) { result += " [=" + arg + "(=" + toLocalString(o.implicit_value) + ")]"; } else { result += " " + arg; } } return result; } String format_description ( const HelpOptionDetails& o, size_t start, size_t width ) { auto desc = o.desc; if (o.has_default) { desc += toLocalString(" (default: " + o.default_value + ")"); } String result; auto current = std::begin(desc); auto startLine = current; auto lastSpace = current; auto size = size_t{}; while (current != std::end(desc)) { if (*current == ' ') { lastSpace = current; } if (size > width) { if (lastSpace == startLine) { stringAppend(result, startLine, current + 1); stringAppend(result, "\n"); stringAppend(result, start, ' '); startLine = current + 1; lastSpace = startLine; } else { stringAppend(result, startLine, lastSpace); stringAppend(result, "\n"); stringAppend(result, start, ' '); startLine = lastSpace + 1; } size = 0; } else { ++size; } ++current; } //append whatever is left stringAppend(result, startLine, current); return result; } } OptionAdder Options::add_options(std::string group) { return OptionAdder(*this, std::move(group)); } OptionAdder& OptionAdder::operator() ( const std::string& opts, const std::string& desc, std::shared_ptr value, std::string arg_help ) { std::match_results result; std::regex_match(opts.c_str(), result, option_specifier); if (result.empty()) { throw invalid_option_format_error(opts); } const auto& s = result[2]; const auto& l = result[3]; m_options.add_option(m_group, s.str(), l.str(), desc, value, std::move(arg_help)); return *this; } void Options::parse_option ( std::shared_ptr value, const std::string& /*name*/, const std::string& arg ) { value->parse(arg); } void Options::checked_parse_arg ( int argc, char* argv[], int& current, std::shared_ptr value, const std::string& name ) { if (current + 1 >= argc) { if (value->value().has_implicit()) { parse_option(value, name, value->value().get_implicit_value()); } else { throw missing_argument_exception(name); } } else { if (argv[current + 1][0] == '-' && value->value().has_implicit()) { parse_option(value, name, value->value().get_implicit_value()); } else { parse_option(value, name, argv[current + 1]); ++current; } } } void Options::add_to_option(const std::string& option, const std::string& arg) { auto iter = m_options.find(option); if (iter == m_options.end()) { throw option_not_exists_exception(option); } parse_option(iter->second, option, arg); } bool Options::consume_positional(std::string a) { while (m_next_positional != m_positional.end()) { auto iter = m_options.find(*m_next_positional); if (iter != m_options.end()) { if (!iter->second->value().is_container()) { if (iter->second->count() == 0) { add_to_option(*m_next_positional, a); ++m_next_positional; return true; } else { ++m_next_positional; continue; } } else { add_to_option(*m_next_positional, a); return true; } } ++m_next_positional; } return false; } void Options::parse_positional(std::string option) { parse_positional(std::vector{option}); } void Options::parse_positional(std::vector options) { m_positional = std::move(options); m_next_positional = m_positional.begin(); m_positional_set.insert(m_positional.begin(), m_positional.end()); } void Options::parse(int& argc, char**& argv) { int current = 1; int nextKeep = 1; bool consume_remaining = false; while (current != argc) { if (strcmp(argv[current], "--") == 0) { consume_remaining = true; ++current; break; } std::match_results result; std::regex_match(argv[current], result, option_matcher); if (result.empty()) { //not a flag //if true is returned here then it was consumed, otherwise it is //ignored if (consume_positional(argv[current])) { } else { argv[nextKeep] = argv[current]; ++nextKeep; } //if we return from here then it was parsed successfully, so continue } else { //short or long option? if (result[4].length() != 0) { const std::string& s = result[4]; for (std::size_t i = 0; i != s.size(); ++i) { std::string name(1, s[i]); auto iter = m_options.find(name); if (iter == m_options.end()) { throw option_not_exists_exception(name); } auto value = iter->second; //if no argument then just add it if (!value->has_arg()) { parse_option(value, name); } else { //it must be the last argument if (i + 1 == s.size()) { checked_parse_arg(argc, argv, current, value, name); } else if (value->value().has_implicit()) { parse_option(value, name, value->value().get_implicit_value()); } else { //error throw option_requires_argument_exception(name); } } } } else if (result[1].length() != 0) { const std::string& name = result[1]; auto iter = m_options.find(name); if (iter == m_options.end()) { throw option_not_exists_exception(name); } auto opt = iter->second; //equals provided for long option? if (result[3].length() != 0) { //parse the option given //but if it doesn't take an argument, this is an error if (!opt->has_arg()) { throw option_not_has_argument_exception(name, result[3]); } parse_option(opt, name, result[3]); } else { if (opt->has_arg()) { //parse the next argument checked_parse_arg(argc, argv, current, opt, name); } else { //parse with empty argument parse_option(opt, name); } } } } ++current; } for (auto& opt : m_options) { auto& detail = opt.second; auto& value = detail->value(); if(!detail->count() && value.has_default()){ detail->parse_default(); } } if (consume_remaining) { while (current < argc) { if (!consume_positional(argv[current])) { break; } ++current; } //adjust argv for any that couldn't be swallowed while (current != argc) { argv[nextKeep] = argv[current]; ++nextKeep; ++current; } } argc = nextKeep; } void Options::add_option ( const std::string& group, const std::string& s, const std::string& l, std::string desc, std::shared_ptr value, std::string arg_help ) { auto stringDesc = toLocalString(std::move(desc)); auto option = std::make_shared(stringDesc, value); if (s.size() > 0) { add_one_option(s, option); } if (l.size() > 0) { add_one_option(l, option); } //add the help details auto& options = m_help[group]; options.options.emplace_back(HelpOptionDetails{s, l, stringDesc, value->has_arg(), value->has_default(), value->get_default_value(), value->has_implicit(), value->get_implicit_value(), std::move(arg_help), value->is_container()}); } void Options::add_one_option ( const std::string& option, std::shared_ptr details ) { auto in = m_options.emplace(option, details); if (!in.second) { throw option_exists_error(option); } } String Options::help_one_group(const std::string& g) const { typedef std::vector> OptionHelp; auto group = m_help.find(g); if (group == m_help.end()) { return ""; } OptionHelp format; size_t longest = 0; String result; if (!g.empty()) { result += toLocalString(" " + g + " options:\n"); } for (const auto& o : group->second.options) { if (o.is_container && m_positional_set.find(o.l) != m_positional_set.end()) { continue; } auto s = format_option(o); longest = std::max(longest, stringLength(s)); format.push_back(std::make_pair(s, String())); } longest = std::min(longest, static_cast(OPTION_LONGEST)); //widest allowed description auto allowed = size_t{76} - longest - OPTION_DESC_GAP; auto fiter = format.begin(); for (const auto& o : group->second.options) { if (o.is_container && m_positional_set.find(o.l) != m_positional_set.end()) { continue; } auto d = format_description(o, longest + OPTION_DESC_GAP, allowed); result += fiter->first; if (stringLength(fiter->first) > longest) { result += '\n'; result += toLocalString(std::string(longest + OPTION_DESC_GAP, ' ')); } else { result += toLocalString(std::string(longest + OPTION_DESC_GAP - stringLength(fiter->first), ' ')); } result += d; result += '\n'; ++fiter; } return result; } void Options::generate_group_help(String& result, const std::vector& groups) const { for (std::size_t i = 0; i < groups.size(); ++i) { String const& group_help = help_one_group(groups[i]); if (empty(group_help)) continue; result += group_help; if (i < groups.size() - 1) { result += '\n'; } } } void Options::generate_all_groups_help(String& result) const { std::vector groups; groups.reserve(m_help.size()); for (auto& group : m_help) { groups.push_back(group.first); } generate_group_help(result, groups); } std::string Options::help(const std::vector& groups) const { String result = m_help_string + "\nUsage:\n " + toLocalString(m_program) + " [OPTION...]"; if (m_positional.size() > 0) { result += " " + toLocalString(m_positional_help); } result += "\n\n"; if (groups.size() == 0) { generate_all_groups_help(result); } else { generate_group_help(result, groups); } return toUTF8String(result); } const std::vector Options::groups() const { std::vector g; std::transform( m_help.begin(), m_help.end(), std::back_inserter(g), [] (const std::map::value_type& pair) { return pair.first; } ); return g; } const HelpGroupDetails& Options::group_help(const std::string& group) const { return m_help.at(group); } } #if defined(__GNU__) #pragma GCC diagnostic pop #endif #endif //CXX_OPTS_HPP maim-5.5.3/src/image.cpp000066400000000000000000000255441355146137300150460ustar00rootroot00000000000000#include "image.hpp" ARGBImage::~ARGBImage() { delete[] data; } ARGBImage::ARGBImage( XImage* image, glm::ivec2 iloc, glm::ivec4 selectionrect, int channels, X11* x11 ) { this->imagex = iloc.x; this->imagey = iloc.y; this->channels = channels; glm::ivec2 spos = glm::ivec2( selectionrect.x, selectionrect.y ); offset = spos-iloc; long long int alpha_mask = ~(image->red_mask|image->green_mask|image->blue_mask); long long int roffset = get_shift(image->red_mask); long long int goffset = get_shift(image->green_mask); long long int boffset = get_shift(image->blue_mask); long long int aoffset = get_shift(alpha_mask); width = selectionrect.z; height = selectionrect.w; data = new unsigned char[width*height*channels]; // Clear necessary stuff // Top rect for ( int y = 0; y < glm::min(-offset.y,(int)height);y++ ) { for ( int x = 0; x < width;x++ ) { for ( int c = 0; c < channels;c++ ) { data[(y*width+x)*channels+c] = 0; } } } // Left rect for ( int y = 0; y < height;y++ ) { for ( int x = 0; x < glm::min(-offset.x,(int)width);x++ ) { for ( int c = 0; c < channels;c++ ) { data[(y*width+x)*channels+c] = 0; } } } // Bot rect for ( int y=-offset.y+image->height; ywidth; xwidth); int minh = glm::min( (int)(offset.y+height), image->height ); // Loop only through the intersecting parts, copying everything. // Also check if we have any useful alpha data. switch( channels ) { case 4: if ( aoffset >= image->depth ) { for(int y = maxy; y < minh; y++) { for(int x = maxx; x < minw; x++) { // This is where we just have RGB but require an RGBA image. computeRGBAPixel( data, image, x, y, roffset, goffset, boffset, width, offset ); } } } else { for(int y = maxy; y < minh; y++) { for(int x = maxx; x < minw; x++) { computeRGBAPixel( data, image, x, y, roffset, goffset, boffset, aoffset, width, offset ); } } } break; case 3: for(int y = maxy; y < minh; y++) { for(int x = maxx; x < minw; x++) { computeRGBPixel( data, image, x, y, roffset, goffset, boffset, width, offset ); } } break; default: throw new std::invalid_argument("Invalid number of channels provided to image."); } } void png_write_ostream(png_structp png_ptr, png_bytep data, png_size_t length) { std::ostream *stream = (std::ostream*)png_get_io_ptr(png_ptr); //Get pointer to ostream stream->write((char*)data,length); //Write requested amount of data } void png_flush_ostream(png_structp png_ptr) { std::ostream *stream = (std::ostream*)png_get_io_ptr(png_ptr); //Get pointer to ostream stream->flush(); } void user_error_fn(png_structp png_ptr, png_const_charp error_msg) { throw new std::runtime_error(error_msg); } void user_warning_fn(png_structp png_ptr, png_const_charp warning_msg) { std::cerr << warning_msg << "\n"; } void ARGBImage::writePNG( std::ostream& streamout, int quality ) { if ( quality > 10 || quality < 1 ) { throw new std::invalid_argument("Quality argument must be between 1 and 10"); } png_structp png = NULL; png_infop info = NULL; png_bytep *rows = new png_bytep[height]; png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if(!png) throw new std::runtime_error( "Failed to write png image" ); info = png_create_info_struct(png); if(!info) throw new std::runtime_error( "Failed to write png image" ); png_set_error_fn(png, png_get_error_ptr(png), user_error_fn, user_warning_fn); png_set_write_fn(png, &streamout, png_write_ostream, png_flush_ostream); png_set_compression_level(png, quality-1); if ( channels == 4 ) { png_set_IHDR(png, info, width, height, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); } else { png_set_IHDR(png, info, width, height, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); } for( int i=0;inext_output_byte - out_buffer ); delete[] out_buffer; } bool ARGBImage::intersect( XRRCrtcInfo* a, glm::vec4 b ) { if (a->x < b.x + b.z && a->x + a->width > b.x && a->y < b.y + b.w && a->height + a->y > b.y) { return true; } return false; } bool ARGBImage::containsCompletely( XRRCrtcInfo* a, glm::vec4 b ) { 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 ) { return true; } return false; } void ARGBImage::mask(X11* x11) { if ( !x11->haveXRR ) { return; } std::vector physicalMonitors = x11->getCRTCS(); // Make sure a masking needs to happen, it's not a perfect detection, // but will detect most situations where a masking actually needs to happen. for ( int i=0;ifreeCRTCS(physicalMonitors); return; } } } unsigned char* copy = new unsigned char[width*height*channels]; // Zero out our copy for ( int y = 0; y < height;y++ ) { for ( int x = 0; x < width;x++ ) { for ( int c = 0; c < channels;c++ ) { copy[(y*width+x)*channels+c] = 0; } } } for ( int i=0;iy-imagey); yy+m->height-imagey);y++ ) { for ( int x = glm::max(0,m->x-imagex); x < glm::min(width,m->x+m->width-imagex);x++ ) { for ( int c = 0; c < channels;c++ ) { copy[(y*width+x)*channels+c] = data[(y*width+x)*channels+c]; } } } } x11->freeCRTCS(physicalMonitors); delete[] data; data = copy; } void ARGBImage::blendCursor( X11* x11 ) { if ( !x11->haveXFixes ) { return; } XFixesCursorImage* xcursor = XFixesGetCursorImage( x11->display ); if ( !xcursor ) { return; } // 64bit -> 32bit conversion unsigned char pixels[xcursor->width * xcursor->height * 4]; for ( unsigned int i=0;iwidth*xcursor->height;i++ ) { ((unsigned int*)pixels)[ i ] = (unsigned int)xcursor->pixels[ i ]; } xcursor->y -= xcursor->yhot + offset.x; xcursor->x -= xcursor->xhot + offset.y; for ( int y = glm::max(0,xcursor->y-imagey); yy+xcursor->height-imagey);y++ ) { for ( int x = glm::max(0,xcursor->x-imagex); x < glm::min((int)width,xcursor->x+xcursor->width-imagex);x++ ) { int cx = x-(xcursor->x-imagex); int cy = y-(xcursor->y-imagey); float alpha = (float)pixels[(cy*xcursor->width+cx)*4+3]/255.f; data[(y*width+x)*channels] = data[(y*width+x)*channels]*(1-alpha) + pixels[(cy*xcursor->width+cx)*4+2]*alpha; data[(y*width+x)*channels+1] = data[(y*width+x)*channels+1]*(1-alpha) + pixels[(cy*xcursor->width+cx)*4+1]*alpha; data[(y*width+x)*channels+2] = data[(y*width+x)*channels+2]*(1-alpha) + pixels[(cy*xcursor->width+cx)*4]*alpha; // If the original image has alpha, we need to override it. if ( channels == 4 ) { data[(y*width+x)*channels+3] = glm::min(data[(y*width+x)*channels+3]+pixels[(cy*xcursor->width+cx)*4+3],255); } } } } maim-5.5.3/src/image.hpp000066400000000000000000000070161355146137300150450ustar00rootroot00000000000000/* image.hpp: image helper * * Copyright (C) 2014: Dalton Nell, Maim Contributors (https://github.com/naelstrof/slop/graphs/contributors). * * This file is part of Maim. * * Maim is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Maim is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Maim. If not, see . */ #ifndef N_IMAGE_H_ #define N_IMAGE_H_ #include #include #include #include #include #include #include #include "x.hpp" 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 ) { int curpixel = ((y-offset.y)*width+((x-offset.x)))*3; unsigned int real = XGetPixel(image, x, y); data[curpixel] = (unsigned char)((real & image->red_mask) >> roffset); data[curpixel+1] = (unsigned char)((real & image->green_mask) >> goffset); data[curpixel+2] = (unsigned char)((real & image->blue_mask) >> boffset); return *data; } 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 ) { int curpixel = ((y-offset.y)*width+(x-offset.x))*4; //unsigned int real = ((unsigned int*)image->data)[curpixel/4]; unsigned int real = XGetPixel(image, x, y); data[curpixel] = (unsigned char)((real & image->red_mask) >> roffset); data[curpixel+1] = (unsigned char)((real & image->green_mask) >> goffset); data[curpixel+2] = (unsigned char)((real & image->blue_mask) >> boffset); data[curpixel+3] = (unsigned char)(real >> aoffset); return *data; } 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 ) { int curpixel = ((y-offset.y)*width+((x-offset.x)))*4; //unsigned int real = ((unsigned int*)image->data)[curpixel/4]; unsigned int real = XGetPixel(image, x, y); data[curpixel] = (unsigned char)((real & image->red_mask) >> roffset); data[curpixel+1] = (unsigned char)((real & image->green_mask) >> goffset); data[curpixel+2] = (unsigned char)((real & image->blue_mask) >> boffset); data[curpixel+3] = 255; return *data; } static inline int get_shift (int mask) { int shift = 0; while (mask) { if (mask & 1) { break; } shift++; mask >>= 1; } return shift; } class ARGBImage { private: unsigned char* data; unsigned int width; unsigned int height; unsigned int channels; int imagex, imagey; glm::ivec2 offset; bool intersect( XRRCrtcInfo* a, glm::vec4 b ); bool containsCompletely( XRRCrtcInfo* a, glm::vec4 b ); public: void blendCursor( X11* x11 ); void mask(X11* x11); ARGBImage( XImage* image, glm::ivec2 imageloc, glm::ivec4 selectionrect, int channels, X11* x11 ); ~ARGBImage(); void writePNG( std::ostream& streamout, int quality ); void writeJPEG( std::ostream& streamout, int quality ); }; #endif maim-5.5.3/src/main.cpp000066400000000000000000000616711355146137300147110ustar00rootroot00000000000000#include #include #include #include #include #include #include #include #include #include "cxxopts.hpp" #include "x.hpp" #include "image.hpp" class MaimOptions { public: MaimOptions(); std::string savepath; std::string format; Window window; Window parent; glm::vec4 geometry; float delay; int quality; bool select; bool hideCursor; bool geometryGiven; bool quiet; bool windowGiven; bool parentGiven; bool formatGiven; bool version; bool help; bool savepathGiven; bool captureBackground; }; MaimOptions::MaimOptions() { savepath = ""; window = None; parent = None; quality = 7; quiet = false; delay = 0; format = "png"; select = false; parentGiven = false; hideCursor = false; geometryGiven = false; savepathGiven = false; windowGiven = false; formatGiven = false; captureBackground = false; } Window parseWindow( std::string win, X11* x11 ) { if ( win == "root" ) { return x11->root; } Window retwin; std::string::size_type sz; try { retwin = std::stoi(win,&sz); } catch ( ... ) { try { retwin = std::stoul(win,&sz,16); } catch ( ... ) { throw new std::invalid_argument("Unable to parse value " + win + " as a window. Expecting integer, hex, or `root`."); } } return retwin; } glm::vec4 parseColor( std::string value ) { std::string valuecopy = value; const auto check_char = [&] (char c) { if (c != ',') { throw new std::invalid_argument("Unable to parse value `" + valuecopy + "` as a color. You need to use commas as separators."); } }; glm::vec4 found; std::string::size_type sz; try { found[0] = std::stof(value,&sz); check_char(value.at(sz)); value = value.substr(sz+1); found[1] = std::stof(value,&sz); check_char(value.at(sz)); value = value.substr(sz+1); found[2] = std::stof(value,&sz); if ( value.size() != sz ) { check_char(value.at(sz)); value = value.substr(sz+1); found[3] = std::stof(value,&sz); if ( value.size() != sz ) { throw "dur"; } } else { found[3] = 1; } } catch (std::invalid_argument* const e) { throw e; } catch ( ... ) { 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."); } return found; } glm::vec4 parseGeometry( std::string value ) { glm::vec4 found; std::string valuecopy = value; std::string::size_type sz = 0; glm::vec2 dim(0,0); int curpos = 0; glm::vec2 pos(0,0); try { if ( std::count(value.begin(), value.end(), '+') > 2 ) { throw "dur"; } if ( std::count(value.begin(), value.end(), '-') > 2 ) { throw "dur"; } if ( std::count(value.begin(), value.end(), 'x') > 1 ) { throw "dur"; } while( value != "" ) { switch( value[0] ) { case 'x': dim.y = std::stof(value.substr(1),&sz); sz++; break; case '+': pos[curpos++] = std::stof(value.substr(1), &sz); sz++; break; case '-': pos[curpos++] = -std::stof(value.substr(1), &sz); sz++; break; default: dim.x = std::stof(value,&sz); break; } value = value.substr(sz); } } catch ( ... ) { 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."); } found.x = pos.x; found.y = pos.y; found.z = dim.x; found.w = dim.y; return found; } MaimOptions* getMaimOptions( cxxopts::Options& options, X11* x11 ) { MaimOptions* foo = new MaimOptions(); foo->parentGiven = options.count("parent") > 0; if ( foo->parentGiven ) { foo->parent = parseWindow( options["parent"].as(), x11 ); } foo->windowGiven = options.count("window") > 0; if ( foo->windowGiven ) { foo->window = parseWindow( options["window"].as(), x11 ); } foo->geometryGiven = options.count("geometry") > 0; if ( foo->geometryGiven ) { foo->geometry = parseGeometry( options["geometry"].as() ); } if ( options.count( "delay" ) > 0 ) { foo->delay = options["delay"].as(); } if ( options.count( "hidecursor" ) > 0 ) { foo->hideCursor = options["hidecursor"].as(); } if ( options.count( "select" ) > 0 ) { foo->select = options["select"].as(); } if ( options.count( "quiet" ) > 0 ) { foo->quiet = options["quiet"].as(); } if ( options.count( "format" ) > 0 ) { foo->quiet = options["quiet"].as(); } foo->formatGiven = options.count("format") > 0; if ( foo->formatGiven ) { foo->format = options["format"].as(); if ( foo->format != "png" && foo->format != "jpg" && foo->format != "jpeg" ) { throw new std::invalid_argument("Unknown format type: `" + foo->format + "`, only `png` or `jpg` is allowed." ); } } if ( options.count( "quality" ) > 0 ) { foo->quality = options["quality"].as(); if ( foo->quality > 10 || foo->quality < 1 ) { throw new std::invalid_argument("Quality argument must be between 1 and 10"); } } if ( options.count( "capturebackground" ) > 0 ) { foo->captureBackground = options["capturebackground"].as(); } auto& positional = options["positional"].as>(); foo->savepathGiven = positional.size() > 0; //std::cerr << positional[0] << "\n"; if ( foo->savepathGiven ) { foo->savepath = positional[0]; } return foo; } slop::SlopOptions* getSlopOptions( cxxopts::Options& options ) { slop::SlopOptions* foo = new slop::SlopOptions(); if ( options.count( "bordersize" ) > 0 ) { foo->border = options["bordersize"].as(); } if ( options.count( "padding" ) > 0 ) { foo->padding = options["padding"].as(); } if ( options.count( "tolerance" ) > 0 ) { foo->tolerance = options["tolerance"].as(); } glm::vec4 color = glm::vec4( foo->r, foo->g, foo->b, foo->a ); if ( options.count( "color" ) > 0 ) { color = parseColor( options["color"].as() ); } foo->r = color.r; foo->g = color.g; foo->b = color.b; foo->a = color.a; if ( options.count( "nokeyboard" ) > 0 ) { foo->nokeyboard = options["nokeyboard"].as(); } if ( options.count( "noopengl" ) > 0 ) { foo->noopengl = options["noopengl"].as(); } if ( options.count( "xdisplay" ) > 0 ) { std::string xdisplay = options["xdisplay"].as(); char* cxdisplay = new char[xdisplay.length()+1]; memcpy( cxdisplay, xdisplay.c_str(), xdisplay.length() ); cxdisplay[xdisplay.length()]='\0'; foo->xdisplay = cxdisplay; } if ( options.count( "shader" ) > 0 ) { std::string shaders = options["shader"].as(); char* cshaders = new char[shaders.length()+1]; memcpy( cshaders, shaders.c_str(), shaders.length() ); cshaders[shaders.length()]='\0'; foo->shaders = cshaders; } if ( options.count( "quiet" ) > 0 ) { foo->quiet = options["quiet"].as(); } if ( options.count( "highlight" ) > 0 ) { foo->highlight = options["highlight"].as(); } if ( options.count( "nodecorations" ) > 0 ) { foo->nodecorations = options["nodecorations"].as(); if ( foo->nodecorations < 0 || foo->nodecorations > 2 ) { throw new std::invalid_argument( "--nodecorations must be between 0 and 2. Or be used as a flag." ); } } return foo; } const auto HELP_MESSAGE = R"MULTI_STRING( maim - make image SYNOPSIS maim [OPTIONS] [FILEPATH] DESCRIPTION maim (make image) is an utility that takes a screenshot of your desktop, and encodes a png or jpg image of it. By default it outputs the encoded image data directly to standard output. OPTIONS -h, --help Print help and exit. -v, --version Print version and exit. -x, --xdisplay=hostname:number.screen_number Sets the xdisplay to use. -f, --format=STRING 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. Cur‐ rently only supports `png` or `jpg`. -i, --window=INT Sets the desired window to capture, defaults to the root window. -g, --geometry=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. -d, --delay=FLOAT 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. -u, --hidecursor By default maim super-imposes the cursor onto the image, you can disable that behavior with this flag. -m, --quality An integer from 1 to 10 that determines the compression quality. 1 is the highest (and lossiest) compression available for the pro‐ vided format. For example a setting of `1` with png (a lossless format) would increase filesize and speed up encoding dramatical- ly. While a setting of `1` on a jpeg would create a pixel mush. -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. -w, --parent=WINDOW 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. -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. SLOP OPTIONS -b, --bordersize=FLOAT Sets the selection rectangle's thickness. -p, --padding=FLOAT Sets the padding size for the selection, this can be negative. -t, --tolerance=FLOAT 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. -c, --color=FLOAT,FLOAT,FLOAT,FLOAT Sets the selection rectangle's color. Supports RGB or RGBA input. Depending on the system's window manager/OpenGL support, the opac‐ ity may be ignored. -r, --shader=STRING 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 ~/.con‐ fig/maim. See https://github.com/naelstrof/slop for more informa‐ tion on how to create your own shaders. -n, --nodecorations=INT Sets the level of aggressiveness when trying to remove window decorations. `0' is off, `1' will try lightly to remove decora‐ tions, and `2' will recursively descend into the root tree until it gets the deepest available visible child under the mouse. Defaults to `0'. -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. -q, --quiet Disable any unnecessary cerr output. Any warnings or info simply won't print. -k, --nokeyboard Disables the ability to cancel selections with the keyboard. -o, --noopengl Disables graphics hardware acceleration. EXAMPLES Screenshot the active window and save it to the clipboard for quick past‐ ing. maim -i $(xdotool getactivewindow) | xclip -selection clipboard -t image/png Save a desktop screenshot with a unique ordered timestamp in the Pictures folder. maim ~/Pictures/$(date +%s).png Prompt for a region to screenshot. Add a fancy shadow to it, then save it to shadow.png. maim -s | convert - \( +clone -background black -shadow 80x3+5+5 \) +swap \ -background none -layers merge +repage shadow.png)MULTI_STRING"; int app( int argc, char** argv ) { // 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. cxxopts::Options options("maim", "Screenshot application."); options.add_options() ("h,help", "Print help and exit.") ("v,version", "Print version and exit.") ("x,xdisplay", "Sets the xdisplay to use", cxxopts::value()) ("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. Currently only supports `png` or `jpg`.", cxxopts::value()) ("i,window", "Sets the desired window to capture, defaults to the root window. Allows for an integer, hex, or `root` for input.", cxxopts::value()) ("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()) ("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()) ("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.") ("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")) ("u,hidecursor", "By default maim super-imposes the cursor onto the image, you can disable that behavior with this flag.") ("m,quality", "An integer from 1 to 10 that determines the compression quality. 1 is the highest (and lossiest) compression available for the provided format. For example a setting of `1` with png (a loss‐ less format) would increase filesize and decrease decoding time. While a setting of `1` on a jpeg would create a pixel mush.", cxxopts::value()) ("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.") ("b,bordersize", "Sets the selection rectangle's thickness.", cxxopts::value()) ("p,padding", "Sets the padding size for the selection, this can be negative.", cxxopts::value()) ("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()) ("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()) ("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()) ("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")) ("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.") ("q,quiet", "Disable any unnecessary cerr output. Any warnings or info simply won't print.") ("k,nokeyboard", "Disables the ability to cancel selections with the keyboard.") ("o,noopengl", "Disables graphics hardware acceleration.") ("positional", "Positional parameters", cxxopts::value>()) ; options.parse_positional("positional"); options.parse(argc, argv); // Version checks and help menu don't require X11, and in fact will fail if running // in a headless environment. if ( options.count( "version" ) > 0 ) { std::cout << MAIM_VERSION << "\n"; return 0; } if ( options.count( "help" ) > 0 ) { std::cout << HELP_MESSAGE << std::endl; return 0; } slop::SlopOptions* slopOptions = getSlopOptions( options ); // Boot up x11 X11* x11 = new X11(slopOptions->xdisplay); MaimOptions* maimOptions = getMaimOptions( options, x11 ); slop::SlopSelection selection(0,0,0,0,0,true); // Check if output is a tty before dumping binary data to it if ( isatty( fileno( stdout ) ) && !maimOptions->savepathGiven ) { std::cout << HELP_MESSAGE << std::endl; return 0; } if ( maimOptions->select ) { if ( maimOptions->windowGiven || maimOptions->parentGiven || maimOptions->geometryGiven ) { throw new std::invalid_argument( "Interactive mode (--select) doesn't support the following parameters: --window, --parent, --geometry." ); } selection = SlopSelect(slopOptions); if ( selection.cancelled ) { if ( !maimOptions->quiet ) { std::cerr << "Selection was cancelled by keystroke or right-click.\n"; } return 1; } } if ( !maimOptions->formatGiven && maimOptions->savepathGiven && maimOptions->savepath.find_last_of(".") != std::string::npos ) { maimOptions->format = maimOptions->savepath.substr(maimOptions->savepath.find_last_of(".")+1); if ( maimOptions->format != "png" && maimOptions->format != "jpg" && maimOptions->format != "jpeg" ) { throw new std::invalid_argument("Unknown format type: `" + maimOptions->format + "`, only `png` or `jpg` is allowed." ); } } if ( !maimOptions->windowGiven ) { maimOptions->window = x11->root; } else { XWindowAttributes attr; XGetWindowAttributes(x11->display, maimOptions->window, &attr); if (attr.backing_store == NotUseful && attr.width == 1 && attr.height == 1) { Window root, parent; parent = None; Window* children; unsigned int nchildren; Window selectedWindow; XQueryTree( x11->display, maimOptions->window, &root, &parent, &children, &nchildren ); if ( parent != None ) { maimOptions->window = parent; } } } if ( !maimOptions->parentGiven ) { maimOptions->parent = maimOptions->window; } else if ( !maimOptions->geometryGiven ) { throw new std::invalid_argument( "Relative mode (--parent) requires --geometry." ); } if ( !maimOptions->geometryGiven ) { Window junk; glm::ivec4 geometry = getWindowGeometry( x11, maimOptions->window ); XTranslateCoordinates(x11->display, x11->root, maimOptions->window, geometry.x, geometry.y, &geometry.x, &geometry.y, &junk); maimOptions->geometry = geometry; } if ( !maimOptions->select ) { selection.x = maimOptions->geometry.x; selection.y = maimOptions->geometry.y; selection.w = maimOptions->geometry.z; selection.h = maimOptions->geometry.w; selection.id = maimOptions->window; } if ( maimOptions->captureBackground ) { selection.id = x11->root; } std::ostream* out; if ( maimOptions->savepathGiven ) { std::ofstream* file = new std::ofstream(); file->open(maimOptions->savepath.c_str()); if ( !file->is_open() ) { throw new std::runtime_error( "Failed to open file for writing: `" + maimOptions->savepath + "`." ); } out = file; } else { out = &std::cout; } // Then we grab the pixel buffer of the provided window/selection. if ( maimOptions->delay ) { if ( !maimOptions->quiet ) { std::cerr << "Snapshotting in..."; } while ( maimOptions->delay > 0 ) { std::this_thread::sleep_for(std::chrono::milliseconds(glm::clamp(glm::min(1000,(int)(maimOptions->delay*1000)),0,1000))); maimOptions->delay-=1; if ( !maimOptions->quiet ) { if ( maimOptions->delay <= 0 ) { std::cerr << "☺"; } else { std::cerr << maimOptions->delay << " "; } } } if ( !maimOptions->quiet ) { std::cerr << "\n"; } } // Localize to our parent int px, py; Window junk; XTranslateCoordinates( x11->display, maimOptions->parent, x11->root, (int)selection.x, (int)selection.y, &px, &py, &junk); glm::ivec2 imageloc; // Snapshot the image XImage* image = x11->getImage( selection.id, px, py, selection.w, selection.h, imageloc); if ( maimOptions->format == "png" ) { // Convert it to an ARGB format, clipping it to the selection. ARGBImage convert(image, imageloc, glm::vec4(px, py, selection.w, selection.h), 4, x11 ); if ( !maimOptions->hideCursor ) { convert.blendCursor( x11 ); } // Mask it if we're taking a picture of root if ( selection.id == x11->root ) { convert.mask(x11); } // Then output it in the desired format. convert.writePNG(*out, maimOptions->quality ); } else if ( maimOptions->format == "jpg" || maimOptions->format == "jpeg" ) { // Convert it to a RGB format, clipping it to the selection. ARGBImage convert(image, imageloc, glm::vec4(px, py, selection.w, selection.h), 3, x11 ); if ( !maimOptions->hideCursor ) { convert.blendCursor( x11 ); } // Mask it if we're taking a picture of root if ( selection.id == x11->root ) { convert.mask(x11); } // Then output it in the desired format. convert.writeJPEG(*out, maimOptions->quality ); } XDestroyImage( image ); if ( maimOptions->savepathGiven ) { std::ofstream* file = (std::ofstream*)out; file->close(); delete (std::ofstream*)out; } delete x11; delete maimOptions; if ( options.count( "xdisplay" ) > 0 ) { delete slopOptions->xdisplay; } if ( options.count( "shader" ) > 0 ) { delete slopOptions->shaders; } delete slopOptions; return 0; } int main( int argc, char** argv ) { try { return app( argc, argv ); } catch( std::exception* e ) { std::cerr << "Maim encountered an error:\n" << e->what() << "\n"; return 1; } // let the operating system handle any other kind of exception. return 1; } maim-5.5.3/src/x.cpp000066400000000000000000000322021355146137300142200ustar00rootroot00000000000000#include "x.hpp" static char _x_err = 0; static int TmpXError(Display * d, XErrorEvent * ev) { _x_err = 1; return 0; } glm::ivec4 getWindowGeometry( X11* x11, Window win ) { // First lets check for if we're a window manager frame. Window root, parent; Window* children; unsigned int num_children; XQueryTree( x11->display, win, &root, &parent, &children, &num_children); // To do that, we check if our top level child happens to have the _NET_FRAME_EXTENTS atom. unsigned char *data; Atom type_return; unsigned long nitems_return; unsigned long bytes_after_return; int format_return; bool window_frame = false; Window actualWindow = win; if ( win != x11->root && num_children > 0 && XGetWindowProperty( x11->display, children[num_children-1], XInternAtom( x11->display, "_NET_FRAME_EXTENTS", False), 0, LONG_MAX, False, XA_CARDINAL, &type_return, &format_return, &nitems_return, &bytes_after_return, &data) == Success ) { if ((type_return == XA_CARDINAL) && (format_return == 32) && (nitems_return == 4) && (data)) { actualWindow = children[num_children-1]; window_frame = true; } } XFree( children ); // If we're a window frame, we actually get the dimensions of the child window, then add the _NET_FRAME_EXTENTS to it. // (then add the border width of the window frame after that.) if ( window_frame ) { // First lets grab the border width. XWindowAttributes frameattr; XGetWindowAttributes( x11->display, win, &frameattr ); // Then lets grab the dims of the child window. XWindowAttributes attr; XGetWindowAttributes( x11->display, actualWindow, &attr ); unsigned int width = attr.width; unsigned int height = attr.height; // We combine both border widths. unsigned int border = attr.border_width+frameattr.border_width; int x, y; // Gotta translate them into root coords, we can adjust for the border width here. Window junk; XTranslateCoordinates( x11->display, actualWindow, attr.root, -border, -border, &x, &y, &junk ); width += border*2; height += border*2; // Now uh, remember that _NET_FRAME_EXTENTS stuff? That's the window frame information. // We HAVE to do this because mutter likes to mess with window sizes with shadows and stuff. unsigned long* ldata = (unsigned long*)data; width += ldata[0] + ldata[1]; height += ldata[2] + ldata[3]; x -= ldata[0]; y -= ldata[2]; XFree( data ); return glm::vec4( x, y, width, height ); } else { // Either the WM is malfunctioning, or the window secified isn't a window manager frame. // so we just rely on X. XWindowAttributes attr; XGetWindowAttributes( x11->display, win, &attr ); unsigned int width = attr.width; unsigned int height = attr.height; // We combine both border widths. unsigned int border = attr.border_width; int x, y; // Gotta translate them into root coords, we can adjust for the border width here. Window junk; XTranslateCoordinates( x11->display, win, attr.root, -border, -border, &x, &y, &junk ); width += border*2; height += border*2; return glm::vec4( x, y, width, height ); } } std::vector X11::getCRTCS() { std::vector monitors; if ( !res ) { return monitors; } for ( int i=0;incrtc;i++ ) { monitors.push_back( XRRGetCrtcInfo( display, res, res->crtcs[ i ] ) ); } return monitors; } void X11::freeCRTCS( std::vector monitors ) { for ( unsigned int i=0;idisplay, this->root, draw, x, y, &localx, &localy, &junk); if ( haveXComposite ) { // We redirect all the pixmaps offscreen, so that they won't be corrupted if obscured. for ( int i = 0; i < ScreenCount( display ); i++ ) { XCompositeRedirectSubwindows( display, RootWindow( display, i ), CompositeRedirectAutomatic ); } // We don't have to worry about undoing the redirect, since as soon as maim closes X knows to undo it. } if ( haveXRender && haveXFixes ) { return getImageUsingXRender( draw, localx, localy, w, h ); } // This stuff doesn't work very well... //if ( haveXShm ) { //XErrorHandler ph = XSetErrorHandler(TmpXError); //XImage* check = getImageUsingXShm( draw, localx, localy, w, h ); //XSetErrorHandler(ph); //if ( !_x_err && check != None ) { //return check; //} //} return XGetImage( display, draw, localx, localy, w, h, AllPlanes, ZPixmap ); } XImage* X11::getImageUsingXRender( Window draw, int localx, int localy, int w, int h ) { // We use XRender to grab the drawable, since it'll save it in a format we like. XWindowAttributes attr; XGetWindowAttributes( display, draw, &attr ); XRenderPictFormat *format = XRenderFindVisualFormat( display, attr.visual ); bool hasAlpha = ( format->type == PictTypeDirect && format->direct.alphaMask ); XRenderPictureAttributes pa; pa.subwindow_mode = IncludeInferiors; Picture picture = XRenderCreatePicture( display, draw, format, CPSubwindowMode, &pa ); if ( draw != root ) { XserverRegion region = findRegion( draw ); // Also we use XRender because of this neato function here. XFixesSetPictureClipRegion( display, picture, 0, 0, region ); XFixesDestroyRegion( display, region ); } Pixmap pixmap = XCreatePixmap(display, root, w, h, 32); XRenderPictureAttributes pa2; XRenderPictFormat *format2 = XRenderFindStandardFormat(display, PictStandardARGB32); Picture pixmapPicture = XRenderCreatePicture( display, pixmap, format2, 0, &pa2 ); XRenderColor c; c.red = 0x0000; c.green = 0x0000; c.blue = 0x0000; c.alpha = 0x0000; XRenderFillRectangle (display, PictOpSrc, pixmapPicture, &c, 0, 0, w, h); XRenderComposite(display, hasAlpha ? PictOpOver : PictOpSrc, picture, 0, pixmapPicture, localx, localy, 0, 0, 0, 0, w, h); XImage* temp = XGetImage( display, pixmap, 0, 0, w, h, AllPlanes, ZPixmap ); temp->red_mask = format2->direct.redMask << format2->direct.red; temp->green_mask = format2->direct.greenMask << format2->direct.green; temp->blue_mask = format2->direct.blueMask << format2->direct.blue; temp->depth = format2->depth; return temp; } bool X11::hasClipping( Window d ) { int bShaped, xbs, ybs, cShaped, xcs, ycs; unsigned int wbs, hbs, wcs, hcs; XShapeQueryExtents ( display, d, &bShaped, &xbs, &ybs, &wbs, &hbs, &cShaped, &xcs, &ycs, &wcs, &hcs ); return bShaped; } XserverRegion X11::findRegion( Window d ) { XserverRegion rootRegion = XFixesCreateRegionFromWindow( display, d, WindowRegionBounding ); glm::vec4 rootgeo = getWindowGeometry( this, d ); XFixesTranslateRegion( display, rootRegion, rootgeo.x, rootgeo.y ); // Regions are in respect to the root window by default. unionClippingRegions( rootRegion, d ); unionBorderRegions( rootRegion, d ); return rootRegion; } void X11::unionBorderRegions( XserverRegion rootRegion, Window d ) { glm::vec4 bordergeo = getWindowGeometry( this, d ); XRectangle* rects = new XRectangle[1]; rects[0].x = bordergeo.x; rects[0].y = bordergeo.y; rects[0].width = bordergeo.z; rects[0].height = bordergeo.w; XserverRegion borderRegionRect = XFixesCreateRegion( display, rects, 1 ); XWindowAttributes attr; XGetWindowAttributes( display, d, &attr ); rects[0].x += attr.border_width; rects[0].y += attr.border_width; rects[0].width -= attr.border_width*2; rects[0].height -= attr.border_width*2; XserverRegion regionRect = XFixesCreateRegion( display, rects, 1 ); XFixesSubtractRegion( display, regionRect, borderRegionRect, regionRect ); delete[] rects; XFixesUnionRegion( display, rootRegion, rootRegion, regionRect ); XFixesDestroyRegion( display, regionRect ); XFixesDestroyRegion( display, borderRegionRect ); } void X11::unionClippingRegions( XserverRegion rootRegion, Window child ) { Window root, parent; Window* children; unsigned int num_children; XQueryTree( display, child, &root, &parent, &children, &num_children); for ( unsigned int i=0;ibytes_per_line * xim->height, IPC_CREAT | 0777); /* if the get succeeds */ if (thing.shmid != -1) { /* set the params for the shm segment */ thing.readOnly = False; thing.shmaddr = xim->data = (char*)shmat(thing.shmid, 0, 0); /* get the shm addr for this data chunk */ if (xim->data != (char *)-1) { XShmAttach(display, &thing); XShmGetImage(display, draw, xim, localx, localy, AllPlanes); return xim; //shmdt(thing.shmaddr); } /* get failed - out of shm id's or shm segment too big ? */ /* remove the shm id we created */ shmctl(thing.shmid, IPC_RMID, 0); shmdt(thing.shmaddr); } return None; } maim-5.5.3/src/x.hpp000066400000000000000000000041411355146137300142260ustar00rootroot00000000000000/* x.hpp: initializes x11 * * Copyright (C) 2014: Dalton Nell, Maim Contributors (https://github.com/naelstrof/slop/graphs/contributors). * * This file is part of Maim. * * Maim is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Maim is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Maim. If not, see . */ #ifndef N_X_H_ #define N_X_H_ #include #include #include #include #include #include #include #include //#include #include #include #include #include #include class X11 { private: bool hasClipping( Window d ); XserverRegion findRegion( Window d ); void unionClippingRegions( XserverRegion rootRegion, Window child ); void unionBorderRegions( XserverRegion rootRegion, Window d ); XImage* getImageUsingXRender( Window draw, int localx, int localy, int w, int h ); XImage* getImageUsingXShm( Window draw, int localx, int localy, int w, int h ); public: bool haveXComposite; bool haveXRender; bool haveXShm; bool haveXFixes; bool haveXRR; X11( std::string displayName ); ~X11(); Display* display; Visual* visual; Screen* screen; Window root; XImage* getImage( Window d, int x, int y, int w, int h, glm::ivec2& imageloc ); XRRScreenResources* res; std::vector getCRTCS(); void freeCRTCS( std::vector monitors ); }; glm::ivec4 getWindowGeometry( X11* x11, Window win ); #endif