pax_global_header00006660000000000000000000000064136441610270014516gustar00rootroot0000000000000052 comment=102136c4eeac60dc7413a8fc856afefbe6927da2 slop-7.5/000077500000000000000000000000001364416102700123465ustar00rootroot00000000000000slop-7.5/.gitignore000066400000000000000000000001631364416102700143360ustar00rootroot00000000000000CMakeCache.txt CMakeFiles/ Makefile bin/ cmake_install.cmake libslopy.so .vscode libslopy.so* install_manifest.txt slop-7.5/CMakeLists.txt000066400000000000000000000076661364416102700151250ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.1.3) project(slop VERSION 7.5 LANGUAGES CXX) set(CMAKE_BUILD_TYPE Debug CACHE STRING "Choose the type of build (Debug or Release)") if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "/usr" CACHE PATH "..." FORCE) endif() include(GNUInstallDirs) set( BUILD_SHARED_LIBS ON CACHE BOOL "Build all libraries as shared" ) # This should really never be disabled. The pure-X mode of slop is very expensive and buggy. # It also doesn't work on Wayland. Though if a system is never running a compositor, or # doesn't have OpenGL, this could remove some linking dependencies I suppose. set( SLOP_OPENGL TRUE CACHE BOOL "To enable or disable OpenGL support." ) if ( SLOP_OPENGL ) add_definitions(-DSLOP_OPENGL="True") endif() set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/bin/") include_directories("${PROJECT_BINARY_DIR}") add_definitions(-DSLOP_VERSION="v${PROJECT_VERSION}") # The names have to be unique unfortunately. set(EXECUTABLE_NAME "slop") set(LIBRARY_NAME "slopy") add_library(${LIBRARY_NAME} src/mouse.cpp src/keyboard.cpp src/x.cpp src/slopstates.cpp src/resource.cpp src/slop.cpp src/rectangle.cpp src/xshaperectangle.cpp) set_target_properties(${LIBRARY_NAME} PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION}) if ( SLOP_OPENGL ) target_sources(${LIBRARY_NAME} PRIVATE src/shader.cpp src/window.cpp src/framebuffer.cpp src/glrectangle.cpp) endif() set_property(TARGET ${LIBRARY_NAME} PROPERTY CXX_STANDARD_REQUIRED ON) set_property(TARGET ${LIBRARY_NAME} PROPERTY CXX_STANDARD 11) set_property(TARGET ${LIBRARY_NAME} PROPERTY CXX_EXTENSIONS OFF) add_executable(${EXECUTABLE_NAME} src/main.cpp) set_property(TARGET ${EXECUTABLE_NAME} PROPERTY CXX_STANDARD_REQUIRED ON) set_property(TARGET ${EXECUTABLE_NAME} PROPERTY CXX_STANDARD 11) set_property(TARGET ${EXECUTABLE_NAME} PROPERTY CXX_EXTENSIONS OFF) set( CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/modules" ) find_package(GLM REQUIRED) find_package(X11 REQUIRED) find_package(XExt REQUIRED) if ( SLOP_OPENGL ) find_package(GLEW REQUIRED) find_package(OpenGL REQUIRED) find_package(GLX REQUIRED) find_package(XRender REQUIRED) # Ahhhh, finally this eliminates the segfault on preload. find_package(Threads REQUIRED) endif() include_directories(${X11_INCLUDE_DIR} ${GLM_INCLUDE_DIR} ${GLX_INCLUDE_DIR}) target_link_libraries(${LIBRARY_NAME} ${X11_LIBRARIES} ${GLM_LIBRARIES} ${XEXT_LIBRARIES}) if ( SLOP_OPENGL ) include_directories( ${XEXT_INCLUDE_DIR} ${GLEW_INCLUDE_DIR} ${XRENDER_INCLUDE_DIR} ${OPENGL_INCLUDE_DIR} ) target_link_libraries(${LIBRARY_NAME} ${OPENGL_LIBRARIES} ${XRENDER_LIBRARY} ${CMAKE_THREAD_LIBS_INIT} ${GLX_LIBRARY} ${GLEW_LIBRARIES}) endif() target_link_libraries(${EXECUTABLE_NAME} ${LIBRARY_NAME} ) if( CMAKE<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( SLOP_UNICODE TRUE CACHE BOOL "To enable or disable unicode support." ) if ( SLOP_UNICODE AND ICU_FOUND ) add_definitions(-DCXXOPTS_USE_UNICODE) include_directories( ${ICU_INCLUDE_DIR} ) target_link_libraries(${EXECUTABLE_NAME} ${ICU_UC_LIBRARIES} ) endif() endif() install( TARGETS ${EXECUTABLE_NAME} DESTINATION "${CMAKE_INSTALL_BINDIR}" ) install( TARGETS ${LIBRARY_NAME} DESTINATION "${CMAKE_INSTALL_LIBDIR}" ) install( FILES ${CMAKE_SOURCE_DIR}/src/slop.hpp DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" COMPONENT development ) install( FILES ${CMAKE_SOURCE_DIR}/slop.1 DESTINATION "${CMAKE_INSTALL_MANDIR}/man1" COMPONENT doc ) slop-7.5/COPYING000066400000000000000000001045131364416102700134050ustar00rootroot00000000000000 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 . slop-7.5/README.md000066400000000000000000000141711364416102700136310ustar00rootroot00000000000000# slop slop (Select Operation) is an application that queries for a selection from the user and prints the region to stdout. ## Features * Hovering over a window will cause a selection rectangle to appear over it. * Clicking on a window makes slop return the dimensions of the window, and it's ID. * OpenGL accelerated graphics where possible. * Supports simple arguments: * Change selection rectangle border size. * Select X display. * Set padding size. * Force window, or pixel selections with the tolerance flag. * Set the color of the selection rectangles to match your theme! (Even supports transparency!) * Remove window decorations from selections. * Supports custom programmable shaders. * Move started selection by holding down the space bar. ## Practical Applications slop can be used to create a video recording script in only three lines of code. ```bash #!/bin/bash slop=$(slop -f "%x %y %w %h %g %i") || exit 1 read -r X Y W H G ID < <(echo $slop) ffmpeg -f x11grab -s "$W"x"$H" -i :0.0+$X,$Y -f alsa -i pulse ~/myfile.webm ``` You can also take images using imagemagick like so: ```bash #!/bin/bash slop=$(slop -f "%g") || exit 1 read -r G < <(echo $slop) import -window root -crop $G ~/myimage.png ``` If you don't like ImageMagick's import: Check out [maim](https://github.com/naelstrof/maim) for a better screenshot utility. ## Lets see some action Ok. Here's a comparison between 'scrot -s's selection and slop's: ![scrotbad](http://farmpolice.com/content/images/2014-10-14-12:08:24.png) ![slopgood](http://farmpolice.com/content/images/2014-10-14-12:14:51.png) You can see scrot leaves garbage lines over the things you're trying to screenshot! While slop not only looks nicer, it's impossible for it to end up in screenshots or recordings because it waits for DestroyNotify events before completely shutting down. Only after the window is completely destroyed can anything take a screenshot. ## how to install ### Install using your Package Manager (Preferred) * [Arch Linux: community/slop](https://www.archlinux.org/packages/community/x86_64/slop/) * [Void Linux: slop](https://github.com/voidlinux/void-packages/blob/24ac22af44018e2598047e5ef7fd3522efa79db5/srcpkgs/slop/template) * [FreeBSD: x11/slop](http://www.freshports.org/x11/slop/) * [NetBSD: x11/slop](http://pkgsrc.se/x11/slop) * [OpenBSD: graphics/slop](http://openports.se/graphics/slop) * [CRUX: 6c37/slop](https://github.com/6c37/crux-ports/tree/3.2/slop) * [Gentoo: x11-misc/slop](https://packages.gentoo.org/packages/x11-misc/slop) * [NixOS: slop](https://github.com/NixOS/nixpkgs/blob/master/pkgs/tools/misc/slop/default.nix) * [GNU Guix: slop](https://www.gnu.org/software/guix/packages/#slop) * [Debian: slop](https://packages.debian.org/sid/slop) * [Fedora: slop](https://src.fedoraproject.org/rpms/slop) * [Ravenports: slop](http://www.ravenports.com/catalog/bucket_CB/slop/standard/) * [Alpine Linux: testing/slop](https://pkgs.alpinelinux.org/package/edge/testing/x86_64/slop) * Please make a package for slop on your favorite system, and make a pull request to add it to this list. ### Install using CMake (Requires CMake) *Note: Dependencies should be installed first: libxext, glew, and glm.* ```bash git clone https://github.com/naelstrof/slop.git cd slop cmake -DCMAKE_INSTALL_PREFIX="/usr" ./ make && sudo make install ``` ### Shaders Slop allows for chained post-processing shaders. Shaders are written in a language called GLSL, and have access to the following data from slop: | GLSL Name | Data Type | Bound to | |------------|----------------|-------------------------------------------------------------------------------------------------| | mouse | vec2 | The mouse position on the screen. | | desktop | sampler2D | An upside-down snapshot of the desktop, this doesn't update as the screen changes. | | texture | sampler2D | The current pixel values of slop's frame buffer. Usually just contains the selection rectangle. | | screenSize | vec2 | The dimensions of the screen, where the x value is the width. | | position | vec2 attribute | This contains the vertex data for the rectangle. Only contains (0,0), (1,0), (1,1), and (0,1). | | uv | vec2 attribute | Same as the position, this contians the UV information of each vertex. | The desktop texture is upside-down because flipping it would cost valuable time. Shaders must be placed in your `${XDG_CONFIG_HOME}/slop` directory, where *XDG_CONFIG_HOME* is typically `~/.config/`. This folder won't exist unless you make it yourself. Shaders are loaded from the `--shader` flag in slop. They are delimited by commas, and rendered in order from left to right. This way you can combine multiple shaders for interesting effects! For example, `slop -rblur1,wiggle` would load `~/.config/slop/blur1{.frag,.vert}` and `~/.config/slop/wiggle{.frag,.vert}`. Then render the selection rectangle twice, each time accumulating the changes from the different shaders. Enough chatting about it though, here's some example shaders you can copy from [shaderexamples](https://github.com/naelstrof/slop/tree/master/shaderexamples) to `~/.config/slop` to try out! The files listed to the right of the `|` are the required files for the command to the left to work correctly. * `slop -r blur1,blur2 -b 100` | `~/.config/slop/{blur1,blur2}{.frag,.vert}` ![slop blur](https://my.mixtape.moe/bvsrzr.png) * `slop -r wiggle -b 10` | `~/.config/slop/wiggle{.frag,.vert}` ![slop animation](http://i.giphy.com/12vjSbFZ0CWDW8.gif) And all together now... * `slop -r blur1,blur2,wiggle -b 50 -c 1,1,1` | `~/.config/slop/{blur1,blur2,wiggle}{.frag,.vert}` ![slop animation](http://i.giphy.com/kfBLafeJfLs2Y.gif) Finally here's an example of a magnifying glass. * `slop -r crosshair` | `~/.config/slop/crosshair{.frag,.vert}` ![slop animation](http://i.giphy.com/2xy0fC2LOFQfm.gif) It's fairly easy to adjust how the shaders work by editing them with your favourite text editor. Or even make your own! slop-7.5/license.txt000066400000000000000000000013171364416102700145330ustar00rootroot00000000000000Copyright (C) 2014 Dalton Nell, Slop Contributors (https://github.com/naelstrof/slop/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 . slop-7.5/modules/000077500000000000000000000000001364416102700140165ustar00rootroot00000000000000slop-7.5/modules/FindGLM.cmake000066400000000000000000000022171364416102700162420ustar00rootroot00000000000000# # Find GLM # # Try to find GLM : OpenGL Mathematics. # This module defines # - GLM_INCLUDE_DIRS # - GLM_FOUND # # The following variables can be set as arguments for the module. # - GLM_ROOT_DIR : Root library directory of GLM # # References: # - https://github.com/Groovounet/glm/blob/master/util/FindGLM.cmake # - https://bitbucket.org/alfonse/gltut/src/28636298c1c0/glm-0.9.0.7/FindGLM.cmake # # Additional modules include(FindPackageHandleStandardArgs) if (WIN32) # Find include files find_path( GLM_INCLUDE_DIR NAMES glm/glm.hpp PATHS $ENV{PROGRAMFILES}/include ${GLM_ROOT_DIR}/include DOC "The directory where glm/glm.hpp resides") else() # Find include files find_path( GLM_INCLUDE_DIR NAMES glm/glm.hpp PATHS /usr/include /usr/local/include /sw/include /opt/local/include ${GLM_ROOT_DIR}/include DOC "The directory where glm/glm.hpp resides") endif() # Handle REQUIRD argument, define *_FOUND variable find_package_handle_standard_args(GLM DEFAULT_MSG GLM_INCLUDE_DIR) # Define GLM_INCLUDE_DIRS if (GLM_FOUND) set(GLM_INCLUDE_DIRS ${GLM_INCLUDE_DIR}) endif() # Hide some variables mark_as_advanced(GLM_INCLUDE_DIR) slop-7.5/modules/FindGLX.cmake000066400000000000000000000024421364416102700162550ustar00rootroot00000000000000# 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 ) slop-7.5/modules/FindXExt.cmake000066400000000000000000000014461364416102700165160ustar00rootroot00000000000000# - Find XExt # Find the XExtension libraries (WARNING: It's geared and tested specifically for the XShape extension though) # # This module defines the following variables: # XEXT_FOUND - 1 if XEXT_INCLUDE_DIR & XEXT_LIBRARY are found, 0 otherwise # XEXT_INCLUDE_DIR - where to find Xlib.h, etc. # XEXT_LIBRARY - the X11 library # find_path( XEXT_INCLUDE_DIR NAMES X11/extensions/shape.h PATH_SUFFIXES X11/extensions DOC "The XExtension include directory" ) find_library( XEXT_LIBRARY NAMES Xext PATHS /usr/lib /lib DOC "The XExtension library" ) if( XEXT_INCLUDE_DIR AND XEXT_LIBRARY ) set( XEXT_FOUND 1 ) else() set( XEXT_FOUND 0 ) endif() mark_as_advanced( XEXT_INCLUDE_DIR XEXT_LIBRARY ) slop-7.5/modules/FindXRender.cmake000066400000000000000000000032721364416102700171740ustar00rootroot00000000000000# - 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) slop-7.5/shaderexamples/000077500000000000000000000000001364416102700153535ustar00rootroot00000000000000slop-7.5/shaderexamples/blur1.frag000066400000000000000000000033351364416102700172450ustar00rootroot00000000000000#version 120 uniform sampler2D texture; uniform sampler2D desktop; uniform vec2 screenSize; varying vec2 uvCoord; // Stolen from https://github.com/Jam3/glsl-fast-gaussian-blur kinda void main() { float radius = 1; vec2 upsideDownUV = vec2( uvCoord.x, -uvCoord.y ); vec4 color = vec4(0.0); vec2 off1 = vec2(1.411764705882353) * vec2( radius, 0 ); vec2 off2 = vec2(3.2941176470588234) * vec2( radius, 0 ); vec2 off3 = vec2(5.176470588235294) * vec2( radius, 0 ); color += texture2D(desktop, upsideDownUV) * 0.1964825501511404; color += texture2D(desktop, upsideDownUV + (off1 / screenSize)) * 0.2969069646728344; color += texture2D(desktop, upsideDownUV - (off1 / screenSize)) * 0.2969069646728344; color += texture2D(desktop, upsideDownUV + (off2 / screenSize)) * 0.09447039785044732; color += texture2D(desktop, upsideDownUV - (off2 / screenSize)) * 0.09447039785044732; color += texture2D(desktop, upsideDownUV + (off3 / screenSize)) * 0.010381362401148057; color += texture2D(desktop, upsideDownUV - (off3 / screenSize)) * 0.010381362401148057; vec4 tcolor = vec4(0.0); tcolor += texture2D(texture, uvCoord) * 0.1964825501511404; tcolor += texture2D(texture, uvCoord + (off1 / screenSize)) * 0.2969069646728344; tcolor += texture2D(texture, uvCoord - (off1 / screenSize)) * 0.2969069646728344; tcolor += texture2D(texture, uvCoord + (off2 / screenSize)) * 0.09447039785044732; tcolor += texture2D(texture, uvCoord - (off2 / screenSize)) * 0.09447039785044732; tcolor += texture2D(texture, uvCoord + (off3 / screenSize)) * 0.010381362401148057; tcolor += texture2D(texture, uvCoord - (off3 / screenSize)) * 0.010381362401148057; gl_FragColor = (tcolor * color); } slop-7.5/shaderexamples/blur1.vert000066400000000000000000000002241364416102700173000ustar00rootroot00000000000000#version 120 attribute vec2 position; attribute vec2 uv; varying vec2 uvCoord; void main() { uvCoord = uv; gl_Position = vec4(position,0,1); } slop-7.5/shaderexamples/blur2.frag000066400000000000000000000017661364416102700172540ustar00rootroot00000000000000#version 120 uniform sampler2D texture; uniform vec2 screenSize; varying vec2 uvCoord; // Stolen from https://github.com/Jam3/glsl-fast-gaussian-blur kinda void main() { float radius = 1; vec4 color = vec4(0.0); vec2 off1 = vec2(1.411764705882353) * vec2( 0, radius ); vec2 off2 = vec2(3.2941176470588234) * vec2( 0, radius ); vec2 off3 = vec2(5.176470588235294) * vec2( 0, radius ); color += texture2D(texture, uvCoord) * 0.1964825501511404; color += texture2D(texture, uvCoord + (off1 / screenSize)) * 0.2969069646728344; color += texture2D(texture, uvCoord - (off1 / screenSize)) * 0.2969069646728344; color += texture2D(texture, uvCoord + (off2 / screenSize)) * 0.09447039785044732; color += texture2D(texture, uvCoord - (off2 / screenSize)) * 0.09447039785044732; color += texture2D(texture, uvCoord + (off3 / screenSize)) * 0.010381362401148057; color += texture2D(texture, uvCoord - (off3 / screenSize)) * 0.010381362401148057; gl_FragColor = color; } slop-7.5/shaderexamples/blur2.vert000066400000000000000000000002241364416102700173010ustar00rootroot00000000000000#version 120 attribute vec2 position; attribute vec2 uv; varying vec2 uvCoord; void main() { uvCoord = uv; gl_Position = vec4(position,0,1); } slop-7.5/shaderexamples/boxzoom.frag000066400000000000000000000042021364416102700177070ustar00rootroot00000000000000#version 120 uniform sampler2D texture; uniform sampler2D desktop; uniform vec2 screenSize; uniform vec2 mouse; varying vec2 uvCoord; void main() { // Adjustable parameters ------- vec2 boxOffset = vec2(-64,-64); vec2 boxSize = vec2(128,128); float magstrength = 5; vec2 borderSize = vec2(1,1); vec4 borderColor = vec4(0,0,0,1); bool crosshair = true; //------------------------------ // actual code (don't touch unless you're brave) // convert to UV space boxOffset = boxOffset/screenSize; boxSize = boxSize/screenSize; borderSize = borderSize/screenSize; // get mouse position in UV space vec2 mpos = vec2(mouse.x, -mouse.y)/screenSize + vec2(0,1); vec4 color; // Check if our current UV is inside our box. if ( uvCoord.x < mpos.x+boxOffset.x+boxSize.x && uvCoord.x > mpos.x+boxOffset.x && uvCoord.y > mpos.y+boxOffset.y && uvCoord.y < mpos.y+boxOffset.y+boxSize.y ) { // Check if we're actually inside the crosshair area. if ( (distance(uvCoord.x, mpos.x+boxOffset.x+boxSize.x/2) <= borderSize.x || distance(uvCoord.y, mpos.y+boxOffset.y+boxSize.y/2) <= borderSize.y) && crosshair ) { color = borderColor; } else { // Calculate where the UV should be. vec2 zoomedUV = ((uvCoord-mpos)-(boxOffset+boxSize/2))/magstrength+mpos; // The desktop texture is upside-down due to X11 vec2 zoomedUVFlipped = vec2( zoomedUV.x, -zoomedUV.y ); // Then change the color to the desktop color to draw, then add on our rectangle on top. vec4 rectColor = texture2D( texture, zoomedUV ); color = mix( texture2D( desktop, zoomedUVFlipped ), rectColor, rectColor.a ); } // Then check if we're in our border size. } else if( uvCoord.x <= mpos.x+boxOffset.x+boxSize.x+borderSize.x && uvCoord.x >= mpos.x+boxOffset.x-borderSize.x && uvCoord.y >= mpos.y+boxOffset.y-borderSize.y && uvCoord.y <= mpos.y+boxOffset.y+boxSize.y+borderSize.y ) { color = borderColor; } else { color = texture2D( texture, uvCoord ); } gl_FragColor = color; } slop-7.5/shaderexamples/boxzoom.vert000066400000000000000000000002241364416102700177500ustar00rootroot00000000000000#version 120 attribute vec2 position; attribute vec2 uv; varying vec2 uvCoord; void main() { uvCoord = uv; gl_Position = vec4(position,0,1); } slop-7.5/shaderexamples/crosshair.frag000066400000000000000000000024761364416102700202220ustar00rootroot00000000000000#version 120 uniform sampler2D texture; uniform sampler2D desktop; uniform vec2 screenSize; uniform vec2 mouse; varying vec2 uvCoord; void main() { // adjustable parameters float circleSize = 128; float borderSize = 2; // The smaller this value is, the more intense the magnification! float magnifyNerf = 1.1; vec4 borderColor = vec4(0,0,0,1); bool crosshair = true; // actual code vec2 mUV = vec2(mouse.x, -mouse.y)/screenSize + vec2(0,1); float du = distance(mUV,uvCoord); float dr = distance(mUV*screenSize,uvCoord*screenSize); vec4 color = vec4(0); if ( dr > circleSize+borderSize ) { color = texture2D( texture, uvCoord ); } else if ( dr < circleSize ) { if ( crosshair && (distance(mUV.x, uvCoord.x)<1/screenSize.x || distance(mUV.y,uvCoord.y)<1/screenSize.y) ) { color = borderColor; } else { float t = 1-du; vec2 b = uvCoord; vec2 c = (mUV-uvCoord); vec2 upsideDown = c/magnifyNerf*t*t+b; vec4 textureColor = texture2D( texture, upsideDown ); color = mix( texture2D( desktop, vec2(upsideDown.x, -upsideDown.y) ), textureColor, textureColor.a ); } } else if ( dr < circleSize+borderSize ) { color = borderColor; } gl_FragColor = color; } slop-7.5/shaderexamples/crosshair.vert000066400000000000000000000002241364416102700202500ustar00rootroot00000000000000#version 120 attribute vec2 position; attribute vec2 uv; varying vec2 uvCoord; void main() { uvCoord = uv; gl_Position = vec4(position,0,1); } slop-7.5/shaderexamples/hippie.frag000066400000000000000000000013431364416102700174730ustar00rootroot00000000000000#version 120 uniform sampler2D texture; uniform vec2 screenSize; uniform float time; varying vec2 uvCoord; const float pi = 3.14159265f; vec3 color(float x) { return max(min(sin(vec3(x,x+pi*2.0/3.0,x+pi*4.0/3.0))+0.5,1.0),0.0); } void main() { vec2 pos = (( gl_FragCoord.xy / screenSize.xy )-0.5)*screenSize.xy/screenSize.x*4.0; pos+=normalize(pos); pos.xy+=sin(pos.yx*10.0)*0.1; float r=(2.0/(dot(pos,pos)*10.0+1.0)); vec2 rr=vec2(cos(r),sin(r)); pos=pos.xy*rr.xx+pos.yx*rr.yy*vec2(-1.0,1.0); float f=(length(pos)*10.0)+time; //f=acos((pos.x/length(pos)*0.5+0.5)*pi); f+=sin(atan(pos.y,pos.x)*7.0)*5.0; vec4 rect = texture2D(texture,uvCoord); gl_FragColor = vec4(color(f),1.f)*rect; } slop-7.5/shaderexamples/hippie.vert000066400000000000000000000002241364416102700175310ustar00rootroot00000000000000#version 120 attribute vec2 position; attribute vec2 uv; varying vec2 uvCoord; void main() { uvCoord = uv; gl_Position = vec4(position,0,1); } slop-7.5/shaderexamples/invert.frag000066400000000000000000000004451364416102700175260ustar00rootroot00000000000000#version 120 uniform sampler2D texture; uniform sampler2D desktop; varying vec2 uvCoord; void main() { vec2 uv = vec2(uvCoord.x, -uvCoord.y); vec4 color = texture2D(desktop,uv); vec4 rect = texture2D(texture,uvCoord); gl_FragColor = vec4( 1.0 - color.rgb, color.a )*rect; } slop-7.5/shaderexamples/invert.vert000066400000000000000000000002241364416102700175620ustar00rootroot00000000000000#version 120 attribute vec2 position; attribute vec2 uv; varying vec2 uvCoord; void main() { uvCoord = uv; gl_Position = vec4(position,0,1); } slop-7.5/shaderexamples/refract.frag000066400000000000000000000055751364416102700176560ustar00rootroot00000000000000#version 120 uniform sampler2D texture; uniform sampler2D desktop; uniform vec2 screenSize; uniform float time; varying vec2 uvCoord; vec2 getDesktopUV( vec2 uv ) { // Desktop image is upside-down, blame X11 lmao uv.y = -uv.y; return uv; } const float pi = 3.14159265f; void main() { float sigma = 5; float numBlurPixelsPerSide = 2.0f; float blurMultiplier = 2.0f; vec2 tc = uvCoord.xy; vec2 p = -1.0 + 2.0 * tc; float len = length(p); vec2 offset = (p/len)*cos(len*12.0-time*4.0)*0.005; // Incremental Gaussian Coefficent Calculation (See GPU Gems 3 pp. 877 - 889) float blurSize = 1.f/screenSize.x*blurMultiplier; vec2 blurMultiplyVec = vec2(0.0f, 1.0f); vec3 incrementalGaussian; incrementalGaussian.x = 1.0f / (sqrt(2.0f * pi) * sigma); incrementalGaussian.y = exp(-0.5f / (sigma * sigma)); incrementalGaussian.z = incrementalGaussian.y * incrementalGaussian.y; vec4 avgValue = vec4(0.0f, 0.0f, 0.0f, 0.0f); float coefficientSum = 0.0f; // Take the central sample first... vec4 color = texture2D( desktop, getDesktopUV( uvCoord.xy ) + offset ); avgValue += color * incrementalGaussian.x; coefficientSum += incrementalGaussian.x; incrementalGaussian.xy *= incrementalGaussian.yz; // Go through the remaining 8 vertical samples (4 on each side of the center) for (float i = 1.0f; i <= numBlurPixelsPerSide; i++) { vec2 uv = (uvCoord.xy - i * blurSize * blurMultiplyVec); color = texture2D( desktop, getDesktopUV( uv ) + offset ); avgValue += color * incrementalGaussian.x; uv = (uvCoord.xy + i * blurSize * blurMultiplyVec); color = texture2D( desktop, getDesktopUV( uv ) + offset ); avgValue += color * incrementalGaussian.x; coefficientSum += 2 * incrementalGaussian.x; incrementalGaussian.xy *= incrementalGaussian.yz; } //Reset blurSize = 1.f/screenSize.x*blurMultiplier; blurMultiplyVec = vec2(1.0f, 0.0f); incrementalGaussian.x = 1.0f / (sqrt(2.0f * pi) * sigma); incrementalGaussian.y = exp(-0.5f / (sigma * sigma)); incrementalGaussian.z = incrementalGaussian.y * incrementalGaussian.y; // Go through the remaining 8 horizontal samples (4 on each side of the center) for (float i = 1.0f; i <= numBlurPixelsPerSide; i++) { vec2 uv = (uvCoord.xy - i * blurSize * blurMultiplyVec); vec4 color = texture2D( desktop, getDesktopUV( uv ) + offset ); avgValue += color * incrementalGaussian.x; uv = (uvCoord.xy + i * blurSize * blurMultiplyVec); color = texture2D( desktop, getDesktopUV( uv ) + offset ); avgValue += color * incrementalGaussian.x; coefficientSum += 2 * incrementalGaussian.x; incrementalGaussian.xy *= incrementalGaussian.yz; } vec4 rect = texture2D(texture,uvCoord); gl_FragColor = (avgValue / coefficientSum)*rect; } slop-7.5/shaderexamples/refract.vert000066400000000000000000000002241364416102700177010ustar00rootroot00000000000000#version 120 attribute vec2 position; attribute vec2 uv; varying vec2 uvCoord; void main() { uvCoord = uv; gl_Position = vec4(position,0,1); } slop-7.5/shaderexamples/wiggle.frag000066400000000000000000000011521364416102700174710ustar00rootroot00000000000000#version 120 uniform sampler2D texture; uniform vec2 screenSize; uniform float time; varying vec2 uvCoord; void main() { // Higher strength means bigger wobble float strength = 10; float flatness = 4; // Higher speed means faster wobble float speed = 2; float variation = cos(time); float x = uvCoord.x + (sin( time*speed + uvCoord.y/flatness * screenSize.y/strength ) + 0.5)/screenSize.x*strength; float y = uvCoord.y + variation*(cos( time*speed + uvCoord.x/flatness * screenSize.x/strength ) + 0.5)/screenSize.y*strength; gl_FragColor = texture2D( texture, vec2( x, y ) ); } slop-7.5/shaderexamples/wiggle.vert000066400000000000000000000002241364416102700175310ustar00rootroot00000000000000#version 120 attribute vec2 position; attribute vec2 uv; varying vec2 uvCoord; void main() { uvCoord = uv; gl_Position = vec4(position,0,1); } slop-7.5/slop.1000066400000000000000000000065311364416102700134120ustar00rootroot00000000000000.\" Manpage for slop. .\" Contact naelstrof@gmail.com to correct errors or typos. .TH SLOP 1 2017-03-21 Linux "slop man page" .SH NAME slop \- select operation .SH SYNOPSIS slop [-klqn] [OPTIONS] .SH DESCRIPTION slop is an application that queries for a selection from the user and prints the region to stdout. It grabs the mouse and turns it into a crosshair, lets the user click and drag to make a selection (or click on a window) while drawing a pretty box around it, then finally prints the selection's dimensions to stdout. .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 \-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/slop. See https://github.com/naelstrof/slop for more information on how to create your own shaders. .TP .BR \-f ", " \-\-format=\fISTRING\fR Sets the output format for slop. Format specifiers are %x (x offset), %y (y offset), %w (width), %h (height), %i (window id), %c (1 if cancelled, 0 otherwise), %g (geometry - `%wx%h+%x+%y'), and %% for a literal percent sign. .TP .BR \-n ", " \-\-nodecorations=INT 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'. Supplying slop with just `-n` is equivalent to supplying `-n1`. .TP .BR \-l ", " \-\-highlight Instead of outlining a selection, slop will highlight it instead. This is particularly useful if the color is set to an opacity lower than 1. .TP .BR \-D ", " \-\-nodrag Allows you to click twice to indicate a selection, rather than click-dragging. .TP .BR \-q ", " \-\-quiet Disable any unnecessary cerr output. Any warnings simply won't print. .TP .BR \-k ", " \-\-nokeyboard Disables the ability to cancel selections with the keyboard. .TP .BR \-o ", " \-\-noopengl Disables graphics acceleration. Might be useful if you get rendering bugs. .SH EXAMPLES To emulate a windows XP selection, you can use something like this: .PP .nf .RS slop --highlight --tolerance=0 --color=0.3,0.4,0.6,0.4 .RE .fi .PP In order to avoid using .BR eval(1) in your scripts (pretty big security issue), you can use slop like this instead: .PP .nf .RS read -r X Y W H G ID < <(slop -f "%x %y %w %h %g %i") .RE .fi .PP .SH SEE ALSO .BR maim(1) .SH BUGS No known bugs. .SH AUTHOR Dalton Nell (naelstrof@gmail.com) slop-7.5/src/000077500000000000000000000000001364416102700131355ustar00rootroot00000000000000slop-7.5/src/cxxopts.hpp000066400000000000000000000675121364416102700153710ustar00rootroot00000000000000/* 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 slop-7.5/src/framebuffer.cpp000066400000000000000000000113261364416102700161300ustar00rootroot00000000000000#include "framebuffer.hpp" slop::Framebuffer::Framebuffer( int w, int h ) { glGenFramebuffers( 1, &fbuffer ); glBindFramebuffer( GL_FRAMEBUFFER, fbuffer ); glGenTextures( 1, &image ); glBindTexture( GL_TEXTURE_2D, image ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, image, 0 ); glBindFramebuffer( GL_FRAMEBUFFER, 0 ); // generate our vertex and uv buffers std::vector verts; std::vector uvs; verts.push_back( glm::vec2(1,1) ); uvs.push_back( glm::vec2( 1, 1 ) ); verts.push_back( glm::vec2(-1,-1) ); uvs.push_back( glm::vec2( 0, 0 ) ); verts.push_back( glm::vec2(-1,1) ); uvs.push_back( glm::vec2( 0, 1 ) ); verts.push_back( glm::vec2(-1,-1) ); uvs.push_back( glm::vec2( 0, 0 ) ); verts.push_back( glm::vec2(1,1) ); uvs.push_back( glm::vec2( 1, 1 ) ); verts.push_back( glm::vec2(1,-1) ); uvs.push_back( glm::vec2( 1, 0 ) ); glGenBuffers( 2, buffers ); glBindBuffer( GL_ARRAY_BUFFER, buffers[0] ); glBufferData( GL_ARRAY_BUFFER, verts.size() * sizeof( glm::vec2 ), &verts[0], GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, buffers[1] ); glBufferData( GL_ARRAY_BUFFER, uvs.size() * sizeof( glm::vec2 ), &uvs[0], GL_STATIC_DRAW ); vertCount = verts.size(); generatedDesktopImage = false; } void slop::Framebuffer::setShader( slop::Shader* shader ) { this->shader = shader; if ( shader->hasParameter( "desktop" ) && !generatedDesktopImage ) { // Try to keep the image from being changed under our feet. XGrabServer(x11->display); XImage* image = XGetImage( x11->display, x11->root, 0, 0, WidthOfScreen( x11->screen ), HeightOfScreen( x11->screen ), 0xffffffff, ZPixmap ); XUngrabServer(x11->display); glEnable(GL_TEXTURE_2D); glGenTextures(1, &desktopImage); glBindTexture(GL_TEXTURE_2D, desktopImage); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); //glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, WidthOfScreen( x11->screen ), HeightOfScreen( x11->screen ), 0, GL_BGRA, GL_UNSIGNED_BYTE, (void*)(&(image->data[0]))); XDestroyImage( image ); generatedDesktopImage = true; } } slop::Framebuffer::~Framebuffer() { glDeleteTextures(1, &image); glDeleteFramebuffers(1,&fbuffer); glDeleteBuffers(2,buffers); } void slop::Framebuffer::resize( int w, int h ) { // Regenerate the image glDeleteTextures(1, &image); glBindTexture(GL_TEXTURE_2D, image); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Re-bind it to the framebuffer glBindFramebuffer( GL_FRAMEBUFFER, fbuffer ); glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, image, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); } void slop::Framebuffer::bind() { glBindFramebuffer( GL_FRAMEBUFFER, fbuffer ); } void slop::Framebuffer::unbind() { glBindFramebuffer( GL_FRAMEBUFFER, 0 ); } void slop::Framebuffer::draw(glm::vec2 mouse, float time, glm::vec4 color){ shader->bind(); shader->setParameter( "texture", 0 ); shader->setAttribute( "position", buffers[0], 2 ); shader->setAttribute( "uv", buffers[1], 2 ); if ( shader->hasParameter( "mouse" ) ) { shader->setParameter( "mouse", mouse ); } if ( shader->hasParameter( "color" ) ) { shader->setParameter( "color", color ); } if ( shader->hasParameter( "screenSize" ) ) { shader->setParameter( "screenSize", glm::vec2( WidthOfScreen( x11->screen ), HeightOfScreen( x11->screen ) )); } if ( shader->hasParameter( "time" ) ) { shader->setParameter( "time", time ); } glActiveTexture(GL_TEXTURE0); glBindTexture( GL_TEXTURE_2D, image ); if ( shader->hasParameter( "desktop" ) ) { shader->setParameter( "desktop", 1 ); glActiveTexture(GL_TEXTURE0 + 1); glBindTexture( GL_TEXTURE_2D, desktopImage ); } glEnable( GL_TEXTURE_2D ); glDrawArrays( GL_TRIANGLES, 0, vertCount ); glDisable( GL_TEXTURE_2D ); shader->unbind(); } slop-7.5/src/framebuffer.hpp000066400000000000000000000027751364416102700161450ustar00rootroot00000000000000/* framebuffer.hpp: Creates and manages an off-screen framebuffer. Uses supplied shader to draw it to the screen. * * Copyright (C) 2014: Dalton Nell, Slop Contributors (https://github.com/naelstrof/slop/graphs/contributors). * * This file is part of Slop. * * Slop 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. * * Slop 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 Slop. If not, see . */ #ifndef N_FRAMEBUFFER_H_ #define N_FRAMEBUFFER_H_ #include #include #include #include #include "shader.hpp" namespace slop { class Framebuffer { private: unsigned int fbuffer; unsigned int image; unsigned int buffers[2]; unsigned int vertCount; unsigned int desktopImage; bool generatedDesktopImage; Shader* shader; public: Framebuffer( int w, int h ); ~Framebuffer(); void setShader( slop::Shader* shader ); void draw(glm::vec2 mouse, float time, glm::vec4 color); void resize( int w, int h ); void bind(); void unbind(); }; } #endif slop-7.5/src/glrectangle.cpp000066400000000000000000000243611364416102700161360ustar00rootroot00000000000000#include "glrectangle.hpp" slop::GLRectangle::GLRectangle( glm::vec2 p1, glm::vec2 p2, float border, float padding, glm::vec4 color, bool highlight ) { this->color = color; this->border = border; this->padding = padding; this->highlight = highlight; // Find each corner of the rectangle ul = glm::vec2( glm::min( p1.x, p2.x ), glm::max( p1.y, p2.y ) ) ; bl = glm::vec2( glm::min( p1.x, p2.x ), glm::min( p1.y, p2.y ) ) ; ur = glm::vec2( glm::max( p1.x, p2.x ), glm::max( p1.y, p2.y ) ) ; br = glm::vec2( glm::max( p1.x, p2.x ), glm::min( p1.y, p2.y ) ) ; // Offset the inner corners by the padding. ul = ul + glm::vec2(-padding,padding); bl = bl + glm::vec2(-padding,-padding); ur = ur + glm::vec2(padding,padding); br = br + glm::vec2(padding,-padding); // Create the outer corners by offsetting the inner by the bordersize oul = ul + glm::vec2(-border,border); obl = bl + glm::vec2(-border,-border); our = ur + glm::vec2(border,border); obr = br + glm::vec2(border,-border); generateBuffers(); std::string vert = "#version 120\nattribute vec2 position;\nuniform mat4 projection;\nvoid main() {\ngl_Position = projection*vec4(position,0,1);\n}"; std::string frag = "#version 120\nuniform vec4 color;\nvoid main() {\ngl_FragColor = color;\n}"; shader = new Shader( vert, frag, false ); } void slop::GLRectangle::setPoints( glm::vec2 p1, glm::vec2 p2 ) { // Find each corner of the rectangle ul = glm::vec2( glm::min( p1.x, p2.x ), glm::max( p1.y, p2.y ) ) ; bl = glm::vec2( glm::min( p1.x, p2.x ), glm::min( p1.y, p2.y ) ) ; ur = glm::vec2( glm::max( p1.x, p2.x ), glm::max( p1.y, p2.y ) ) ; br = glm::vec2( glm::max( p1.x, p2.x ), glm::min( p1.y, p2.y ) ) ; // Offset the inner corners by the padding. ul = ul + glm::vec2(-padding,padding); bl = bl + glm::vec2(-padding,-padding); ur = ur + glm::vec2(padding,padding); br = br + glm::vec2(padding,-padding); // Create the outer corners by offsetting the inner by the bordersize oul = ul + glm::vec2(-border,border); obl = bl + glm::vec2(-border,-border); our = ur + glm::vec2(border,border); obr = br + glm::vec2(border,-border); generateBuffers(); } void slop::GLRectangle::generateBuffers() { std::vector rectangle_verts; std::vector rectangle_uvs; std::vector corner_verts; std::vector corner_uvs; std::vector center_verts; std::vector center_uvs; // Top left corner corner_verts.push_back( oul ); corner_uvs.push_back( glm::vec2(0, 1) ); corner_verts.push_back( ul ); corner_uvs.push_back( glm::vec2(1, 0) ); corner_verts.push_back( ul + glm::vec2( -border, 0 ) ); corner_uvs.push_back( glm::vec2(0, 0) ); corner_verts.push_back( oul ); corner_uvs.push_back( glm::vec2(0, 1) ); corner_verts.push_back( ul + glm::vec2( 0, border ) ); corner_uvs.push_back( glm::vec2(1, 1) ); corner_verts.push_back( ul ); corner_uvs.push_back( glm::vec2(1, 0) ); // Top right corner corner_verts.push_back( ur + glm::vec2( 0, border ) ); corner_uvs.push_back( glm::vec2(0, 1) ); corner_verts.push_back( ur + glm::vec2( border, 0 ) ); corner_uvs.push_back( glm::vec2(1, 0) ); corner_verts.push_back( ur ); corner_uvs.push_back( glm::vec2(0, 0) ); corner_verts.push_back( ur + glm::vec2( 0, border ) ); corner_uvs.push_back( glm::vec2(0, 1) ); corner_verts.push_back( our ); corner_uvs.push_back( glm::vec2(1, 1) ); corner_verts.push_back( ur + glm::vec2( border, 0 ) ); corner_uvs.push_back( glm::vec2(1, 0) ); // Bottom left corner corner_verts.push_back( bl + glm::vec2( -border, 0 ) ); corner_uvs.push_back( glm::vec2(0, 1) ); corner_verts.push_back( obl + glm::vec2( border, 0 ) ); corner_uvs.push_back( glm::vec2(1, 0) ); corner_verts.push_back( obl ); corner_uvs.push_back( glm::vec2(0, 0) ); corner_verts.push_back( bl + glm::vec2( -border, 0 ) ); corner_uvs.push_back( glm::vec2(0, 1) ); corner_verts.push_back( bl ); corner_uvs.push_back( glm::vec2(1, 1) ); corner_verts.push_back( bl + glm::vec2( 0, -border ) ); corner_uvs.push_back( glm::vec2(1, 0) ); // Bottom right corner corner_verts.push_back( br ); corner_uvs.push_back( glm::vec2(0, 1) ); corner_verts.push_back( obr ); corner_uvs.push_back( glm::vec2(1, 0) ); corner_verts.push_back( br + glm::vec2( 0, -border ) ); corner_uvs.push_back( glm::vec2(0, 0) ); corner_verts.push_back( br ); corner_uvs.push_back( glm::vec2(0, 1) ); corner_verts.push_back( br + glm::vec2( border, 0 ) ); corner_uvs.push_back( glm::vec2(1, 1) ); corner_verts.push_back( obr ); corner_uvs.push_back( glm::vec2(1, 0) ); // Left GLRectangle rectangle_verts.push_back( ul + glm::vec2( -border, 0 ) ); rectangle_uvs.push_back( glm::vec2(0, 1) ); rectangle_verts.push_back( bl ); rectangle_uvs.push_back( glm::vec2(1, 0) ); rectangle_verts.push_back( bl + glm::vec2( -border, 0 ) ); rectangle_uvs.push_back( glm::vec2(0, 0) ); rectangle_verts.push_back( ul + glm::vec2( -border, 0 ) ); rectangle_uvs.push_back( glm::vec2(0, 1) ); rectangle_verts.push_back( ul ); rectangle_uvs.push_back( glm::vec2(1, 1) ); rectangle_verts.push_back( bl ); rectangle_uvs.push_back( glm::vec2(1, 0) ); // Right GLRectangle rectangle_verts.push_back( ur ); rectangle_uvs.push_back( glm::vec2(0, 1) ); rectangle_verts.push_back( br + glm::vec2( border, 0 ) ); rectangle_uvs.push_back( glm::vec2(1, 0) ); rectangle_verts.push_back( br ); rectangle_uvs.push_back( glm::vec2(0, 0) ); rectangle_verts.push_back( ur ); rectangle_uvs.push_back( glm::vec2(0, 1) ); rectangle_verts.push_back( ur + glm::vec2( border, 0 ) ); rectangle_uvs.push_back( glm::vec2(1, 1) ); rectangle_verts.push_back( br + glm::vec2( border, 0 ) ); rectangle_uvs.push_back( glm::vec2(1, 0) ); // Top GLRectangle rectangle_verts.push_back( ul + glm::vec2( 0, border ) ); rectangle_uvs.push_back( glm::vec2(0, 1) ); rectangle_verts.push_back( ur ); rectangle_uvs.push_back( glm::vec2(1, 0) ); rectangle_verts.push_back( ul ); rectangle_uvs.push_back( glm::vec2(0, 0) ); rectangle_verts.push_back( ul + glm::vec2( 0, border ) ); rectangle_uvs.push_back( glm::vec2(0, 1) ); rectangle_verts.push_back( ur + glm::vec2( 0, border ) ); rectangle_uvs.push_back( glm::vec2(1, 1) ); rectangle_verts.push_back( ur ); rectangle_uvs.push_back( glm::vec2(1, 0) ); // Bot GLRectangle rectangle_verts.push_back( bl ); rectangle_uvs.push_back( glm::vec2(0, 1) ); rectangle_verts.push_back( br + glm::vec2( 0, -border ) ); rectangle_uvs.push_back( glm::vec2(1, 0) ); rectangle_verts.push_back( bl + glm::vec2( 0, -border ) ); rectangle_uvs.push_back( glm::vec2(0, 0) ); rectangle_verts.push_back( bl ); rectangle_uvs.push_back( glm::vec2(0, 1) ); rectangle_verts.push_back( br ); rectangle_uvs.push_back( glm::vec2(1, 1) ); rectangle_verts.push_back( br + glm::vec2( 0, -border ) ); rectangle_uvs.push_back( glm::vec2(1, 0) ); center_verts.push_back( ul ); center_uvs.push_back( glm::vec2(0, 1) ); center_verts.push_back( br ); center_uvs.push_back( glm::vec2(1, 0) ); center_verts.push_back( bl ); center_uvs.push_back( glm::vec2(0, 0) ); center_verts.push_back( ul ); center_uvs.push_back( glm::vec2(0, 1) ); center_verts.push_back( ur ); center_uvs.push_back( glm::vec2(1, 1) ); center_verts.push_back( br ); center_uvs.push_back( glm::vec2(1, 0) ); glGenBuffers( 6, (GLuint*)&buffer ); glBindBuffer( GL_ARRAY_BUFFER, buffer.corner_verts ); glBufferData( GL_ARRAY_BUFFER, corner_verts.size() * sizeof( glm::vec2 ), &corner_verts[0], GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, buffer.corner_uvs ); glBufferData( GL_ARRAY_BUFFER, corner_uvs.size() * sizeof( glm::vec2 ), &corner_uvs[0], GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, buffer.rectangle_verts ); glBufferData( GL_ARRAY_BUFFER, rectangle_verts.size() * sizeof( glm::vec2 ), &rectangle_verts[0], GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, buffer.rectangle_uvs ); glBufferData( GL_ARRAY_BUFFER, rectangle_uvs.size() * sizeof( glm::vec2 ), &rectangle_uvs[0], GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, buffer.center_verts ); glBufferData( GL_ARRAY_BUFFER, center_verts.size() * sizeof( glm::vec2 ), ¢er_verts[0], GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, buffer.rectangle_uvs ); glBufferData( GL_ARRAY_BUFFER, center_uvs.size() * sizeof( glm::vec2 ), ¢er_uvs[0], GL_STATIC_DRAW ); corner_vertCount = corner_verts.size(); rectangle_vertCount = rectangle_verts.size(); center_vertCount = center_verts.size(); } slop::GLRectangle::~GLRectangle() { delete shader; glDeleteBuffers( 6, (GLuint*)&buffer ); } void slop::GLRectangle::draw( glm::mat4& matrix ) { glEnable( GL_BLEND ); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); shader->bind(); shader->setParameter( "projection", matrix ); if ( highlight ) { // Draw the center of the highlight shader->setParameter( "color", color ); shader->setAttribute( "position", buffer.center_verts, 2 ); glDrawArrays(GL_TRIANGLES, 0, center_vertCount ); // Set the color to have no alpha, then draw the borders. glm::vec4 fullAlpha = glm::vec4(color.r,color.g,color.b,1); shader->setParameter( "color", fullAlpha ); shader->setAttribute( "position", buffer.corner_verts, 2 ); glDrawArrays(GL_TRIANGLES, 0, corner_vertCount ); shader->setAttribute( "position", buffer.rectangle_verts, 2 ); glDrawArrays(GL_TRIANGLES, 0, rectangle_vertCount ); } else { shader->setParameter( "color", color ); shader->setAttribute( "position", buffer.corner_verts, 2 ); glDrawArrays(GL_TRIANGLES, 0, corner_vertCount ); shader->setAttribute( "position", buffer.rectangle_verts, 2 ); glDrawArrays(GL_TRIANGLES, 0, rectangle_vertCount ); } shader->unbind(); glDisable( GL_BLEND ); } glm::vec4 slop::GLRectangle::getRect() { return glm::vec4( bl.x, bl.y, ur.x-ul.x, ul.y-bl.y ); } slop-7.5/src/glrectangle.hpp000066400000000000000000000036771364416102700161520ustar00rootroot00000000000000/* rectangle.hpp: generates a vertex mesh and draws it. * * Copyright (C) 2014: Dalton Nell, Slop Contributors (https://github.com/naelstrof/slop/graphs/contributors). * * This file is part of Slop. * * Slop 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. * * Slop 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 Slop. If not, see . */ #ifndef N_GLRECTANGLE_H_ #define N_GLRECTANGLE_H_ #include #include #include #include #include #include "shader.hpp" #include "rectangle.hpp" namespace slop { struct RectangleBuffer { unsigned int corner_verts; unsigned int corner_uvs; unsigned int rectangle_verts; unsigned int rectangle_uvs; unsigned int center_verts; unsigned int center_uvs; }; class GLRectangle : public Rectangle { private: glm::vec2 ul, oul; glm::vec2 bl, obl; glm::vec2 ur, our; glm::vec2 br, obr; bool highlight; void generateBuffers(); RectangleBuffer buffer; unsigned int corner_vertCount; unsigned int rectangle_vertCount; unsigned int center_vertCount; float border; float padding; Shader* shader; glm::vec4 color; public: glm::vec4 getRect(); GLRectangle(glm::vec2 p1, glm::vec2 p2, float border = 1, float padding = 0, glm::vec4 color = glm::vec4(1,1,1,1), bool highlight = false ); ~GLRectangle(); void setPoints( glm::vec2 p1, glm::vec2 p2 ); void draw(glm::mat4& matrix); }; } #endif // N_RECTANGLE_H_ slop-7.5/src/keyboard.cpp000066400000000000000000000053151364416102700154450ustar00rootroot00000000000000#include #include #include "keyboard.hpp" bool slop::Keyboard::getKey( KeySym key ) { KeyCode keycode = XKeysymToKeycode( x11->display, key ); if ( keycode != 0 ) { // Get the whole keyboard state char keys[32]; XQueryKeymap( x11->display, keys ); // Check our keycode return ( keys[ keycode / 8 ] & ( 1 << ( keycode % 8 ) ) ) != 0; } else { return false; } } // This returns if a key is currently pressed. // Ignores arrow key presses specifically so users can // adjust their selection. bool slop::Keyboard::anyKeyDown() { return keyDown; } void slop::Keyboard::update() { char keys[32]; XQueryKeymap( x11->display, keys ); // We first delete the arrow key buttons from the mapping. // This allows the user to press the arrow keys without triggering anyKeyDown KeyCode keycode = XKeysymToKeycode( x11->display, XK_Left ); keys[ keycode / 8 ] = keys[ keycode / 8 ] & ~( 1 << ( keycode % 8 ) ); keycode = XKeysymToKeycode( x11->display, XK_Right ); keys[ keycode / 8 ] = keys[ keycode / 8 ] & ~( 1 << ( keycode % 8 ) ); keycode = XKeysymToKeycode( x11->display, XK_Up ); keys[ keycode / 8 ] = keys[ keycode / 8 ] & ~( 1 << ( keycode % 8 ) ); keycode = XKeysymToKeycode( x11->display, XK_Down ); keys[ keycode / 8 ] = keys[ keycode / 8 ] & ~( 1 << ( keycode % 8 ) ); // Also deleting Space for move operation keycode = XKeysymToKeycode( x11->display, XK_space ); keys[ keycode / 8 ] = keys[ keycode / 8 ] & ~( 1 << ( keycode % 8 ) ); keyDown = false; for ( int i=0;i<32;i++ ) { if ( deltaState[i] == keys[i] ) { continue; } // Found a key in a group of 4 that's different char a = deltaState[i]; char b = keys[i]; // Find the "different" bits char c = a^b; // A new key was pressed since the last update. if ( c && b&c ) { keyDown = true; } deltaState[i] = keys[i]; } } slop::Keyboard::Keyboard( X11* x11 ) { this->x11 = x11; int err = XGrabKeyboard( x11->display, x11->root, False, GrabModeAsync, GrabModeAsync, CurrentTime ); int tries = 0; while( err != GrabSuccess && tries < 5 ) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); err = XGrabKeyboard( x11->display, x11->root, False, GrabModeAsync, GrabModeAsync, CurrentTime ); tries++; } // Non-fatal. if ( err != GrabSuccess ) { //throw std::runtime_error( "Couldn't grab the keyboard after 10 tries." ); } XQueryKeymap( x11->display, deltaState ); keyDown = false; } slop::Keyboard::~Keyboard() { XUngrabKeyboard( x11->display, CurrentTime ); } slop-7.5/src/keyboard.hpp000066400000000000000000000023741364416102700154540ustar00rootroot00000000000000/* keyboard.hpp: Interfaces with x11 to grab key press information. * * Copyright (C) 2014: Dalton Nell, Slop Contributors (https://github.com/naelstrof/slop/graphs/contributors). * * This file is part of Slop. * * Slop 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. * * Slop 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 Slop. If not, see . */ #ifndef N_KEYBOARD_H_ #define N_KEYBOARD_H_ #define XK_MISCELLANY #define XK_LATIN1 // for XK_space #include #include "x.hpp" namespace slop { class Keyboard { private: char deltaState[32]; X11* x11; bool keyDown; public: Keyboard( X11* x11 ); ~Keyboard(); void update(); bool getKey( KeySym key ); bool anyKeyDown(); }; extern Keyboard* keyboard; } #endif // N_KEYBOARD_H_ slop-7.5/src/main.cpp000066400000000000000000000375211364416102700145750ustar00rootroot00000000000000/* main.cpp: parses options, runs slop, prints results. * * Copyright (C) 2014: Dalton Nell, Slop Contributors (https://github.com/naelstrof/slop/graphs/contributors). * * This file is part of Slop. * * Slop 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. * * Slop 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 Slop. If not, see . */ #include #include #include #include #include #include "slop.hpp" #include "cxxopts.hpp" using namespace slop; glm::vec4 parseColor( std::string value ) { std::string valuecopy = value; glm::vec4 found; std::string::size_type sz; try { found[0] = std::stof(value,&sz); value = value.substr(sz+1); found[1] = std::stof(value,&sz); value = value.substr(sz+1); found[2] = std::stof(value,&sz); if ( value.size() != sz ) { value = value.substr(sz+1); found[3] = std::stof(value,&sz); if ( value.size() != sz ) { throw std::runtime_error("dur"); } } else { found[3] = 1; } } catch ( ... ) { throw 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; } SlopOptions* getOptions( 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( "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( "noopengl" ) > 0 ) { foo->noopengl = options["noopengl"].as(); } if ( options.count( "highlight" ) > 0 ) { foo->highlight = options["highlight"].as(); } if ( options.count( "nodrag" ) > 0 ) { foo->nodrag = options["nodrag"].as(); } if ( options.count( "quiet" ) > 0 ) { foo->quiet = options["quiet"].as(); } if ( options.count( "nodecorations" ) > 0 ) { foo->nodecorations = options["nodecorations"].as(); if ( foo->nodecorations < 0 || foo->nodecorations > 2 ) { throw std::invalid_argument( "--nodecorations must be between 0 and 2. Or be used as a flag." ); } } return foo; } std::string formatOutput( std::string input, SlopSelection selection ) { std::stringstream output; for( unsigned int i=0;i()) ("f,format", "Sets the output format for slop. Format specifiers are %x, %y, %w, %h, %i, %c, and %g. If actual percentage signs are desired in output, use a double percentage sign like so `%%`.", cxxopts::value()) ("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()) ("D,nodrag", "Select region with two clicks instead of click and drag") ("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 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'.", 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); // Options just validates all of our input from argv auto& positional = options["positional"].as>(); if ( positional.size() > 0 ) { throw std::invalid_argument("Unexpected positional argument: " + positional[0]); } bool help = false; if ( options.count( "help" ) > 0 ) { help = options["help"].as(); } if ( help ) { printHelp(); return 0; } bool version = false; if ( options.count( "version" ) > 0 ) { version = options["version"].as(); } if ( version ) { std::cout << SLOP_VERSION << "\n"; return 0; } // We then parse the options into something slop can understand. SlopOptions* parsedOptions = getOptions( options ); // We want to validate our format option if we got one, we do that by just doing a dry run // on a fake selection. SlopSelection selection(0,0,0,0,0,true); std::string format; bool gotFormat = options.count( "format" ) > 0; if ( gotFormat ) { format = options["format"].as(); formatOutput( format, selection ); } // Finally we do the real selection. selection = SlopSelect(parsedOptions); bool quiet = parsedOptions->quiet; // Here we're done with the parsed option data. delete parsedOptions; // We know if we cancelled or not if ( selection.cancelled ) { if ( !quiet ) { std::cerr << "Selection was cancelled by keystroke or right-click.\n"; } return 1; } // If we recieved a format option, we output the specified output. if ( gotFormat ) { std::cout << formatOutput( format, selection ); return 0; } std::cout << formatOutput( "%g\n", selection ); return 0; } int main( int argc, char** argv ) { try { return app( argc, argv ); } catch( std::exception& e ) { std::cerr << "Slop encountered an error:\n" << e.what() << "\n"; return 1; } // let the operating system handle any other kind of exception. return 1; } slop-7.5/src/mouse.cpp000066400000000000000000000114151364416102700147730ustar00rootroot00000000000000#include #include #include "mouse.hpp" void slop::Mouse::setButton( int button, int state ) { for (unsigned int i=0;idisplay, x11->root, &root, &child, &mx, &my, &wx, &wy, &mask ); return glm::vec2( mx, my ); } void slop::Mouse::setCursor( int cursor ) { if ( currentCursor == cursor ) { return; } XFreeCursor( x11->display, xcursor ); xcursor = XCreateFontCursor( x11->display, cursor ); XChangeActivePointerGrab( x11->display, PointerMotionMask | ButtonPressMask | ButtonReleaseMask | EnterWindowMask, xcursor, CurrentTime ); } slop::Mouse::Mouse(X11* x11, int nodecorations, Window ignoreWindow ) { this->x11 = x11; currentCursor = XC_cross; xcursor = XCreateFontCursor( x11->display, XC_cross ); hoverWindow = None; int err = XGrabPointer( x11->display, x11->root, True, PointerMotionMask | ButtonPressMask | ButtonReleaseMask | EnterWindowMask, GrabModeAsync, GrabModeAsync, None, xcursor, CurrentTime ); int tries = 0; while( err != GrabSuccess && tries < 5 ) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); err = XGrabPointer( x11->display, x11->root, True, PointerMotionMask | ButtonPressMask | ButtonReleaseMask | EnterWindowMask, GrabModeAsync, GrabModeAsync, None, xcursor, CurrentTime ); tries++; } if ( err != GrabSuccess ) { throw std::runtime_error( "Couldn't grab the mouse after 10 tries." ); } this->nodecorations = nodecorations; this->ignoreWindow = ignoreWindow; hoverWindow = findWindow(x11->root); } slop::Mouse::~Mouse() { XUngrabPointer( x11->display, CurrentTime ); } void slop::Mouse::update() { XEvent event; while ( XCheckTypedEvent( x11->display, ButtonPress, &event ) ) { setButton( event.xbutton.button, 1 ); } bool findNewWindow = false; while ( XCheckTypedEvent( x11->display, MotionNotify, &event ) ) { findNewWindow = true; } if ( findNewWindow ) { hoverWindow = findWindow(x11->root); } while ( XCheckTypedEvent( x11->display, ButtonRelease, &event ) ) { setButton( event.xbutton.button, 0 ); } while ( XCheckTypedEvent( x11->display, EnterNotify, &event ) ) { hoverWindow = event.xcrossing.window; } } Window slop::Mouse::findWindow( Window foo ) { glm::vec2 pos = getMousePos(); Window root, parent; Window* children; unsigned int nchildren; Window selectedWindow; XQueryTree( x11->display, foo, &root, &parent, &children, &nchildren ); if ( !children || nchildren <= 0 ) { return foo; } // The children are ordered, so we traverse backwards. for( int i=nchildren-1;i>=0;i-- ) { if ( children[i] == ignoreWindow ) { continue; } // We need to make sure the window is mapped. XWindowAttributes attr; XGetWindowAttributes( x11->display, children[i], &attr ); if ( attr.map_state != IsViewable ) { continue; } // We need to make sure we can get pixel data from it as well if ( attr.c_class == InputOnly ) { continue; } glm::vec4 rect = getWindowGeometry(children[i], false); float a = pos.x - rect.x; float b = pos.y - rect.y; if ( a <= rect.z && a >= 0 ) { if ( b <= rect.w && b >= 0 ) { selectedWindow = children[i]; switch( nodecorations ) { case 0: XFree(children); return selectedWindow; case 1: XFree(children); //return findWindow( selectedWindow ); XQueryTree( x11->display, selectedWindow, &root, &parent, &children, &nchildren ); if ( !children || nchildren <= 0 ) { return selectedWindow; } return children[nchildren-1]; case 2: return findWindow( selectedWindow ); } } } } return foo; } slop-7.5/src/mouse.hpp000066400000000000000000000027641364416102700150070ustar00rootroot00000000000000/* mouse.hpp: Interfaces with x11 to grab mouse information. * * Copyright (C) 2014: Dalton Nell, Slop Contributors (https://github.com/naelstrof/slop/graphs/contributors). * * This file is part of Slop. * * Slop 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. * * Slop 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 Slop. If not, see . */ #ifndef N_MOUSE_H_ #define N_MOUSE_H_ #include #include #include #include #include "x.hpp" namespace slop { class Mouse { private: X11* x11; std::vector buttons; Cursor xcursor; int currentCursor; Window findWindow( Window foo ); int nodecorations; Window ignoreWindow; public: Window hoverWindow; void update(); Mouse( X11* x11, int nodecorations, Window ignoreWindow ); ~Mouse(); void setCursor( int cursor ); glm::vec2 getMousePos(); void setButton( int button, int state ); int getButton( int button ); }; extern Mouse* mouse; } #endif // N_MOUSE_H_ slop-7.5/src/rectangle.cpp000066400000000000000000000004221364416102700156030ustar00rootroot00000000000000#include "rectangle.hpp" slop::Rectangle::Rectangle() { } slop::Rectangle::~Rectangle() { } void slop::Rectangle::setPoints( glm::vec2 p1, glm::vec2 p2 ) { } void slop::Rectangle::draw(glm::mat4& matrix) { } glm::vec4 slop::Rectangle::getRect() { return glm::vec4(); } slop-7.5/src/rectangle.hpp000066400000000000000000000021601364416102700156110ustar00rootroot00000000000000/* rectangle.hpp: Rectangle generic * * Copyright (C) 2014: Dalton Nell, Slop Contributors (https://github.com/naelstrof/slop/graphs/contributors). * * This file is part of Slop. * * Slop 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. * * Slop 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 Slop. If not, see . */ #ifndef N_RECTANGLE_H_ #define N_RECTANGLE_H_ #include namespace slop { class Rectangle { public: Rectangle(); virtual glm::vec4 getRect(); virtual ~Rectangle(); virtual void setPoints( glm::vec2 p1, glm::vec2 p2 ); virtual void draw(glm::mat4& matrix); }; } #endif // N_RECTANGLE_H_ slop-7.5/src/resource.cpp000066400000000000000000000040641364416102700154740ustar00rootroot00000000000000/* resource.cpp: Handles converting local paths to full paths. * * Copyright (C) 2014: Dalton Nell, Slop Contributors (https://github.com/naelstrof/slop/graphs/contributors). * * This file is part of Slop. * * Slop 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. * * Slop 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 Slop. If not, see . */ #include "resource.hpp" slop::Resource::Resource() { // Find the configuration directory. // usually ~/.config/slop and /usr/share/slop char* config = getenv( "XDG_CONFIG_HOME" ); if ( config == NULL ) { char* home = getpwuid(getuid())->pw_dir; usrconfig += home; usrconfig += "/.config/slop/"; return; } usrconfig += config; usrconfig += "/slop/"; } std::string slop::Resource::getRealPath( const std::string& localpath ) { if (localpath[0] == '/' && validatePath(dirname(localpath))) { return localpath; } if ( validatePath( usrconfig + localpath ) ) { return usrconfig + localpath; } std::string err = "The file or folder " + localpath + " was not found in " + usrconfig + "\n"; throw std::runtime_error(err); return localpath; } std::string slop::Resource::dirname(const std::string& localpath) { size_t i = localpath.find_last_of("/"); return (i != std::string::npos ? localpath.substr(0, i) : localpath); } bool slop::Resource::validatePath( const std::string& path ) { struct stat st; const char* dirname = path.c_str(); if ( stat( dirname, &st ) != 0 ) { return false; } // Lookin' good! return true; } slop-7.5/src/resource.hpp000066400000000000000000000026341364416102700155020ustar00rootroot00000000000000/* resource.hpp: Handles getting resources like textures and stuff. * * Copyright (C) 2014: Dalton Nell, Slop Contributors (https://github.com/naelstrof/slop/graphs/contributors). * * This file is part of Slop. * * Slop 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. * * Slop 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 Slop. If not, see . */ #ifndef N_RESOURCE_H_ #define N_RESOURCE_H_ #include #include #include #include #include #include #include #include #include #include #include namespace slop { class Resource { public: Resource(); std::string getRealPath( const std::string& localpath ); private: std::string dirname(const std::string& localpath); bool validatePath( const std::string& path ); std::string usrconfig; }; extern Resource* resource; } #endif // IS_RESOURCE_H_ slop-7.5/src/shader.cpp000066400000000000000000000133361364416102700151150ustar00rootroot00000000000000#include "shader.hpp" slop::Shader::Shader( std::string vert, std::string frag, bool file ) { std::string vert_contents; std::string frag_contents; if ( file ) { vert = resource->getRealPath(vert); frag = resource->getRealPath(frag); std::ifstream v( vert.c_str() ); if (!v.is_open()) { throw std::runtime_error( "Failed to open " + vert ); } vert_contents = std::string((std::istreambuf_iterator(v)), std::istreambuf_iterator()); std::ifstream f( frag.c_str() ); if (!f.is_open()) { throw std::runtime_error( "Failed to open " + frag ); } frag_contents = std::string((std::istreambuf_iterator(f)), std::istreambuf_iterator()); } else { vert_contents = vert; frag_contents = frag; } const char* vertsrc = vert_contents.c_str(); const char* fragsrc = frag_contents.c_str(); // Create the program to link to. program = glCreateProgram(); if ( vert_contents.length() <= 0 ) { std::string errstring = "Failed to open file (or is empty) `" + vert + "`.\n"; throw std::runtime_error(errstring); } if ( frag_contents.length() <= 0 ) { std::string errstring = "Failed to open file (or is empty) `" + frag + "`.\n"; throw std::runtime_error(errstring); } // Compile both shaders. unsigned int vertShader = glCreateShader( GL_VERTEX_SHADER ); glShaderSource( vertShader, 1, &vertsrc , NULL ); std::string errortxt; int err = compile( vertShader, errortxt ); if ( err ) { std::string errstring = "Failed to compile shader `" + vert + "`:\n" + errortxt; throw std::runtime_error(errstring); glDeleteShader( vertShader ); return; } unsigned int fragShader = glCreateShader( GL_FRAGMENT_SHADER ); glShaderSource( fragShader, 1, &fragsrc, NULL ); err = compile( fragShader, errortxt ); if ( err ) { std::string errstring = "Failed to compile shader `" + frag + "`:\n" + errortxt; throw std::runtime_error(errstring); glDeleteShader( vertShader ); glDeleteShader( fragShader ); return; } // Then attempt to link them to this shader. err = link( vertShader, fragShader, errortxt ); if ( err ) { std::string errstring = "Failed to link shader `" + vert + "` and `" + frag + "`:\n" + errortxt; throw std::runtime_error(errstring); glDeleteShader( vertShader ); glDeleteShader( fragShader ); return; } // Clean up :) glDeleteShader( vertShader ); glDeleteShader( fragShader ); glUseProgram( 0 ); } slop::Shader::~Shader() { glDeleteProgram( program ); } unsigned int slop::Shader::getProgram() { return program; } void slop::Shader::bind() { glUseProgram( program ); } int slop::Shader::compile( unsigned int shader, std::string& error ) { glCompileShader( shader ); // Compiling the shader is the easy part, all this junk down here is for printing the error it might generate. int result; int logLength; glGetShaderiv( shader, GL_COMPILE_STATUS, &result ); glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &logLength ); if ( result == false ) { char* errormsg = new char[ logLength ]; glGetShaderInfoLog( shader, logLength, NULL, errormsg ); error = errormsg; delete[] errormsg; return 1; } return 0; } int slop::Shader::link( unsigned int vertshader, unsigned int fragshader, std::string& error ) { glAttachShader( program, vertshader ); glAttachShader( program, fragshader ); glLinkProgram( program ); // Linking the shader is the easy part, all this junk down here is for printing the error it might generate. int result = false; int logLength; glGetProgramiv( program, GL_LINK_STATUS, &result); glGetProgramiv( program, GL_INFO_LOG_LENGTH, &logLength); if ( result == false ) { char* errormsg = new char[ logLength ]; glGetProgramInfoLog( program, logLength, NULL, errormsg ); error = errormsg; delete[] errormsg; return 1; } return 0; } unsigned int slop::Shader::getUniformLocation( std::string name ) { glUseProgram( program ); return glGetUniformLocation( program, name.c_str() ); } bool slop::Shader::hasParameter( std::string name ) { glUseProgram( program ); return glGetUniformLocation( program, name.c_str() ) != -1; } void slop::Shader::setParameter( std::string name, int foo ) { glUniform1i( getUniformLocation( name ), foo ); } void slop::Shader::setParameter( std::string name, float foo ) { glUniform1f( getUniformLocation( name ), foo ); } void slop::Shader::setParameter( std::string name, glm::mat4& foo ) { glUniformMatrix4fv( getUniformLocation( name ), 1, false, glm::value_ptr( foo ) ); } void slop::Shader::setParameter( std::string name, glm::vec4 foo ) { glUniform4f( getUniformLocation( name ), foo.x, foo.y, foo.z, foo.w ); } void slop::Shader::setParameter( std::string name, glm::vec2 foo ) { glUniform2f( getUniformLocation( name ), foo.x, foo.y ); } void slop::Shader::setAttribute( std::string name, unsigned int buffer, unsigned int stepsize ) { unsigned int a = glGetAttribLocation( program, name.c_str() ); glEnableVertexAttribArray( a ); glBindBuffer( GL_ARRAY_BUFFER, buffer ); glVertexAttribPointer( a, stepsize, GL_FLOAT, false, 0, NULL ); activeAttributes.push_back( a ); } void slop::Shader::unbind() { for ( unsigned int i=0; i. */ #ifndef N_SHADER_H_ #define N_SHADER_H_ #include #include #include #include #include #include #include #include #include #include "resource.hpp" #include "x.hpp" namespace slop { class Shader { public: Shader( std::string vert, std::string frag, bool file = true ); ~Shader(); unsigned int getProgram(); void bind(); void unbind(); bool hasParameter( std::string name ); void setParameter( std::string name, int foo ); void setParameter( std::string name, float foo ); void setParameter( std::string name, glm::mat4& foo ); void setParameter( std::string name, glm::vec4 foo ); void setParameter( std::string name, glm::vec2 foo ); void setAttribute( std::string name, unsigned int buffer, unsigned int stepsize ); private: std::vector activeAttributes; unsigned int getUniformLocation( std::string ); int compile( unsigned int shader, std::string& error ); int link( unsigned int vert, unsigned int frag, std::string& error ); unsigned int program; }; } #endif // N_SHADER_H_ slop-7.5/src/slop.cpp000066400000000000000000000347041364416102700146260ustar00rootroot00000000000000#ifdef SLOP_OPENGL #include #include #endif #include #include #include #include #include #include "slopstates.hpp" #include "mouse.hpp" #include "resource.hpp" #include "keyboard.hpp" #ifdef SLOP_OPENGL #include "window.hpp" #include "shader.hpp" #include "framebuffer.hpp" #include "glrectangle.hpp" #endif #include "xshaperectangle.hpp" #include "slop.hpp" namespace slop { X11* x11; Mouse* mouse; Keyboard* keyboard; Resource* resource; #ifdef SLOP_OPENGL SlopSelection GLSlopSelect( slop::SlopOptions* options, slop::SlopWindow* window ); #endif SlopSelection XShapeSlopSelect( slop::SlopOptions* options ); static int TmpXError(Display * d, XErrorEvent * ev) { return 0; } } template static void split(const std::string &s, char delim, Out result) { std::stringstream ss; ss.str(s); std::string item; while (std::getline(ss, item, delim)) { *(result++) = item; } } static std::vector split(const std::string &s, char delim) { std::vector elems; split(s, delim, std::back_inserter(elems)); return elems; } using namespace slop; char slop_default_xdisplay[] = ":0"; char slop_default_shaders[] = "textured"; // Defaults! slop::SlopOptions::SlopOptions() { border = 1; nokeyboard = false; noopengl = false; nodrag = false; nodecorations = false; tolerance = 2; padding = 0; shaders = slop_default_shaders; highlight = false; r = 0.5; g = 0.5; b = 0.5; a = 1; quiet = false; char* envdisplay = getenv("DISPLAY"); if (envdisplay == NULL) { xdisplay = slop_default_xdisplay; } else { xdisplay = envdisplay; } } slop::SlopSelection::SlopSelection( float x, float y, float w, float h, int id, bool cancelled ) { this->x = x; this->y = y; this->w = w; this->h = h; this->id = id; this->cancelled = cancelled; } slop::SlopSelection slop::SlopSelect( slop::SlopOptions* options ) { slop::SlopSelection returnval(0,0,0,0,0,true); bool deleteOptions = false; if ( !options ) { deleteOptions = true; options = new slop::SlopOptions(); } resource = new Resource(); // Set up x11 temporarily x11 = new X11(options->xdisplay); if ( !options->nokeyboard ) { XErrorHandler ph = XSetErrorHandler(slop::TmpXError); keyboard = new Keyboard( x11 ); XSetErrorHandler(ph); } #ifdef SLOP_OPENGL bool success = false; std::string errorstring = ""; SlopWindow* window; // First we check if we have a compositor available if ( x11->hasCompositor() && !options->noopengl ) { // If we have a compositor, we try using OpenGL try { window = new SlopWindow(); if (!GLEW_VERSION_3_0) { delete window; throw std::runtime_error( "OpenGL version is not high enough, slop requires OpenGL 3.0!\nOpenGL acceleration is disabled. Use -o or -q to suppress this message." ); } success = true; } catch( std::exception& e ) { errorstring += std::string(e.what()) + "\n"; success = false; } catch (...) { success = false; } } else { errorstring += "Failed to detect a compositor, OpenGL hardware-acceleration disabled...\n"; } if ( !success ) { // If we fail, we launch the XShape version of slop. if ( !options->quiet && !options->noopengl ) { if ( errorstring.length() <= 0 ) { errorstring += "Failed to launch OpenGL context, --shader parameter will be ignored.\n"; std::cerr << errorstring; } else { std::cerr << errorstring; } } #endif // SLOP_OPENGL returnval = slop::XShapeSlopSelect( options ); #ifdef SLOP_OPENGL } else { returnval = slop::GLSlopSelect( options, window ); } #endif delete x11; delete slop::resource; if ( deleteOptions ) { delete options; } return returnval; } slop::SlopSelection slop::XShapeSlopSelect( slop::SlopOptions* options ) { // Init our little state machine, memory is a tad of a misnomer bool cancelled = false; slop::SlopMemory* memory = new slop::SlopMemory( options, new XShapeRectangle(glm::vec2(0,0), glm::vec2(0,0), options->border, options->padding, glm::vec4( options->r, options->g, options->b, options->a ), options->highlight) ); slop::mouse = new slop::Mouse( x11, options->nodecorations, ((XShapeRectangle*)memory->rectangle)->window ); // We have no GL context, so the matrix is useless... glm::mat4 fake; // This is where we'll run through all of our stuffs auto last = std::chrono::high_resolution_clock::now(); while( memory->running ) { slop::mouse->update(); if ( !options->nokeyboard ) { slop::keyboard->update(); } // We move our statemachine forward. auto current = std::chrono::high_resolution_clock::now(); std::chrono::duration frametime = current-last; last = current; memory->update( frametime.count()/1000.f ); // We don't actually draw anything, but the state machine uses // this to know when to spawn the window. memory->draw( fake ); // X11 explodes if we update as fast as possible, here's a tiny sleep. XFlush(x11->display); std::this_thread::sleep_for(std::chrono::milliseconds(10)); // Then we draw the framebuffer to the screen if ( (!options->nokeyboard && slop::keyboard->anyKeyDown()) || slop::mouse->getButton( 3 ) ) { memory->running = false; cancelled = true; } } // Now we should have a selection! We parse everything we know about it here. glm::vec4 output = memory->rectangle->getRect(); // Lets now clear both front and back buffers before closing. // hopefully it'll be completely transparent while closing! // Then we clean up. delete slop::mouse; Window selectedWindow = memory->selectedWindow; delete memory; // Try to detect the window dying. int tries = 0; while( tries < 50 ) { XEvent event; if ( XCheckTypedEvent( x11->display, UnmapNotify, &event ) ) { break; } if ( XCheckTypedEvent( x11->display, DestroyNotify, &event ) ) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(10)); tries++; } // Finally return the data. return slop::SlopSelection( output.x, output.y, output.z, output.w, selectedWindow, cancelled ); } #ifdef SLOP_OPENGL slop::SlopSelection slop::GLSlopSelect( slop::SlopOptions* options, SlopWindow* window ) { bool cancelled = false; slop::mouse = new slop::Mouse( x11, options->nodecorations, window->window ); std::string vert = "#version 120\nattribute vec2 position;\nattribute vec2 uv;\nvarying vec2 uvCoord;\nvoid main()\n{\nuvCoord = uv;\ngl_Position = vec4(position,0,1);\n}\n"; std::string frag = "#version 120\nuniform sampler2D texture;\nvarying vec2 uvCoord;\nvoid main()\n {\ngl_FragColor = texture2D( texture, uvCoord );\n}\n"; slop::Shader* textured = new slop::Shader( vert, frag, false ); std::vector shaders; std::vector stringShaders = split( options->shaders, ',' ); for( int i=0;iborder, options->padding, glm::vec4( options->r, options->g, options->b, options->a ), options->highlight) ); slop::Framebuffer* pingpong = new slop::Framebuffer(WidthOfScreen(x11->screen), HeightOfScreen(x11->screen)); // This is where we'll run through all of our stuffs auto start = std::chrono::high_resolution_clock::now(); auto last = start; while( memory->running ) { slop::mouse->update(); if ( !options->nokeyboard ) { slop::keyboard->update(); } // We move our statemachine forward. auto current = std::chrono::high_resolution_clock::now(); std::chrono::duration frametime = current-last; last = current; memory->update( frametime.count()/1000.f ); // Then we draw our junk to a framebuffer. window->framebuffer->setShader( textured ); window->framebuffer->bind(); glClearColor (0.0, 0.0, 0.0, 0.0); glClear (GL_COLOR_BUFFER_BIT); memory->draw( window->camera ); window->framebuffer->unbind(); std::chrono::duration elapsed = current-start; int i; // We have our clean buffer, now to slather it with some juicy shader chains. glEnable( GL_BLEND ); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); for (i=0;i<=(int)shaders.size()-2;i+=2) { pingpong->bind(); glClearColor (0.0, 0.0, 0.0, 0.0); glClear (GL_COLOR_BUFFER_BIT); window->framebuffer->setShader( shaders[i] ); window->framebuffer->draw(slop::mouse->getMousePos(), elapsed.count()/1000.f, glm::vec4( options->r, options->g, options->b, options->a ) ); pingpong->unbind(); window->framebuffer->bind(); glClearColor (0.0, 0.0, 0.0, 0.0); glClear (GL_COLOR_BUFFER_BIT); pingpong->setShader( shaders[i+1] ); pingpong->draw(slop::mouse->getMousePos(), elapsed.count()/1000.f, glm::vec4( options->r, options->g, options->b, options->a ) ); window->framebuffer->unbind(); } for (;ibind(); glClearColor (0.0, 0.0, 0.0, 0.0); glClear (GL_COLOR_BUFFER_BIT); window->framebuffer->setShader( shaders[i] ); window->framebuffer->draw(slop::mouse->getMousePos(), elapsed.count()/1000.f, glm::vec4( options->r, options->g, options->b, options->a ) ); pingpong->unbind(); } glDisable( GL_BLEND ); if ( i%2 != 0 ) { window->framebuffer->draw(slop::mouse->getMousePos(), elapsed.count()/1000.f, glm::vec4( options->r, options->g, options->b, options->a ) ); } else { pingpong->draw(slop::mouse->getMousePos(), elapsed.count()/1000.f, glm::vec4( options->r, options->g, options->b, options->a ) ); } window->display(); // Here we sleep just to prevent our CPU usage from going to 100%. std::this_thread::sleep_for(std::chrono::milliseconds(10)); GLenum err = glGetError(); if ( err != GL_NO_ERROR ) { std::string error; switch(err) { case GL_INVALID_OPERATION: error="INVALID_OPERATION"; break; case GL_INVALID_ENUM: error="INVALID_ENUM"; break; case GL_INVALID_VALUE: error="INVALID_VALUE"; break; case GL_OUT_OF_MEMORY: error="OUT_OF_MEMORY"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: error="INVALID_FRAMEBUFFER_OPERATION"; break; } throw std::runtime_error( "OpenGL threw an error: " + error ); } if ( (!options->nokeyboard && slop::keyboard->anyKeyDown()) || slop::mouse->getButton( 3 ) ) { memory->running = false; cancelled = true; } } // Now we should have a selection! We parse everything we know about it here. glm::vec4 output = memory->rectangle->getRect(); // Lets now clear both front and back buffers before closing. // hopefully it'll be completely transparent while closing! glClearColor (0.0, 0.0, 0.0, 0.0); glClear (GL_COLOR_BUFFER_BIT); window->display(); glClear (GL_COLOR_BUFFER_BIT); window->display(); // Then we clean up. for( int i=0;iselectedWindow; delete memory; // Try to detect the window dying. int tries = 0; while( tries < 50 ) { XEvent event; if ( XCheckTypedEvent( x11->display, UnmapNotify, &event ) ) { break; } if ( XCheckTypedEvent( x11->display, DestroyNotify, &event ) ) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(10)); tries++; } // Finally return the data. return slop::SlopSelection( output.x, output.y, output.z, output.w, selectedWindow, cancelled ); } #endif extern "C" struct slop_options slop_options_default() { struct slop_options options; options.border = 1; options.nokeyboard = false; options.noopengl = false; options.nodecorations = false; options.tolerance = 2; options.padding = 0; options.shaders = slop_default_shaders; options.highlight = false; options.r = 0.5; options.g = 0.5; options.b = 0.5; options.a = 1; options.quiet = false; char* envdisplay = getenv("DISPLAY"); if (envdisplay == NULL) { options.xdisplay = slop_default_xdisplay; } else { options.xdisplay = envdisplay; } return options; } extern "C" struct slop_selection slop_select( struct slop_options* options ) { slop::SlopOptions realOptions = slop::SlopOptions(); if ( options != NULL ) { realOptions.border = options->border; realOptions.nokeyboard = options->nokeyboard; realOptions.noopengl = options->noopengl; realOptions.nodecorations = options->nodecorations; realOptions.tolerance = options->tolerance; realOptions.padding = options->padding; realOptions.shaders = options->shaders; realOptions.highlight = options->highlight; realOptions.r = options->r; realOptions.g = options->g; realOptions.b = options->b; realOptions.a = options->a; realOptions.quiet = options->quiet; realOptions.xdisplay = options->xdisplay; } slop::SlopSelection select = SlopSelect( &realOptions ); slop_selection realSelect; realSelect.x = select.x; realSelect.y = select.y; realSelect.w = select.w; realSelect.h = select.h; realSelect.id = select.id; realSelect.cancelled = select.cancelled; return realSelect; } slop-7.5/src/slop.hpp000066400000000000000000000046011364416102700146240ustar00rootroot00000000000000/* slop.hpp: exposes a selection interface * * Copyright (C) 2014: Dalton Nell, Slop Contributors (https://github.com/naelstrof/slop/graphs/contributors). * * This file is part of Slop. * * Slop 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. * * Slop 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 Slop. If not, see . */ #ifndef N_SLOP_H_ #define N_SLOP_H_ // Here we make some C-styled structs and function definitions, // allows other people to have a pure C interface to slop. struct slop_options { //SlopOptions(); int quiet; float border; float padding; float tolerance; int highlight; int noopengl; int nokeyboard; int nodecorations; char* shaders; float r; float g; float b; float a; char* xdisplay; }; struct slop_selection { //SlopSelection( float x, float y, float w, float h, int id, bool cancelled ); int cancelled; float x; float y; float w; float h; // This is an X11 Window ID int id; }; #ifdef __cplusplus namespace slop { class SlopOptions { public: SlopOptions(); bool quiet; float border; float padding; float tolerance; bool nodrag; bool highlight; bool noopengl; bool nokeyboard; bool nodecorations; char* shaders; float r; float g; float b; float a; char* xdisplay; }; class SlopSelection { public: SlopSelection( float x, float y, float w, float h, int id, bool cancelled ); bool cancelled; float x; float y; float w; float h; // This is an X11 Window ID int id; }; SlopSelection SlopSelect( SlopOptions* options = NULL ); } extern "C" struct slop_options slop_options_default(); extern "C" struct slop_selection slop_select( struct slop_options* options ); #else // __cplusplus struct slop_options slop_options_default(); struct slop_selection slop_select( struct slop_options* options ); #endif #endif // N_SLOP_H_ slop-7.5/src/slopstates.cpp000066400000000000000000000145271364416102700160530ustar00rootroot00000000000000#include "slopstates.hpp" using namespace slop; slop::SlopMemory::SlopMemory( SlopOptions* options, Rectangle* rect ) { up = false; running = true; state = (SlopState*)new SlopStart(); nextState = NULL; tolerance = options->tolerance; nodrag = options->nodrag; nodecorations = options->nodecorations; rectangle = rect; selectedWindow = x11->root; state->onEnter( *this ); } slop::SlopMemory::~SlopMemory() { delete state; if ( nextState ) { delete nextState; } delete rectangle; } void slop::SlopMemory::update( double dt ) { state->update( *this, dt ); if ( nextState ) { state->onExit( *this ); delete state; state = nextState; state->onEnter( *this ); nextState = NULL; } } void slop::SlopMemory::setState( SlopState* state ) { if ( nextState ) { delete nextState; } nextState = state; } void slop::SlopMemory::draw( glm::mat4& matrix ) { state->draw( *this, matrix ); } slop::SlopState::~SlopState() { } void slop::SlopState::onEnter( SlopMemory& memory ) { } void slop::SlopState::onExit( SlopMemory& memory ) { } void slop::SlopState::update( SlopMemory& memory, double dt ) { } void slop::SlopState::draw( SlopMemory& memory, glm::mat4 matrix ) { memory.rectangle->draw( matrix ); } void slop::SlopStart::onEnter( SlopMemory& memory ) { setStartPos = false; } void slop::SlopStart::update( SlopMemory& memory, double dt ) { if ( mouse->getButton( 1 ) && !setStartPos ) { startPoint = mouse->getMousePos(); setStartPos = true; } if ( setStartPos && glm::distance( startPoint, mouse->getMousePos() ) >= memory.tolerance ) { memory.setState( (SlopState*)new SlopStartDrag( startPoint ) ); } if ( mouse->hoverWindow != None ) { glm::vec4 rect = getWindowGeometry( mouse->hoverWindow, memory.nodecorations ); memory.rectangle->setPoints( glm::vec2( (float)rect.x, (float)rect.y ), glm::vec2( (float)rect.x+rect.z, (float)rect.y+rect.w ) ); } if ( (setStartPos && !mouse->getButton( 1 ) && !memory.nodrag) || (setStartPos && memory.nodrag && memory.up && mouse->getButton( 1 ) ) ) { memory.selectedWindow = mouse->hoverWindow; memory.setState( (SlopState*)new SlopEndDrag() ); } if ( setStartPos && memory.nodrag && !mouse->getButton( 1 )) { memory.up = true; } } void slop::SlopStart::draw( SlopMemory& memory, glm::mat4 matrix ) { if ( memory.tolerance > 0 ) { memory.rectangle->draw( matrix ); } } slop::SlopStartDrag::SlopStartDrag( glm::vec2 point ) { startPoint = point; } void slop::SlopStartDrag::onEnter( SlopMemory& memory ) { // redundant because it happens in upate() anyway //compensation comp = determineCompensation(); //setPoints( memory, comp ); } void slop::SlopStartDrag::update( SlopMemory& memory, double dt ) { if ( memory.nodrag && !memory.up && !mouse->getButton( 1 ) ) { memory.up = true; } if ( memory.nodrag && memory.up && mouse->getButton( 1 ) ) { memory.setState( (SlopState*)new SlopEndDrag() ); } // Determine which cursor to use char a = startPoint.y > mouse->getMousePos().y; char b = startPoint.x > mouse->getMousePos().x; char c = (a << 1) | b; switch ( c ) { case 0: mouse->setCursor( XC_lr_angle ); break; case 1: mouse->setCursor( XC_ll_angle ); break; case 2: mouse->setCursor( XC_ur_angle ); break; case 3: mouse->setCursor( XC_ul_angle ); break; } // Compensate for edges of screen, depending on the mouse position in relation to the start point. int lx = mouse->getMousePos().x < startPoint.x; int ly = mouse->getMousePos().y < startPoint.y; memory.rectangle->setPoints(startPoint+glm::vec2(1*lx,1*ly), mouse->getMousePos()+glm::vec2(1*(!lx), 1*(!ly))); if ( !memory.nodrag && !mouse->getButton( 1 ) ) { memory.setState( (SlopState*)new SlopEndDrag() ); return; } if ( keyboard ) { if ( keyboard->getKey(XK_space) ) { memory.setState( (SlopState*)new SlopStartMove( startPoint, mouse->getMousePos() ) ); return; } int arrows[2]; arrows[0] = keyboard->getKey(XK_Down)-keyboard->getKey(XK_Up); arrows[1] = keyboard->getKey(XK_Right)-keyboard->getKey(XK_Left); if ( arrows[0] || arrows[1] ) { if ( repeatTimer == 0 || repeatTimer > .4 ) { startPoint.y += arrows[0]*multiplier; startPoint.x += arrows[1]*multiplier; } if ( repeatTimer > 1 ) { multiplier += dt*2; } repeatTimer += dt; } else { repeatTimer = 0; multiplier = 1; } } } void slop::SlopEndDrag::onEnter( SlopMemory& memory ) { memory.running = false; } slop::SlopStartMove::SlopStartMove( glm::vec2 oldPoint, glm::vec2 newPoint ) { // oldPoint is where drag was started and newPoint where move was startPoint = oldPoint; // This vector is the diagonal of the rectangle // it will be used to move the startPoint along with mousePos diagonal = newPoint - oldPoint; } void slop::SlopStartMove::onEnter( SlopMemory& memory ) { // redundant because of update() //compensation comp = determineCompensation(); //setPoints( memory, comp ); mouse->setCursor( XC_fleur ); } void slop::SlopStartMove::update( SlopMemory& memory, double dt ) { // Unclear why it has to be - and not + startPoint = mouse->getMousePos() - diagonal; int lx = mouse->getMousePos().x < startPoint.x; int ly = mouse->getMousePos().y < startPoint.y; memory.rectangle->setPoints(startPoint+glm::vec2(1*lx,1*ly), mouse->getMousePos()+glm::vec2(1*(!lx), 1*(!ly))); // space or mouse1 released, return to drag // if mouse1 is released then drag will end also if ( !keyboard->getKey(XK_space) or !mouse->getButton( 1 ) ) { // clip rectangle on edges of screen. startPoint.x = glm::min((int)startPoint.x, WidthOfScreen(x11->screen)); startPoint.x = glm::max((int)startPoint.x, 0); startPoint.y = glm::min((int)startPoint.y, HeightOfScreen(x11->screen)); startPoint.y = glm::max((int)startPoint.y, 0); memory.setState( (SlopState*) new SlopStartDrag(startPoint) ); } } slop-7.5/src/slopstates.hpp000066400000000000000000000050401364416102700160460ustar00rootroot00000000000000/* slopstates.hpp: State machine stuffs. * * Copyright (C) 2014: Dalton Nell, Slop Contributors (https://github.com/naelstrof/slop/graphs/contributors). * * This file is part of Slop. * * Slop 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. * * Slop 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 Slop. If not, see . */ #ifndef N_SLOPSTATES_H_ #define N_SLOPSTATES_H_ #include "mouse.hpp" #include "keyboard.hpp" #include "slop.hpp" #include "rectangle.hpp" namespace slop { class SlopMemory; class SlopOptions; class SlopState { protected: glm::vec2 startPoint; public: virtual void onEnter( SlopMemory& memory ); virtual void onExit( SlopMemory& memory ); virtual void update( SlopMemory& memory, double dt ); virtual void draw( SlopMemory& memory, glm::mat4 matrix ); virtual ~SlopState(); }; class SlopStart : SlopState { private: bool setStartPos; public: virtual void onEnter( SlopMemory& memory ); virtual void update( SlopMemory& memory, double dt ); virtual void draw( SlopMemory& memory, glm::mat4 matrix ); }; class SlopStartDrag : SlopState { private: float repeatTimer; float multiplier; public: SlopStartDrag( glm::vec2 point ); virtual void onEnter( SlopMemory& memory ); virtual void update( SlopMemory& memory, double dt ); }; class SlopEndDrag : SlopState { public: virtual void onEnter( SlopMemory& memory ); }; class SlopStartMove : SlopState { private: glm::vec2 diagonal; public: SlopStartMove( glm::vec2 oldPoint, glm::vec2 newPoint ); virtual void onEnter( SlopMemory& memory ); virtual void update( SlopMemory& memory, double dt ); }; class SlopMemory { private: SlopState* state; SlopState* nextState; public: SlopMemory( SlopOptions* options, Rectangle* rect ); ~SlopMemory(); Window selectedWindow; bool running; float tolerance; bool nodecorations; bool nodrag; bool up; Rectangle* rectangle; void setState( SlopState* state ); void update( double dt ); void draw( glm::mat4& matrix ); }; } #endif // N_SLOPSTATES_H_ slop-7.5/src/window.cpp000066400000000000000000000121501364416102700151470ustar00rootroot00000000000000#include "window.hpp" using namespace slop; slop::SlopWindow::SlopWindow() { // Load up a opengl context static int attributeList[] = { GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, GLX_DOUBLEBUFFER, True, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1, GLX_ALPHA_SIZE, 1, None }; int nelements; int render_event_base, render_error_base; if(!XRenderQueryExtension(x11->display, &render_event_base, &render_error_base)) { throw std::runtime_error("No XRENDER extension found\n"); } GLXFBConfig* fbc = glXChooseFBConfig(x11->display, DefaultScreen(x11->display), attributeList, &nelements); GLXFBConfig fbconfig; if ( !fbc ) { throw std::runtime_error("No matching visuals available.\n"); } XVisualInfo* vi ; XRenderPictFormat *pictFormat; int i; for (i=0; idisplay, fbc[i]); if (!vi) { continue; } pictFormat = XRenderFindVisualFormat(x11->display, vi->visual); if (!pictFormat) { XFree( vi ); continue; } if(pictFormat->direct.alphaMask > 0) { fbconfig = fbc[i]; break; } else { XFree( vi ); } } if (i == nelements ) { throw std::runtime_error( "No matching visuals available" ); } XFree( fbc ); XSetWindowAttributes attributes; attributes.colormap = XCreateColormap(x11->display, RootWindow(x11->display, vi->screen), vi->visual, AllocNone); attributes.background_pixmap = None; attributes.border_pixel = 0; // Disable window decorations. attributes.override_redirect = True; // Make sure we know when we've been successfully destroyed later! attributes.event_mask = StructureNotifyMask; unsigned long valueMask = CWOverrideRedirect | CWColormap | CWBackPixmap | CWBorderPixel | CWEventMask; // Create the window window = XCreateWindow( x11->display, x11->root, 0, 0, WidthOfScreen( x11->screen ), HeightOfScreen( x11->screen ), 0, vi->depth, InputOutput, vi->visual, valueMask, &attributes ); XFree( vi ); if ( !window ) { throw std::runtime_error( "Couldn't create a GL window!" ); } // Prep some hints for the window static char title[] = "slop"; XWMHints* startup_state = XAllocWMHints(); startup_state->initial_state = NormalState; startup_state->flags = StateHint; XTextProperty textprop; textprop.value = (unsigned char*)title; textprop.encoding = XA_STRING; textprop.format = 8; textprop.nitems = strlen( title ); XSizeHints sizehints; sizehints.x = 0; sizehints.y = 0; sizehints.width = WidthOfScreen( x11->screen ); sizehints.height = HeightOfScreen( x11->screen ); sizehints.flags = USPosition | USSize; XClassHint classhints; char name[] = "slop"; classhints.res_name = name; classhints.res_class = name; // Finally send it all over... XSetClassHint( x11->display, window, &classhints ); XSetWMProperties( x11->display, window, &textprop, &textprop, NULL, 0, &sizehints, startup_state, NULL ); XFree( startup_state ); // Keep the window on top of all other windows. Atom stateAbove = XInternAtom(x11->display, "_NET_WM_STATE_ABOVE", False); XChangeProperty(x11->display, window, XInternAtom(x11->display, "_NET_WM_STATE", False), XA_ATOM, 32, PropModeReplace, (unsigned char *) &stateAbove, 1); context = glXCreateNewContext( x11->display, fbconfig, GLX_RGBA_TYPE, 0, True ); if ( !context ) { throw std::runtime_error( "Failed to create an OpenGL context." ); } setCurrent(); // Finally we grab some OpenGL 3.3 stuffs. GLenum err = glewInit(); if (GLEW_OK != err) { throw std::runtime_error((char*)glewGetErrorString(err)); } framebuffer = new Framebuffer( WidthOfScreen( x11->screen ), HeightOfScreen( x11->screen ) ); glViewport( 0, 0, WidthOfScreen( x11->screen ), HeightOfScreen( x11->screen ) ); camera = glm::ortho( 0.0f, (float)WidthOfScreen( x11->screen ), (float)HeightOfScreen( x11->screen ), 0.0f, -1.0f, 1.0f); // Last, we actually display the window <:o) XMapWindow( x11->display, window ); } slop::SlopWindow::~SlopWindow() { delete framebuffer; // Try to erase the window before destroying it. glClearColor( 0, 0, 0, 0 ); glClear( GL_COLOR_BUFFER_BIT ); display(); glClearColor( 0, 0, 0, 0 ); glClear( GL_COLOR_BUFFER_BIT ); display(); glXDestroyContext( x11->display, context ); XUnmapWindow( x11->display, window ); XDestroyWindow( x11->display, window ); glXMakeCurrent( x11->display, None, NULL ); } void slop::SlopWindow::display() { glXSwapBuffers( x11->display, window ); glXWaitGL(); } void slop::SlopWindow::setCurrent() { glXMakeCurrent( x11->display, window, context ); } slop-7.5/src/window.hpp000066400000000000000000000030241364416102700151540ustar00rootroot00000000000000/* window.hpp: Spawns and manages windows. By default it creates an OpenGL context with them. * * Copyright (C) 2014: Dalton Nell, Slop Contributors (https://github.com/naelstrof/slop/graphs/contributors). * * This file is part of Slop. * * Slop 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. * * Slop 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 Slop. If not, see . */ #ifndef N_WINDOW_H_ #define N_WINDOW_H_ #include #include #include #include #include #define GL_GLEXT_PROTOTYPES #define GLX_GLXEXT_PROTOTYPES #include #include #include #include #include #include #include "x.hpp" #include "framebuffer.hpp" namespace slop { class SlopWindow { public: Framebuffer* framebuffer; int width, height; glm::mat4 camera; GLXWindow window; GLXContext context; SlopWindow(); ~SlopWindow(); void setCurrent(); void display(); }; } #endif // N_WINDOW_H_ slop-7.5/src/x.cpp000066400000000000000000000105721364416102700141150ustar00rootroot00000000000000#include "x.hpp" using namespace slop; glm::vec4 slop::getWindowGeometry( Window win, bool removeDecoration ) { // 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 ( 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; } } // If we actually don't want the window frame (decoration), we just actually grab the decoration's innards. // And ignore all of the _NET_FRAME_EXTENTS information. if ( actualWindow != win && removeDecoration ) { win = actualWindow; window_frame = false; } // 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 specified isn't a window manager frame. // so we just rely on X to give a decent geometry. 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 ); } } bool X11::hasCompositor() { std::stringstream prop_name; prop_name << "_NET_WM_CM_S" << XScreenNumberOfScreen( screen ); Atom prop_atom = XInternAtom(display, prop_name.str().c_str(), False); return XGetSelectionOwner(display, prop_atom) != None; } X11::X11( std::string displayName ) { // Initialize display display = XOpenDisplay( displayName.c_str() ); if ( !display ) { throw std::runtime_error(std::string("Error: Failed to open X display: ") + displayName ); } screen = ScreenOfDisplay( display, DefaultScreen( display ) ); visual = DefaultVisual( display, XScreenNumberOfScreen( screen ) ); root = DefaultRootWindow( display ); } X11::~X11() { XCloseDisplay( display ); } slop-7.5/src/x.hpp000066400000000000000000000023671364416102700141250ustar00rootroot00000000000000/* x.hpp: initializes x11 * * Copyright (C) 2014: Dalton Nell, Slop Contributors (https://github.com/naelstrof/slop/graphs/contributors). * * This file is part of Slop. * * Slop 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. * * Slop 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 Slop. If not, see . */ #ifndef N_X_H_ #define N_X_H_ #include #include #include #include #include #include #include namespace slop { glm::vec4 getWindowGeometry( Window win, bool removeDecoration ); class X11 { public: bool hasCompositor(); X11( std::string displayName ); ~X11(); Display* display; Visual* visual; Screen* screen; Window root; }; extern X11* x11; } #endif slop-7.5/src/xshaperectangle.cpp000066400000000000000000000126621364416102700170250ustar00rootroot00000000000000#include "xshaperectangle.hpp" slop::XShapeRectangle::XShapeRectangle( glm::vec2 p1, glm::vec2 p2, float border, float padding, glm::vec4 color, bool highlight ) { this->color = convertColor( color ); this->border = border; this->padding = padding; this->highlight = highlight; this->alpha = color.a; // Find each corner of the rectangle ul = glm::vec2( glm::min( p1.x, p2.x ), glm::max( p1.y, p2.y ) ) ; bl = glm::vec2( glm::min( p1.x, p2.x ), glm::min( p1.y, p2.y ) ) ; ur = glm::vec2( glm::max( p1.x, p2.x ), glm::max( p1.y, p2.y ) ) ; br = glm::vec2( glm::max( p1.x, p2.x ), glm::min( p1.y, p2.y ) ) ; // Offset the inner corners by the padding. ul = ul + glm::vec2(-padding,padding); bl = bl + glm::vec2(-padding,-padding); ur = ur + glm::vec2(padding,padding); br = br + glm::vec2(padding,-padding); // Create the outer corners by offsetting the inner by the bordersize oul = ul + glm::vec2(-border,border); obl = bl + glm::vec2(-border,-border); our = ur + glm::vec2(border,border); obr = br + glm::vec2(border,-border); XSetWindowAttributes attributes; // Set up the window so it's our color attributes.background_pixel = this->color.pixel; // Disable window decorations. attributes.override_redirect = True; // Make sure we know when we've been successfully destroyed later! attributes.event_mask = StructureNotifyMask; unsigned long valueMask = CWBackPixel | CWOverrideRedirect | CWEventMask; // Create the window window = XCreateWindow( x11->display, x11->root, 0, 0, WidthOfScreen( x11->screen ), HeightOfScreen( x11->screen ), 0, CopyFromParent, InputOutput, CopyFromParent, valueMask, &attributes ); if ( alpha < 1 ) { // Change the window opacity unsigned int cardinal_alpha = (unsigned int) (alpha * (unsigned int)-1) ; XChangeProperty( x11->display, window, XInternAtom( x11->display, "_NET_WM_WINDOW_OPACITY", 0), XA_CARDINAL, 32, PropModeReplace, (unsigned char*)&cardinal_alpha, 1 ); } // Set the class hint, and title to "slop" XClassHint classhints; char name[] = "slop"; classhints.res_name = name; classhints.res_class = name; XSetClassHint( x11->display, window, &classhints ); // Now punch a hole into it so it looks like a selection rectangle, but only if we're not highlighting. generateHoles(); createdWindow = false; } void slop::XShapeRectangle::createWindow() { if ( createdWindow ) { return; } XMapWindow( x11->display, window ); createdWindow = true; } void slop::XShapeRectangle::generateHoles() { if ( !highlight ) { XRectangle rects[4]; // Left rects[0].x = oul.x; rects[0].y = obl.y; rects[0].width = border; rects[0].height = oul.y-obl.y; // Top rects[1].x = ul.x; rects[1].y = obl.y; rects[1].width = ur.x-ul.x; rects[1].height = border; // Right rects[2].x = ur.x; rects[2].y = obr.y; rects[2].width = border; rects[2].height = our.y - obr.y; // Bottom rects[3].x = bl.x; rects[3].y = ul.y; rects[3].width = br.x-bl.x; rects[3].height = border; XShapeCombineRectangles( x11->display, window, ShapeBounding, 0, 0, rects, 4, ShapeSet, 0); return; } XRectangle rect; rect.x = oul.x; rect.y = obl.y; rect.width = our.x-oul.x; rect.height = oul.y-obl.y; XShapeCombineRectangles( x11->display, window, ShapeBounding, 0, 0, &rect, 1, ShapeSet, 0); } void slop::XShapeRectangle::setPoints( glm::vec2 p1, glm::vec2 p2 ) { // Find each corner of the rectangle ul = glm::vec2( glm::min( p1.x, p2.x ), glm::max( p1.y, p2.y ) ) ; bl = glm::vec2( glm::min( p1.x, p2.x ), glm::min( p1.y, p2.y ) ) ; ur = glm::vec2( glm::max( p1.x, p2.x ), glm::max( p1.y, p2.y ) ) ; br = glm::vec2( glm::max( p1.x, p2.x ), glm::min( p1.y, p2.y ) ) ; // Offset the inner corners by the padding. ul = ul + glm::vec2(-padding,padding); bl = bl + glm::vec2(-padding,-padding); ur = ur + glm::vec2(padding,padding); br = br + glm::vec2(padding,-padding); // Create the outer corners by offsetting the inner by the bordersize oul = ul + glm::vec2(-border,border); obl = bl + glm::vec2(-border,-border); our = ur + glm::vec2(border,border); obr = br + glm::vec2(border,-border); generateHoles(); } slop::XShapeRectangle::~XShapeRectangle() { XUnmapWindow( x11->display, window ); XDestroyWindow( x11->display, window ); } void slop::XShapeRectangle::draw( glm::mat4& matrix ) { // We don't want to be visible until we're asked to draw. createWindow(); } glm::vec4 slop::XShapeRectangle::getRect() { return glm::vec4( bl.x, bl.y, ur.x-ul.x, ul.y-bl.y ); } XColor slop::XShapeRectangle::convertColor( glm::vec4 color ) { // Convert float colors to shorts. short red = short( floor( color.r * 65535.f ) ); short green = short( floor( color.g * 65535.f ) ); short blue = short( floor( color.b * 65535.f ) ); XColor xc; xc.red = red; xc.green = green; xc.blue = blue; int err = XAllocColor( x11->display, DefaultColormap( x11->display, XScreenNumberOfScreen( x11->screen ) ), &xc ); if ( err == BadColor ) { throw std::runtime_error(std::string("Couldn't allocate a color")); } return xc; } slop-7.5/src/xshaperectangle.hpp000066400000000000000000000034541364416102700170310ustar00rootroot00000000000000/* xshaperectangle.hpp: A rectangle that doesn't use OpenGL to function. * * Copyright (C) 2014: Dalton Nell, Slop Contributors (https://github.com/naelstrof/slop/graphs/contributors). * * This file is part of Slop. * * Slop 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. * * Slop 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 Slop. If not, see . */ #ifndef N_XSHAPERECTANGLE_H_ #define N_XSHAPERECTANGLE_H_ #include #include #include #include #include #include #include #include "x.hpp" #include "rectangle.hpp" namespace slop { class XShapeRectangle : public Rectangle { private: glm::vec2 ul, oul; glm::vec2 bl, obl; glm::vec2 ur, our; glm::vec2 br, obr; bool createdWindow; bool highlight; float border; float padding; XColor color; float alpha; XColor convertColor( glm::vec4 color ); void generateHoles(); void createWindow(); public: Window window; glm::vec4 getRect(); XShapeRectangle(glm::vec2 p1, glm::vec2 p2, float border = 1, float padding = 0, glm::vec4 color = glm::vec4(1,1,1,1), bool highlight = false ); ~XShapeRectangle(); void setPoints( glm::vec2 p1, glm::vec2 p2 ); void draw(glm::mat4& matrix); }; } #endif // N_XSHAPERECTANGLE_H_