From 4642216f70dd98134a79f9299b7ca4bc876649c7 Mon Sep 17 00:00:00 2001 From: Vito Caputo Date: Sun, 28 Aug 2016 00:36:53 -0700 Subject: *: refactor all the things Long overdue house cleaning. The addition of compositing/monitoring overlays in vwm3 pushed vwm well past what is a reasonable size for a simple thousand line file. This is a first step towards restoring sanity in the code, but no behavioral differences are intended, this is mostly just shuffling around and organizing code. I expect some performance regressions initially, follow-on commits will make more improvements to that end as the dust settles. --- .gitignore | 1 + colors.def | 6 - launchers.def | 8 - libvmon/LICENSE | 674 -------- libvmon/bitmap.h | 15 - libvmon/defs/_begin.def | 549 ------- libvmon/defs/_end.def | 43 - libvmon/defs/proc_files.def | 8 - libvmon/defs/proc_io.def | 33 - libvmon/defs/proc_stat.def | 105 -- libvmon/defs/proc_vm.def | 19 - libvmon/defs/proc_wants.def | 14 - libvmon/defs/sys_stat.def | 114 -- libvmon/defs/sys_vm.def | 169 -- libvmon/defs/sys_wants.def | 7 - libvmon/vmon.c | 1634 ------------------- libvmon/vmon.h | 308 ---- list.h | 252 --- src/clickety.c | 244 +++ src/clickety.h | 12 + src/colors.def | 6 + src/composite.c | 331 ++++ src/composite.h | 24 + src/context.c | 97 ++ src/context.h | 14 + src/desktop.c | 158 ++ src/desktop.h | 25 + src/key.c | 371 +++++ src/key.h | 11 + src/launch.c | 45 + src/launch.h | 13 + src/launchers.def | 8 + src/libvmon/LICENSE | 674 ++++++++ src/libvmon/bitmap.h | 15 + src/libvmon/defs/_begin.def | 549 +++++++ src/libvmon/defs/_end.def | 43 + src/libvmon/defs/proc_files.def | 8 + src/libvmon/defs/proc_io.def | 33 + src/libvmon/defs/proc_stat.def | 105 ++ src/libvmon/defs/proc_vm.def | 19 + src/libvmon/defs/proc_wants.def | 14 + src/libvmon/defs/sys_stat.def | 114 ++ src/libvmon/defs/sys_vm.def | 169 ++ src/libvmon/defs/sys_wants.def | 7 + src/libvmon/vmon.c | 1634 +++++++++++++++++++ src/libvmon/vmon.h | 308 ++++ src/list.h | 252 +++ src/logo.c | 66 + src/logo.h | 8 + src/overlay.c | 960 ++++++++++++ src/overlay.h | 36 + src/screen.c | 152 ++ src/screen.h | 19 + src/vwm.c | 291 ++++ src/vwm.h | 79 + src/window.c | 468 ++++++ src/window.h | 81 + src/xevent.c | 269 ++++ src/xevent.h | 18 + src/xwindow.c | 247 +++ src/xwindow.h | 52 + vwm.c | 3285 --------------------------------------- vwm.h | 84 - 63 files changed, 8050 insertions(+), 7327 deletions(-) delete mode 100644 colors.def delete mode 100644 launchers.def delete mode 100644 libvmon/LICENSE delete mode 100644 libvmon/bitmap.h delete mode 100644 libvmon/defs/_begin.def delete mode 100644 libvmon/defs/_end.def delete mode 100644 libvmon/defs/proc_files.def delete mode 100644 libvmon/defs/proc_io.def delete mode 100644 libvmon/defs/proc_stat.def delete mode 100644 libvmon/defs/proc_vm.def delete mode 100644 libvmon/defs/proc_wants.def delete mode 100644 libvmon/defs/sys_stat.def delete mode 100644 libvmon/defs/sys_vm.def delete mode 100644 libvmon/defs/sys_wants.def delete mode 100644 libvmon/vmon.c delete mode 100644 libvmon/vmon.h delete mode 100644 list.h create mode 100644 src/clickety.c create mode 100644 src/clickety.h create mode 100644 src/colors.def create mode 100644 src/composite.c create mode 100644 src/composite.h create mode 100644 src/context.c create mode 100644 src/context.h create mode 100644 src/desktop.c create mode 100644 src/desktop.h create mode 100644 src/key.c create mode 100644 src/key.h create mode 100644 src/launch.c create mode 100644 src/launch.h create mode 100644 src/launchers.def create mode 100644 src/libvmon/LICENSE create mode 100644 src/libvmon/bitmap.h create mode 100644 src/libvmon/defs/_begin.def create mode 100644 src/libvmon/defs/_end.def create mode 100644 src/libvmon/defs/proc_files.def create mode 100644 src/libvmon/defs/proc_io.def create mode 100644 src/libvmon/defs/proc_stat.def create mode 100644 src/libvmon/defs/proc_vm.def create mode 100644 src/libvmon/defs/proc_wants.def create mode 100644 src/libvmon/defs/sys_stat.def create mode 100644 src/libvmon/defs/sys_vm.def create mode 100644 src/libvmon/defs/sys_wants.def create mode 100644 src/libvmon/vmon.c create mode 100644 src/libvmon/vmon.h create mode 100644 src/list.h create mode 100644 src/logo.c create mode 100644 src/logo.h create mode 100644 src/overlay.c create mode 100644 src/overlay.h create mode 100644 src/screen.c create mode 100644 src/screen.h create mode 100644 src/vwm.c create mode 100644 src/vwm.h create mode 100644 src/window.c create mode 100644 src/window.h create mode 100644 src/xevent.c create mode 100644 src/xevent.h create mode 100644 src/xwindow.c create mode 100644 src/xwindow.h delete mode 100644 vwm.c delete mode 100644 vwm.h diff --git a/.gitignore b/.gitignore index 551120e..e537ae5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ *.o vwm +*.swp diff --git a/colors.def b/colors.def deleted file mode 100644 index 97c0dc9..0000000 --- a/colors.def +++ /dev/null @@ -1,6 +0,0 @@ -color(focused_window_border, "Green") -color(shelved_window_border, "purple") -color(unfocused_window_border, "DarkGray") -color(shelved_console_border, "red") -color(rubberband, "Orange") -color(logo, "LimeGreen") diff --git a/launchers.def b/launchers.def deleted file mode 100644 index 2c63f96..0000000 --- a/launchers.def +++ /dev/null @@ -1,8 +0,0 @@ -/* it's up to you to ensure you don't conflict with the global VWM keys */ -/* keysym, label, cmd */ -launcher( XK_x, "xterm", "/usr/bin/xterm") -launcher( XK_b, "iceweasel", "/usr/bin/iceweasel -ProfileManager -no-remote") -launcher( XK_g, "gimp", "/usr/bin/gimp") -launcher( XK_period, "lock", "/usr/bin/xlock") -launcher( XK_minus, "dpms off", "/usr/bin/xset -dpms s off") -launcher( XK_equal, "dpms on", "/usr/bin/xset +dpms s on") diff --git a/libvmon/LICENSE b/libvmon/LICENSE deleted file mode 100644 index 94a9ed0..0000000 --- a/libvmon/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ - 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 -. diff --git a/libvmon/bitmap.h b/libvmon/bitmap.h deleted file mode 100644 index eacb97d..0000000 --- a/libvmon/bitmap.h +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef _BITMAP_H -#define _BITMAP_H - -/* simple implementation of general-purpose bitmap macros taken from the comp.lang.c FAQ */ - -#include /* for CHAR_BIT */ - -#define BITMASK(b) (1 << ((b) % CHAR_BIT)) -#define BITSLOT(b) ((b) / CHAR_BIT) -#define BITSET(a, b) ((a)[BITSLOT(b)] |= BITMASK(b)) -#define BITCLEAR(a, b) ((a)[BITSLOT(b)] &= ~BITMASK(b)) -#define BITTEST(a, b) ((a)[BITSLOT(b)] & BITMASK(b)) -#define BITNSLOTS(nb) ((nb + CHAR_BIT - 1) / CHAR_BIT) - -#endif diff --git a/libvmon/defs/_begin.def b/libvmon/defs/_begin.def deleted file mode 100644 index 047fd4d..0000000 --- a/libvmon/defs/_begin.def +++ /dev/null @@ -1,549 +0,0 @@ -/* the common types are handled in _begin.def and _end.def, individual .def files are free to create special types as well, but should - * provide macros for all the ifdef's supported here for any additions. - */ - -/* for declaring the want-specific sample data structure (used by vmon.h) */ -#ifdef VMON_DECLARE_MEMBERS -#define vmon_datum_str(_name, _sym, _label, _desc) char *_name; -#define vmon_datum_str_array(_name, _sym, _label, _desc) char **_name; -#define vmon_datum_char(_name, _sym, _label, _desc) char _name; -#define vmon_datum_char_array(_name, _sym, _label, _desc) vmon_char_array_t _name; -#define vmon_datum_int(_name, _sym, _label, _desc) int _name; -#define vmon_datum_uint(_name, _sym, _label, _desc) unsigned int _name; -#define vmon_datum_ulong(_name, _sym, _label, _desc) unsigned long _name; -#define vmon_datum_ulonglong(_name, _sym, _label, _desc) unsigned long long _name; -#define vmon_datum_long(_name, _sym, _label, _desc) long _name; -#define vmon_datum_longlong(_name, _sym, _label, _desc) long long _name; - -/* leave omissions undefined, they'll get defined as noops at the end of this file */ -#endif - - - -/* for creating the symbolic constants enumeration (used by vmon.h) */ -#ifdef VMON_ENUM_SYMBOLS -#define vmon_datum_str(_name, _sym, _label, _desc) VMON_ ## _sym, -#define vmon_datum_str_array(_name, _sym, _label, _desc) VMON_ ## _sym, -#define vmon_datum_char(_name, _sym, _label, _desc) VMON_ ## _sym, -#define vmon_datum_char_array(_name, _sym, _label, _desc) VMON_ ## _sym, -#define vmon_datum_int(_name, _sym, _label, _desc) VMON_ ## _sym, -#define vmon_datum_uint(_name, _sym, _label, _desc) VMON_ ## _sym, -#define vmon_datum_ulong(_name, _sym, _label, _desc) VMON_ ## _sym, -#define vmon_datum_ulonglong(_name, _sym, _label, _desc) VMON_ ## _sym, -#define vmon_datum_long(_name, _sym, _label, _desc) VMON_ ## _sym, -#define vmon_datum_longlong(_name, _sym, _label, _desc) VMON_ ## _sym, - -/* leave omissions undefined, they'll get defined as noops at the end of this file */ -#endif - - - -/* for creating an offset table relating symbols to struct member offsets */ -#ifdef VMON_INITIALIZE_OFFSET_TABLE -/* TODO: error out using #error if VMON_OFFSET_TABLE_STRUCT is not defined */ -/* I use the gcc builtin here because it's convenient, otherwise we either do the double macro expansion dance or put the offsetof definition here */ -#define vmon_datum_str(_name, _sym, _label, _desc) __builtin_offsetof(VMON_OFFSET_TABLE_STRUCT, _name), -#define vmon_datum_str_array(_name, _sym, _label, _desc) __builtin_offsetof(VMON_OFFSET_TABLE_STRUCT, _name), -#define vmon_datum_char(_name, _sym, _label, _desc) __builtin_offsetof(VMON_OFFSET_TABLE_STRUCT, _name), -#define vmon_datum_char_array(_name, _sym, _label, _desc) __builtin_offsetof(VMON_OFFSET_TABLE_STRUCT, _name), -#define vmon_datum_int(_name, _sym, _label, _desc) __builtin_offsetof(VMON_OFFSET_TABLE_STRUCT, _name), -#define vmon_datum_uint(_name, _sym, _label, _desc) __builtin_offsetof(VMON_OFFSET_TABLE_STRUCT, _name), -#define vmon_datum_ulong(_name, _sym, _label, _desc) __builtin_offsetof(VMON_OFFSET_TABLE_STRUCT, _name), -#define vmon_datum_ulonglong(_name, _sym, _label, _desc) __builtin_offsetof(VMON_OFFSET_TABLE_STRUCT, _name), -#define vmon_datum_long(_name, _sym, _label, _desc) __builtin_offsetof(VMON_OFFSET_TABLE_STRUCT, _name), -#define vmon_datum_longlong(_name, _sym, _label, _desc) __builtin_offsetof(VMON_OFFSET_TABLE_STRUCT, _name), - -/* no offsets can exist for omitted members, so they're declared as nops */ -/* leave omissions undefined, they'll get defined as noops at the end of this file */ -#endif - - - -/* for creating a lookup table for the member names as strings, indexed by the enumerated symbols */ -#ifdef VMON_INITIALIZE_NAME_TABLE -#define vmon_datum_str(_name, _sym, _label, _desc) #_name , -#define vmon_datum_str_array(_name, _sym, _label, _desc) #_name , -#define vmon_datum_char(_name, _sym, _label, _desc) #_name , -#define vmon_datum_char_array(_name, _sym, _label, _desc) #_name , -#define vmon_datum_int(_name, _sym, _label, _desc) #_name , -#define vmon_datum_uint(_name, _sym, _label, _desc) #_name , -#define vmon_datum_ulong(_name, _sym, _label, _desc) #_name , -#define vmon_datum_ulonglong(_name, _sym, _label, _desc) #_name , -#define vmon_datum_long(_name, _sym, _label, _desc) #_name , -#define vmon_datum_longlong(_name, _sym, _label, _desc) #_name , - -/* leave omissions undefined, they'll get defined as noops at the end of this file */ -#endif - - - -/* for creating a lookup table for the human-readable descriptions, indexed by the enumerated symbols */ -#ifdef VMON_INITIALIZE_DESC_TABLE -#define vmon_datum_str(_name, _sym, _label, _desc) _desc , -#define vmon_datum_str_array(_name, _sym, _label, _desc) _desc , -#define vmon_datum_char(_name, _sym, _label, _desc) _desc , -#define vmon_datum_char_array(_name, _sym, _label, _desc) _desc , -#define vmon_datum_int(_name, _sym, _label, _desc) _desc , -#define vmon_datum_uint(_name, _sym, _label, _desc) _desc , -#define vmon_datum_ulong(_name, _sym, _label, _desc) _desc , -#define vmon_datum_ulonglong(_name, _sym, _label, _desc) _desc , -#define vmon_datum_long(_name, _sym, _label, _desc) _desc , -#define vmon_datum_longlong(_name, _sym, _label, _desc) _desc , - -/* leave omissions undefined, they'll get defined as noops at the end of this file */ -#endif - - - -/* these are different from the symbols, because they ignore the omissions, the definition includes all fields so we can parse the file, - * but the symbols only relate to fields we actually store in memory. */ -#ifdef VMON_ENUM_PARSER_STATES -#define vmon_datum_str(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, -#define vmon_datum_str_array(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, -#define vmon_datum_char(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, -#define vmon_datum_char_array(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, -#define vmon_datum_int(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, -#define vmon_datum_uint(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, -#define vmon_datum_ulong(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, -#define vmon_datum_ulonglong(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, -#define vmon_datum_long(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, -#define vmon_datum_longlong(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, - -#define vmon_omit_n(_n, _sym, _desc) VMON_PARSER_STATE_ ## _sym, -#define vmon_omit_literal(_lit, _sym) VMON_PARSER_STATE_ ## _sym, -#define vmon_omit_run(_char, _sym) VMON_PARSER_STATE_ ## _sym, -#define vmon_omit_str(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, -#define vmon_omit_str_array(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, -#define vmon_omit_char(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, -#define vmon_omit_char_array(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, -#define vmon_omit_int(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, -#define vmon_omit_uint(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, -#define vmon_omit_ulong(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, -#define vmon_omit_ulonglong(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, -#define vmon_omit_long(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, -#define vmon_omit_longlong(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, -#endif - - -/* most the stuff we need in scope for the parser generated via VMON_IMPLEMENT_PARSER before including the appropriate .def */ -#ifdef VMON_PREPARE_PARSER - char input; - int var_isneg = 0; - int var_int = 0; - unsigned int var_uint = 0; - long var_long = 0; - long long var_longlong = 0; - unsigned long var_ulong = 0; - unsigned long long var_ulonglong = 0; - char *var_array = NULL; - int var_array_alloc_len = 0, var_array_len = 0; - -#define vmon_datum_str(_name, _sym, _label, _desc) -#define vmon_datum_str_array(_name, _sym, _label, _desc) -#define vmon_datum_char(_name, _sym, _label, _desc) -#define vmon_datum_char_array(_name, _sym, _label, _desc) -#define vmon_datum_int(_name, _sym, _label, _desc) -#define vmon_datum_uint(_name, _sym, _label, _desc) -#define vmon_datum_ulong(_name, _sym, _label, _desc) -#define vmon_datum_ulonglong(_name, _sym, _label, _desc) -#define vmon_datum_long(_name, _sym, _label, _desc) -#define vmon_datum_longlong(_name, _sym, _label, _desc) - -#define vmon_omit_n(_n, _sym, _desc) -#define vmon_omit_literal(_lit, _sym) -#define vmon_omit_run(_char, _sym) -#define vmon_omit_str(_name, _sym, _label, _desc) -#define vmon_omit_str_array(_name, _sym, _label, _desc) -#define vmon_omit_char(_name, _sym, _label, _desc) -#define vmon_omit_char_array(_name, _sym, _label, _desc) -#define vmon_omit_int(_name, _sym, _label, _desc) -#define vmon_omit_uint(_name, _sym, _label, _desc) -#define vmon_omit_ulong(_name, _sym, _label, _desc) -#define vmon_omit_ulonglong(_name, _sym, _label, _desc) -#define vmon_omit_long(_name, _sym, _label, _desc) -#define vmon_omit_longlong(_name, _sym, _label, _desc) -#endif - - -/* implements the cases for a simple switch()-based bytestream parser */ -#ifdef VMON_IMPLEMENT_PARSER -/* TODO: error out if the following aren't defined, these are utilized by the parser FSM: - * VMON_PARSER_DELIM <-- what value to treat as a delimiter for string/char arrays (sort of like IFS in bash) - * TODO: there are a bunch of variables we assume are available and named a certain way here, - * it would be preferable to be able to define those externally and inform the x-macro of their - * names etc. - */ -#define vmon_datum_str(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ - switch(input) {\ - case VMON_PARSER_DELIM:\ - /* store accumulated string, reset tmp, and advance */\ - if(*store)->_name) {\ - if( strncmp((*store)->name, _array, var_array_len) ||\ - (*store)->name[var_array_len] != '\0') {\ - BITSET((*store)->changed, VMON_ ## _sym);\ - changes++;\ - }\ - free((*store)->name);\ - } else {\ - BITSET((*store)->changed, VMON_ ## _sym);\ - changes++;\ - }\ - (*store)->_name = strndup(var_array, var_array_len);\ - var_array_len = 0;\ - state++;\ - break;\ - default:\ - /* accumulate string */\ - var_array[var_array_len++] = input;\ - break;\ - }\ - break; - -#define vmon_datum_str_array(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ - /* TODO ? */ \ - break; - -#define vmon_datum_char(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ - if((*store)->_name != input) {\ - BITSET((*store)->changed, VMON_ ## _sym);\ - changes++;\ - (*store)->_name = input;\ - }\ - state++;\ - break; - -#define vmon_datum_char_array(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ - /* TODO */\ - /* TODO */\ - break; - -#define vmon_datum_int(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ - switch(input) {\ - case '-':\ - /* TODO: we don't verify the '-' is leading... */\ - var_isneg = 1;\ - break;\ - case '0' ... '9':\ - var_int *= 10;\ - var_int += input - '0';\ - break;\ - default:\ - if(var_isneg) {\ - var_int = -var_int;\ - var_isneg = 0;\ - }\ - if((*store)->_name != var_int) {\ - BITSET((*store)->changed, VMON_ ## _sym);\ - changes++;\ - (*store)->_name = var_int;\ - }\ - var_int = 0;\ - state++;\ - break;\ - }\ - if(state == VMON_PARSER_STATE_ ## _sym) {\ - /* we want to fall-through when the state advances */\ - break;\ - } - -#define vmon_datum_uint(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ - switch(input) {\ - case '0' ... '9':\ - var_uint *= 10;\ - var_uint += input - '0';\ - break;\ - default:\ - if((*store)->_name != var_uint) {\ - BITSET((*store)->changed, VMON_ ## _sym);\ - changes++;\ - (*store)->_name = var_uint;\ - }\ - var_uint = 0;\ - state++;\ - break;\ - }\ - if(state == VMON_PARSER_STATE_ ## _sym) {\ - /* we want to fall-through when the state advances */\ - break;\ - } - -#define vmon_datum_ulong(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ - switch(input) {\ - case '0' ... '9':\ - var_ulong *= 10;\ - var_ulong += input - '0';\ - break;\ - default:\ - if((*store)->_name != var_ulong) {\ - BITSET((*store)->changed, VMON_ ## _sym);\ - changes++;\ - (*store)->_name = var_ulong;\ - }\ - var_ulong = 0;\ - state++;\ - break;\ - }\ - if(state == VMON_PARSER_STATE_ ## _sym) {\ - /* we want to fall-through when the state advances */\ - break;\ - } - -#define vmon_datum_ulonglong(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ - switch(input) {\ - case '0' ... '9':\ - var_ulonglong *= 10;\ - var_ulonglong += input - '0';\ - break;\ - default:\ - if((*store)->_name != var_ulonglong) {\ - BITSET((*store)->changed, VMON_ ## _sym);\ - changes++;\ - (*store)->_name = var_ulonglong;\ - }\ - var_ulonglong = 0;\ - state++;\ - break;\ - }\ - if(state == VMON_PARSER_STATE_ ## _sym) {\ - /* we want to fall-through when the state advances */\ - break;\ - } - -#define vmon_datum_long(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ - switch(input) {\ - case '-':\ - /* TODO: we dont verify the '-' is leading... */\ - var_isneg = 1;\ - break;\ - case '0' ... '9':\ - var_long *= 10;\ - var_long += input - '0';\ - break;\ - default:\ - if(var_isneg) {\ - var_long = -var_long;\ - var_isneg = 0;\ - }\ - if((*store)->_name != var_long) {\ - BITSET((*store)->changed, VMON_ ## _sym);\ - changes++;\ - (*store)->_name = var_long;\ - }\ - var_long = 0;\ - state++;\ - break;\ - }\ - if(state == VMON_PARSER_STATE_ ## _sym) {\ - /* we want to fall-through when the state advances */\ - break;\ - } - -#define vmon_datum_longlong(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ - switch(input) {\ - case '-':\ - /* TODO: we dont verify the '-' is leading... */\ - var_isneg = 1;\ - break;\ - case '0' ... '9':\ - var_longlong *= 10;\ - var_longlong += input - '0';\ - break;\ - default:\ - if(var_isneg) {\ - var_longlong = -var_longlong;\ - var_isneg = 0;\ - }\ - if((*store)->_name != var_longlong) {\ - BITSET((*store)->changed, VMON_ ## _sym);\ - changes++;\ - (*store)->_name = var_longlong;\ - }\ - var_longlong = 0;\ - state++;\ - break;\ - }\ - if(state == VMON_PARSER_STATE_ ## _sym) {\ - /* we want to fall-through when the state advances */\ - break;\ - } - -/* parse but simply skip omitted fields, advance on the delimiter */ -#define vmon_omit_n(_n, _sym, _desc) case VMON_PARSER_STATE_ ## _sym:\ - var_int++;\ - if(var_int >= _n) {\ - var_int = 0;\ - state++;\ - }\ - break; - -#define vmon_omit_literal(_lit, _sym) case VMON_PARSER_STATE_ ## _sym:\ - /* TODO make this actually match the literal, for now we skip the length. */ \ - var_int++;\ - if(var_int >= (sizeof(_lit) - 1)) {\ - var_int = 0;\ - state++;\ - }\ - break; - -#define vmon_omit_run(_char, _sym) case VMON_PARSER_STATE_ ## _sym:\ - if(input != _char) {\ - state++;\ - /* XXX: we fall-through to the next case because this byte belongs to the next state */\ - } else {\ - break;\ - } - - -#define vmon_omit_str(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ - if(input == VMON_PARSER_DELIM) {\ - state++;\ - } else {\ - break;\ - } - -#define vmon_omit_str_array(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ - if(input == VMON_PARSER_DELIM) {\ - state++;\ - } else {\ - break;\ - } - -#define vmon_omit_char(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ - state++;\ - break; - -#define vmon_omit_char_array(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ - if(input == VMON_PARSER_DELIM) {\ - state++;\ - } else {\ - break;\ - } - -#define vmon_omit_int(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ - switch(input) {\ - case '0' ... '9':\ - case '-':\ - break;\ - default:\ - state++;\ - break;\ - }\ - if(state == VMON_PARSER_STATE_ ## _sym) {\ - /* we want to fall-through when the state advances */\ - break;\ - } - -#define vmon_omit_uint(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ - switch(input) {\ - case '0' ... '9':\ - break;\ - default:\ - state++;\ - break;\ - }\ - if(state == VMON_PARSER_STATE_ ## _sym) {\ - /* we want to fall-through when the state advances */\ - break;\ - } - -#define vmon_omit_ulong(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ - switch(input) {\ - case '0' ... '9':\ - break;\ - default:\ - state++;\ - break;\ - }\ - if(state == VMON_PARSER_STATE_ ## _sym) {\ - /* we want to fall-through when the state advances */\ - break;\ - } - -#define vmon_omit_ulonglong(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ - switch(input) {\ - case '0' ... '9':\ - break;\ - default:\ - state++;\ - break;\ - }\ - if(state == VMON_PARSER_STATE_ ## _sym) {\ - /* we want to fall-through when the state advances */\ - break;\ - } - -#define vmon_omit_long(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ - switch(input) {\ - case '0' ... '9':\ - case '-':\ - break;\ - default:\ - state++;\ - break;\ - }\ - if(state == VMON_PARSER_STATE_ ## _sym) {\ - /* we want to fall-through when the state advances */\ - break;\ - } - -#define vmon_omit_longlong(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ - switch(input) {\ - case '0' ... '9':\ - case '-':\ - break;\ - default:\ - state++;\ - break;\ - }\ - if(state == VMON_PARSER_STATE_ ## _sym) {\ - /* we want to fall-through when the state advances */\ - break;\ - } -#endif - - -/* for convenience, if the omit macros are undefind define them as noops, since that's the most common pattern */ -/* XXX TODO: we may need to add some mechanism for informing the VMON_SUPPRESS_UNDEFS clause in _end.def when these - * have been automatically defined vs. explicitly defined. When automatically defined, we should undefine them regarldess - * of undef suppression. But when they are explicitly defined prior to entering here, we should honor the undef suppression. - * I'm going to leave it as-is for now until it bites me in the ass. - */ -#ifndef vmon_omit_n -# define vmon_omit_n(_n, _sym, _desc) -#endif -#ifndef vmon_omit_literal -# define vmon_omit_literal(_lit, _sym) -#endif -#ifndef vmon_omit_run -# define vmon_omit_run(_char, _sym) -#endif -#ifndef vmon_omit_str -# define vmon_omit_str(_name, _sym, _label, _desc) -#endif -#ifndef vmon_omit_str_array -# define vmon_omit_str_array(_name, _sym, _label, _desc) -#endif -#ifndef vmon_omit_char -# define vmon_omit_char(_name, _sym, _label, _desc) -#endif -#ifndef vmon_omit_char_array -# define vmon_omit_char_array(_name, _sym, _label, _desc) -#endif -#ifndef vmon_omit_int -# define vmon_omit_int(_name, _sym, _label, _desc) -#endif -#ifndef vmon_omit_uint -# define vmon_omit_uint(_name, _sym, _label, _desc) -#endif -#ifndef vmon_omit_ulong -# define vmon_omit_ulong(_name, _sym, _label, _desc) -#endif -#ifndef vmon_omit_ulonglong -# define vmon_omit_ulonglong(_name, _sym, _label, _desc) -#endif -#ifndef vmon_omit_long -# define vmon_omit_long(_name, _sym, _label, _desc) -#endif -#ifndef vmon_omit_longlong -# define vmon_omit_longlong(_name, _sym, _label, _desc) -#endif diff --git a/libvmon/defs/_end.def b/libvmon/defs/_end.def deleted file mode 100644 index 9243349..0000000 --- a/libvmon/defs/_end.def +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef VMON_SUPPRESS_UNDEFS - -/* XXX TODO: we may need to detect and manage the automatic definition of the vmon_omit_* definitions */ - -#undef vmon_datum_str -#undef vmon_datum_str_array -#undef vmon_datum_char -#undef vmon_datum_char_array -#undef vmon_datum_int -#undef vmon_datum_uint -#undef vmon_datum_ulong -#undef vmon_datum_ulonglong -#undef vmon_datum_long -#undef vmon_datum_longlong -#undef vmon_omit_n -#undef vmon_omit_literal -#undef vmon_omit_run -#undef vmon_omit_str -#undef vmon_omit_str_array -#undef vmon_omit_char -#undef vmon_omit_char_array -#undef vmon_omit_int -#undef vmon_omit_uint -#undef vmon_omit_ulong -#undef vmon_omit_ulonglong -#undef vmon_omit_long -#undef vmon_omit_longlong -#undef VMON_DECLARE_MEMBERS -#undef VMON_DECLARE_CHANGEBITS -#undef VMON_ENUM_SYMBOLS -#undef VMON_ASSIGN_NAME_TABLE -#undef VMON_ASSIGN_DESC_TABLE -#undef VMON_ENUM_PARSER_STATES -#undef VMON_PREPARE_PARSER -#undef VMON_IMPLEMENT_PARSER -#undef VMON_PARSER_DELIM -#undef vmon_want - -#else - -#undef VMON_SUPPRESS_UNDEFS - -#endif diff --git a/libvmon/defs/proc_files.def b/libvmon/defs/proc_files.def deleted file mode 100644 index 6e3db98..0000000 --- a/libvmon/defs/proc_files.def +++ /dev/null @@ -1,8 +0,0 @@ -#include "_begin.def" - - /* member name, symbolic constant, human label, human description (think UI/help) */ - /* /proc/$pid/fd */ -vmon_datum_int( fdnum, FILES_FDNUM, "FdNum", "File descriptor number (historically 0-255)") -vmon_datum_char_array( object_path, FILES_OBJPATH, "ObjPath", "Object path this descriptor represents a handle for") - -#include "_end.def" diff --git a/libvmon/defs/proc_io.def b/libvmon/defs/proc_io.def deleted file mode 100644 index 0e1776d..0000000 --- a/libvmon/defs/proc_io.def +++ /dev/null @@ -1,33 +0,0 @@ -#include "_begin.def" - - /* member name, symbolic constant, human label, human description (think UI/help) */ - /* /proc/$pid/io */ -vmon_omit_literal("rchar: ", PROC_IO_RCHAR_LABEL) -vmon_datum_ulonglong( rchars, PROC_IO_RCHAR, "CharsRead", "Characters read (all)") -vmon_omit_literal("\n", PROC_IO_RCHAR_NL) - -vmon_omit_literal("wchar: ", PROC_IO_WCHAR_LABEL) -vmon_datum_ulonglong( wchars, PROC_IO_WCHAR, "CharsWritten", "Characters written (all)") -vmon_omit_literal("\n", PROC_IO_WCHAR_NL) - -vmon_omit_literal("syscr: ", PROC_IO_SYSCR_LABEL) -vmon_datum_ulonglong( syscr, PROC_IO_SYSCR, "SysReads", "Read system calls") -vmon_omit_literal("\n", PROC_IO_SYSCR_NL) - -vmon_omit_literal("syscw: ", PROC_IO_SYSCW_LABEL) -vmon_datum_ulonglong( syscw, PROC_IO_SYSCW, "SysWrites", "Write system calls") -vmon_omit_literal("\n", PROC_IO_SYSCW_NL) - -vmon_omit_literal("read_bytes: ", PROC_IO_READBYTES_LABEL) -vmon_datum_ulonglong( read_bytes, PROC_IO_READBYTES, "BytesReadIO", "Bytes read from storage") -vmon_omit_literal("\n", PROC_IO_READBYTES_NL) - -vmon_omit_literal("write_bytes: ", PROC_IO_WRITEBYTES_LABEL) -vmon_datum_ulonglong( write_bytes, PROC_IO_WRITEBYTES, "BytesWrittenIO", "Bytes written to storage") -vmon_omit_literal("\n", PROC_IO_WRITEBYTES_NL) - -vmon_omit_literal("cancelled_write_bytes: ", PROC_IO_CANCELLED_WRITEBYTES_LABEL) -vmon_datum_ulonglong( cancelled_write_bytes, PROC_IO_CANCELLED_WRITEBYTES, "CancelledWriteBytes", "Bytes written but canceled before reaching storage (truncate)") -vmon_omit_literal("\n", PROC_IO_CANCELLED_WRITEBYTES_NL) - -#include "_end.def" diff --git a/libvmon/defs/proc_stat.def b/libvmon/defs/proc_stat.def deleted file mode 100644 index db704e9..0000000 --- a/libvmon/defs/proc_stat.def +++ /dev/null @@ -1,105 +0,0 @@ -#include "_begin.def" - - /* member name, symbolic constant, human label, human description (think UI/help) */ - /* /proc/$pid/comm */ -vmon_datum_char_array( comm, PROC_STAT_COMM, "Cmd", "/proc/$pid/comm raw contents (with the \n substituted with \0)") - - /* /proc/$pid/cmdline */ -vmon_datum_char_array( cmdline, PROC_STAT_CMDLINE, "Cmdline", "/proc/$pid/cmdline raw contents") -vmon_datum_int( argc, PROC_STAT_ARGC, "Argc", "parsed cmdline count as if executed") -vmon_datum_str_array( argv, PROC_STAT_ARGV, "Argv", "parsed cmdline argv contents as if executed, pointers into cmdline") - - /* /proc/$pid/exe */ -vmon_datum_char_array( exe, PROC_STAT_EXE, "ExePath", "/proc/$pid/exe symlink target") - - /* /proc/$pid/wchan */ -vmon_datum_char_array( wchan, PROC_STAT_WCHAN, "WChan", "/proc/$pid/wchan raw contents (address resolved)") - - /* /proc/$pid/stat */ -vmon_datum_int( pid, PROC_STAT_PID, "PID", "the process id") -vmon_omit_n( (*store)->comm.len + 3, PROC_STAT_COMM_, "the filename of the executable, in parentheses, skipped") -vmon_datum_char( state, PROC_STAT_STATE, "State", "process state, one of \"RSDZTW\"") -vmon_omit_run( ' ', PROC_STAT_PPID_SP) -vmon_datum_longlong( ppid, PROC_STAT_PPID, "PPId", "parent pid") -vmon_omit_run( ' ', PROC_STAT_PGID_SP) -vmon_datum_longlong( pgrp, PROC_STAT_PGID, "PGId", "parent process group") -vmon_omit_run( ' ', PROC_STAT_SID_SP) -vmon_datum_longlong( sid, PROC_STAT_SID, "SessionId", "session id") -vmon_omit_run( ' ', PROC_STAT_TTY_NR_SP) -vmon_datum_longlong( tty_nr, PROC_STAT_TTY_NR, "Tty", "controlling terminal of the process") -vmon_omit_run( ' ', PROC_STAT_TPGID_SP) -vmon_datum_longlong( tpgid, PROC_STAT_TPGID, "CtrlPGid", "id of the foreground process group of the controlling terminal of the process") -vmon_omit_run( ' ', PROC_STAT_FLAGS_SP) -vmon_datum_ulonglong( flags, PROC_STAT_FLAGS, "Flags", "the kernel flags of the process (see PF_* in the non-uapi )") -vmon_omit_run( ' ', PROC_STAT_MINFLT_SP) -vmon_datum_ulonglong( minflt, PROC_STAT_MINFLT, "MnrFlts", "the number of minor faults (no hitting disk)") -vmon_omit_run( ' ', PROC_STAT_CMINFLT_SP) -vmon_datum_ulonglong( cminflt, PROC_STAT_CMINFLT, "ChldMnrFlts", "number of minor faults waited-for children have made") -vmon_omit_run( ' ', PROC_STAT_MAJFLT_SP) -vmon_datum_ulonglong( majflt, PROC_STAT_MAJFLT, "MjrFlts", "the number of major faults (hit disk)") -vmon_omit_run( ' ', PROC_STAT_CMAJFLT_SP) -vmon_datum_ulonglong( cmajflt, PROC_STAT_CMAJFLT, "ChldMjrFlts", "the number of major faults waited-for children have made") -vmon_omit_run( ' ', PROC_STAT_UTIME_SP) -vmon_datum_ulonglong( utime, PROC_STAT_UTIME, "UsrCPU", "amount of time this process has spent in user mode (ticks)") -vmon_omit_run( ' ', PROC_STAT_STIME_SP) -vmon_datum_ulonglong( stime, PROC_STAT_STIME, "SysCPU", "amount of time this process has spent in kernel mode (ticks)") -vmon_omit_run( ' ', PROC_STAT_CUTIME_SP) -vmon_datum_longlong( cutime, PROC_STAT_CUTIME, "ChldUsrCPU", "amount of time the waited-for children have spent in user mode (ticks)") -vmon_omit_run( ' ', PROC_STAT_CSTIME_SP) -vmon_datum_longlong( cstime, PROC_STAT_CSTIME, "ChldSysCPU", "amount of time the waited-for children have spent in kernel mode (ticks)") -vmon_omit_run( ' ', PROC_STAT_PRIORITY_SP) -vmon_datum_longlong( priority, PROC_STAT_PRIORITY, "Priority", "priority of the process") -vmon_omit_run( ' ', PROC_STAT_NICE_SP) -vmon_datum_longlong( nice, PROC_STAT_NICE, "Nice", "nice value") -vmon_omit_run( ' ', PROC_STAT_NUM_THREADS_SP) -vmon_datum_longlong( num_threads, PROC_STAT_NUM_THREADS, "NumThreads", "number of threads") -vmon_omit_run( ' ', PROC_STAT_ALARM_SP) -vmon_omit_ulonglong( itrealvalue, PROC_STAT_ALARM, "NextAlarm", "the time in jiffies before the next SIGALRM is sent (not maintained)") -vmon_omit_run( ' ', PROC_STAT_START_SP) -vmon_datum_ulonglong( start, PROC_STAT_START, "StartTime", "start time relative to system boot in jiffies") -vmon_omit_run( ' ', PROC_STAT_VSIZE_SP) -vmon_datum_ulonglong( vsize, PROC_STAT_VSIZE, "VirtSize", "virtual memory size (bytes)") -vmon_omit_run( ' ', PROC_STAT_RSS_SP) -vmon_datum_ulonglong( rss, PROC_STAT_RSS, "ResSize", "resident set size (bytes)") -vmon_omit_run( ' ', PROC_STAT_RSSLIM_SP) -vmon_datum_ulonglong( rsslim, PROC_STAT_RSSLIM, "ResSizeLimit", "resident set size ulimit") -vmon_omit_run( ' ', PROC_STAT_STARTCODE_SP) -vmon_omit_ulonglong( startcode, PROC_STAT_STARTCODE, "CodeStart", "address above which program text can run") -vmon_omit_run( ' ', PROC_STAT_ENDCODE_SP) -vmon_omit_ulonglong( endcode, PROC_STAT_ENDCODE, "CodeEnd", "address below which program text can run") -vmon_omit_run( ' ', PROC_STAT_STARTSTACK_SP) -vmon_omit_ulonglong( startstack, PROC_STAT_STARTSTACK, "StackStart", "address of the stack start") -vmon_omit_run( ' ', PROC_STAT_ESP_SP) -vmon_omit_ulonglong( kstkesp, PROC_STAT_ESP, "StackPtr", "current stack pointer") -vmon_omit_run( ' ', PROC_STAT_EIP_SP) -vmon_omit_ulonglong( kstkeip, PROC_STAT_EIP, "InstructnPtr", "current instruction pointer") -vmon_omit_run( ' ', PROC_STAT_SIGNAL_SP) -vmon_omit_ulonglong( signal, PROC_STAT_SIGNAL, "SigsPending", "bitmap of pending signals") -vmon_omit_run( ' ', PROC_STAT_SIGBLOCKED_SP) -vmon_omit_ulonglong( blocked, PROC_STAT_SIGBLOCKED, "SigsBlocked", "bitmap of blocked signals") -vmon_omit_run( ' ', PROC_STAT_SIGIGNORED_SP) -vmon_omit_ulonglong( ignored, PROC_STAT_SIGIGNORED, "SigsIgnored", "bitmap of ignored signals") -vmon_omit_run( ' ', PROC_STAT_SIGCAUGHT_SP) -vmon_omit_ulonglong( caught, PROC_STAT_SIGCAUGHT, "SigsCaught", "bitmap of caughtsignals") -vmon_omit_run( ' ', PROC_STAT_WCHAN_ADDR_SP) -vmon_datum_ulonglong( wchan_addr, PROC_STAT_WCHAN_ADDR, "WchanAddr", "address of the process' wchan") -vmon_omit_run( ' ', PROC_STAT_SWAPPED_SP) -vmon_omit_ulonglong( nswap, PROC_STAT_SWAPPED, "NumSwapped", "number of pages swapped (not maintained)") -vmon_omit_run( ' ', PROC_STAT_CSWAPPED_SP) -vmon_omit_ulonglong( cnswap, PROC_STAT_CSWAPPED, "ChldNumSwpd", "number of cumulative pages swapped for children (not maintained)") -vmon_omit_run( ' ', PROC_STAT_EXITSIGNAL_SP) -vmon_omit_longlong( exit_signal, PROC_STAT_EXITSIGNAL, "ExitSignal", "signal to be sent to parent when we die") -vmon_omit_run( ' ', PROC_STAT_PROCESSOR_SP) -vmon_datum_longlong( processor, PROC_STAT_PROCESSOR, "LastCPU", "CPU number last executed on") -vmon_omit_run( ' ', PROC_STAT_RT_PRIORITY_SP) -vmon_omit_ulonglong( rt_priority, PROC_STAT_RT_PRIORITY, "RTPriority", "realtime priority of the process") -vmon_omit_run( ' ', PROC_STAT_POLICY_SP) -vmon_omit_ulonglong( policy, PROC_STAT_POLICY, "SchedPolicy", "scheduling policy of the process") -vmon_omit_run( ' ', PROC_STAT_DELAY_BLKIO_SP) -vmon_datum_ulonglong( delay_blkio, PROC_STAT_DELAY_BLKIO, "BlkIODelays", "aggregated block IO delays, in ticks") -vmon_omit_run( ' ', PROC_STAT_GUEST_TIME_SP) -vmon_datum_ulonglong( guest_time, PROC_STAT_GUEST_TIME, "GuestTime", "time spent running a virtual cpu for a guest OS") -vmon_omit_run( ' ', PROC_STAT_CGUEST_TIME_SP) -vmon_datum_longlong( cguest_time, PROC_STAT_CGUEST_TIME, "ChldGuestTim", "time spent running a virtual cpu for a guest OS in (waited for?) children") - -#include "_end.def" diff --git a/libvmon/defs/proc_vm.def b/libvmon/defs/proc_vm.def deleted file mode 100644 index 9028272..0000000 --- a/libvmon/defs/proc_vm.def +++ /dev/null @@ -1,19 +0,0 @@ -#include "_begin.def" - - /* member name, symbolic constant, human label, human description (think UI/help) */ - /* /proc/$pid/statm */ -vmon_datum_ulonglong( size_pages, PROC_VM_SIZE_PAGES, "Size", "Size in pages") -vmon_omit_run( ' ', PROC_VM_RESIDENT_PAGES_SP) -vmon_datum_ulonglong( resident_pages, PROC_VM_RESIDENT_PAGES, "Resident", "Resident set size in pages") -vmon_omit_run( ' ', PROC_VM_SHARED_PAGES_SP) -vmon_datum_ulonglong( shared_pages, PROC_VM_SHARED_PAGES, "Shared", "Shared size in pages") -vmon_omit_run( ' ', PROC_VM_TEXT_PAGES_SP) -vmon_datum_ulonglong( text_pages, PROC_VM_TEXT_PAGES, "Text", "Text segment size in pages") -vmon_omit_run( ' ', PROC_VM_LIB_PAGES_SP) -vmon_omit_ulonglong( lib_pages, PROC_VM_LIB_PAGES, "Library", "Library segment size (skipped, unused in 2.6)") -vmon_omit_run( ' ', PROC_VM_DATA_PAGES_SP) -vmon_datum_ulonglong( data_pages, PROC_VM_DATA_PAGES, "Data", "Data segment size in pages") -vmon_omit_run( ' ', PROC_VM_DIRTY_PAGES_SP) -vmon_omit_ulonglong( dirty_pages, PROC_VM_DIRTY_PAGES, "Dirty", "Dirtied (skipped, unused in 2.6)") - -#include "_end.def" diff --git a/libvmon/defs/proc_wants.def b/libvmon/defs/proc_wants.def deleted file mode 100644 index 7f02602..0000000 --- a/libvmon/defs/proc_wants.def +++ /dev/null @@ -1,14 +0,0 @@ -#include "_begin.def" - -/* the available per-process wants, the order here matters, put wants which affect the sampling heirarchy first */ -/* otherwise they will change the heirarchy after samples have been collected, leaving newly introduced nodes with uninitialized sample stores after return from vmon_sample() */ - -/* sym, name, internal fulfilllment function */ -vmon_want(PROC_FOLLOW_CHILDREN, proc_follow_children, proc_follow_children) -vmon_want(PROC_FOLLOW_THREADS, proc_follow_threads, proc_follow_threads) -vmon_want(PROC_FILES, proc_files, proc_sample_files) -vmon_want(PROC_STAT, proc_stat, proc_sample_stat) -vmon_want(PROC_VM, proc_vm, proc_sample_vm) -vmon_want(PROC_IO, proc_io, proc_sample_io) - -#include "_end.def" diff --git a/libvmon/defs/sys_stat.def b/libvmon/defs/sys_stat.def deleted file mode 100644 index ef8b9a7..0000000 --- a/libvmon/defs/sys_stat.def +++ /dev/null @@ -1,114 +0,0 @@ -#include "_begin.def" - - /* member name, symbolic constant, human label, human description (think UI/help) */ - /* /proc/stat */ - -/* a cpu row, this is shown once for the total prefixed with "cpu ", then again for every cpu prefixed with "cpuN ", newlines terminate rows */ -vmon_omit_n( 5, SYS_STAT_CPU_PREFIX, "cpu line \"cpu \" prefix") -vmon_datum_ulonglong( user, SYS_STAT_CPU_USER, "UserTime", "Time spent in user mode (ticks)") -vmon_omit_run( ' ', SYS_STAT_CPU_NICE_SP) -vmon_datum_ulonglong( nice, SYS_STAT_CPU_NICE, "NiceTime", "Time spent in user mode with low priority (ticks)") -vmon_omit_run( ' ', SYS_STAT_CPU_SYS_SP) -vmon_datum_ulonglong( system, SYS_STAT_CPU_SYS, "SysTime", "Time spent in system mode (ticks)") -vmon_omit_run( ' ', SYS_STAT_CPU_IDLE_SP) -vmon_datum_ulonglong( idle, SYS_STAT_CPU_IDLE, "IdleTime", "Time spent in the idle task (ticks)") -vmon_omit_run( ' ', SYS_STAT_CPU_IOWAIT_SP) -vmon_datum_ulonglong( iowait, SYS_STAT_CPU_IOWAIT, "IOWaitTime", "Time spent runnable but waiting for IO (ticks)") -vmon_omit_run( ' ', SYS_STAT_CPU_IRQ_SP) -vmon_datum_ulonglong( irq, SYS_STAT_CPU_IRQ, "IRQTime", "Time spent in IRQ context (ticks)") -vmon_omit_run( ' ', SYS_STAT_CPU_SIRQ_SP) -vmon_datum_ulonglong( softirq, SYS_STAT_CPU_SIRQ, "SoftIRQTime", "Time spent in the softirq context (ticks)") -vmon_omit_run( ' ', SYS_STAT_CPU_STEAL_SP) -vmon_datum_ulonglong( steal, SYS_STAT_CPU_STEAL, "StealTime", "Time spent in a virtualized environment (ticks)") -vmon_omit_run( ' ', SYS_STAT_CPU_GUEST_SP) -vmon_datum_ulonglong( guest, SYS_STAT_CPU_GUEST, "GuestTime", "Time spent in a virtual cpu (ticks)") -vmon_omit_literal( "\n", SYS_STAT_CPU_NL) - - - - -#if 0 -/* here we want to embed a list of a cpus, the cpu entries need to be a composite type which needs */ - -/* TODO: the rest of /proc/stat, need to develop the macro language further to cleanly support the variable structures like N cpu rows etc... */ -vmon_heredef_list_begin( cpus, SYS_STAT_CPUS, "CPUs", "CPU time accounts for every cpu in the system") -/* we probably should somehow express which field is to be used as an index for addressing the array elements (and growing as needed) */ -vmon_omit_n( 5, SYS_STAT_PERCPU_PREFIX, "cpu line \"cpu \" prefix") -vmon_datum_ulonglong( user, SYS_STAT_PERCPU_USER, "UserTime", "Time spent in user mode (ticks)") -vmon_omit_run( ' ', SYS_STAT_PERCPU_NICE_SP) -vmon_datum_ulonglong( nice, SYS_STAT_PERCPU_NICE, "NiceTime", "Time spent in user mode with low priority (ticks)") -vmon_omit_run( ' ', SYS_STAT_PERCPU_SYS_SP) -vmon_datum_ulonglong( system, SYS_STAT_PERCPU_SYS, "SysTime", "Time spent in system mode (ticks)") -vmon_omit_run( ' ', SYS_STAT_PERCPU_IDLE_SP) -vmon_datum_ulonglong( idle, SYS_STAT_PERCPU_IDLE, "IdleTime", "Time spent in the idle task (ticks)") -vmon_omit_run( ' ', SYS_STAT_PERCPU_IOWAIT_SP) -vmon_datum_ulonglong( iowait, SYS_STAT_PERCPU_IOWAIT, "IOWaitTime", "Time spent runnable but waiting for IO (ticks)") -vmon_omit_run( ' ', SYS_STAT_PERCPU_IRQ_SP) -vmon_datum_ulonglong( irq, SYS_STAT_PERCPU_IRQ, "IRQTime", "Time spent in IRQ context (ticks)") -vmon_omit_run( ' ', SYS_STAT_PERCPU_SIRQ_SP) -vmon_datum_ulonglong( softirq, SYS_STAT_PERCPU_SIRQ, "SoftIRQTime", "Time spent in the softirq context (ticks)") -vmon_omit_run( ' ', SYS_STAT_PERCPU_STEAL_SP) -vmon_datum_ulonglong( steal, SYS_STAT_PERCPU_STEAL, "StealTime", "Time spent in a virtualized environment (ticks)") -vmon_omit_run( ' ', SYS_STAT_PERCPU_GUEST_SP) -vmon_datum_ulonglong( guest, SYS_STAT_PERCPU_GUEST, "GuestTime", "Time spent in a virtual cpu (ticks)") -vmon_omit_literal( "\n", SYS_STAT_PERCPU_NL) -vmon_heredef_list_end( cpus, SYS_STAT_CPUS) - -/* we make the interrupts array dynamic, which is kind of annoying, since in older/simple XT-PIC systems it could be simply an array of 16 elements, - and the calling code could have made assumptions about the layout. Taking this approach to accomodate modern systems also forces calling code to - be more indirect about accessing the members of this array, less assumptions can be made, such is life. I considered using a simple static array with - named directly-accessible members in the CONFIG_GENERIC_HARDIRQS case, but that would encourage creating programs dependent on that case which would - then not work unmodified on the newer (and more common, now) complicated irq routing case. :( - */ -vmon_omit_literal("intr", SYS_STAT_IRQS_PREFIX) -vmon_heredef_array_begin( irqs, SYS_STAT_IRQS, "IRQs", "Counters for all interrupts in the system") -vmon_omit_literal(" ", SYS_STAT_IRQS_SP) -vmon_datum_ulonglong( count, SYS_STAT_PERIRQ_COUNT) -vmon_heredef_array_end( irqs, SYS_STAT_IRQS) -vmon_omit_literal("\n", SYS_STAT_IRQS_NL) - -vmon_omit_literal("ctxt ", SYS_STAT_CTXT_SWITCHES_PREFIX) -vmon_datum_ulonglong( ctxt, SYS_STAT_CTXT_SWITCHES, "CXs", "Count of context switches since boot") -vmon_omit_literal("\n", SYS_STAT_CTXT_SWITCHES_NL) - -vmon_omit_literal("btime ", SYS_STAT_BOOTTIME_PREFIX) -vmon_datum_ulong( boot_time, SYS_STAT_BOOTTIME, "BootTime", "Number of seconds since epoch the system booted at") -vmon_omit_literal("\n", SYS_STAT_BOOTTIME_NL) - -vmon_omit_literal("processes ", SYS_STAT_FORKS_PREFIX) -vmon_datum_ulong( forks, SYS_STAT_FORKS, "Forks", "Number of forks since the system booted") -vmon_omit_literal("\n", SYS_STAT_FORKS_NL) - -vmon_omit_literal("procs_running ", SYS_STAT_NRUNNABLE_PREFIX) -vmon_datum_ulong( n_runnable, SYS_STAT_NRUNNABLE, "NumRunnable", "Number of processes currently runnable (may exceed number of cpus)") -vmon_omit_literal("\n", SYS_STAT_NRUNNABLE_NL) - -vmon_omit_literal("procs_blocked ", SYS_STAT_NBLOCKED_PREFIX) -vmon_datum_ulong( n_blocked, SYS_STAT_NBLOCKED, "NumBlocked", "Number of processes currently blocked") -vmon_omit_literal("\n", SYS_STAT_NBLOCKED_NL) - -vmon_omit_literal("softirq ", SYS_STAT_SIRQS_PREFIX) -vmon_datum_ulonglong( sirq_hi, SYS_STAT_SIRQ_HI, "HiSIRQ", "Number of high priority soft interrupts (HI_SOFTIRQ)") -vmon_omit_literal(" ", SYS_STAT_SIRQ_TIMER_SP) -vmon_datum_ulonglong( sirq_timer, SYS_STAT_SIRQ_TIMER, "TimerSIRQ", "Number of timer software interrupts (TIMER_SOFTIRQ)") -vmon_omit_literal(" ", SYS_STAT_SIRQ_NET_TX_SP) -vmon_datum_ulonglong( sirq_net_tx, SYS_STAT_SIRQ_NET_TX, "NetTxSIRQ", "Number of network transmit software interrupts (NET_TX_SOFTIRQ)") -vmon_omit_literal(" ", SYS_STAT_SIRQ_NET_RX_SP) -vmon_datum_ulonglong( sirq_net_rx, SYS_STAT_SIRQ_NET_RX, "NetRxSIRQ", "Number of network receive software interrupts (NET_RX_SOFTIRQ)") -vmon_omit_literal(" ", SYS_STAT_SIRQ_BLOCK_SP) -vmon_datum_ulonglong( sirq_block, SYS_STAT_SIRQ_BLOCK, "BlockSIRQ", "Number of block software interrupts (BLOCK_SOFTIRQ)") -vmon_omit_literal(" ", SYS_STAT_SIRQ_IOPOLL_SP) -vmon_datum_ulonglong( sirq_iopoll, SYS_STAT_SIRQ_IOPOLL, "IOPollSIRQ", "Number of block IO poll software interrupts (BLOCK_IOPOLL_SOFTIRQ)") -vmon_omit_literal(" ", SYS_STAT_SIRQ_TASKLET_SP) -vmon_datum_ulonglong( sirq_tasklet, SYS_STAT_SIRQ_TASKLET, "TaskletSIRQ", "Number of tasklet software interrupts (TASKLET SOFTIRQ)") -vmon_omit_literal(" ", SYS_STAT_SIRQ_HRTIMER_SP) -vmon_datum_ulonglong( sirq_hrtimer, SYS_STAT_SIRQ_HRTIMER, "HRTimerSIRQ", "Number of hrtimer software interrupts (HRTIMER_SOFTIRQ)") -vmon_omit_literal(" ", SYS_STAT_SIRQ_RCU_SP) -vmon_datum_ulonglong( sirq_rcu, SYS_STAT_SIRQ_RCU, "RCUSIRQ", "Number of RCU software interrupts (RCU_SOFTIRQ)") -vmon_omit_literal("\n", SYS_STAT_SIRQS_NL) - - -#endif - - -#include "_end.def" diff --git a/libvmon/defs/sys_vm.def b/libvmon/defs/sys_vm.def deleted file mode 100644 index 33b4d3f..0000000 --- a/libvmon/defs/sys_vm.def +++ /dev/null @@ -1,169 +0,0 @@ -#include "_begin.def" - - - /* member name, symbolic constant, human label, human description (think UI/help) */ - /* /proc/meminfo */ -vmon_omit_literal("MemTotal:", SYS_VM_TOTAL_KB_LABEL) -vmon_omit_run(' ', SYS_VM_TOTAL_KB_WHITESPACE) -vmon_datum_ulong( total_kb, SYS_VM_TOTAL_KB, "Total", "Total memory in system") -vmon_omit_literal(" kB\n", SYS_VM_TOTAL_KB_UNIT_NL) -vmon_omit_literal("MemFree:", SYS_VM_FREE_KB_LABEL) -vmon_omit_run(' ', SYS_VM_FREE_KB_WHITESPACE) -vmon_datum_ulong( free_kb, SYS_VM_FREE_KB, "Free", "Free memory in system") -vmon_omit_literal(" kB\n", SYS_VM_FREE_KB_UNIT_NL) -vmon_omit_literal("Buffers:", SYS_VM_BUFFERS_KB_LABEL) -vmon_omit_run(' ', SYS_VM_BUFFERS_KB_WHITESPACE) -vmon_datum_ulong( buffers_kb, SYS_VM_BUFFERS_KB, "Buffers", "Memory allocated to buffers") -vmon_omit_literal(" kB\n", SYS_VM_BUFFERS_KB_UNIT_NL) -vmon_omit_literal("Cached:", SYS_VM_CACHED_KB_LABEL) -vmon_omit_run(' ', SYS_VM_CACHED_KB_WHITESPACE) -vmon_datum_ulong( cached_kb, SYS_VM_CACHED_KB, "Cached", "Memory allocated to caches") -vmon_omit_literal(" kB\n", SYS_VM_CACHED_KB_UNIT_NL) -vmon_omit_literal("SwapCached:", SYS_VM_SWAPCACHED_KB_LABEL) -vmon_omit_run(' ', SYS_VM_SWAPCACHED_KB_WHITESPACE) -vmon_datum_ulong( swapcached_kb, SYS_VM_SWAPCACHED_KB, "SwapCached", "Memory allocated to swap caches") -vmon_omit_literal(" kB\n", SYS_VM_SWAPCACHED_KB_UNIT_NL) -vmon_omit_literal("Active:", SYS_VM_ACTIVE_KB_LABEL) -vmon_omit_run(' ', SYS_VM_ACTIVE_KB_WHITESPACE) -vmon_datum_ulong( active_kb, SYS_VM_ACTIVE_KB, "Active", "Active pages") -vmon_omit_literal(" kB\n", SYS_VM_ACTIVE_KB_UNIT_NL) -vmon_omit_literal("Inactive:", SYS_VM_INACTIVE_KB_LABEL) -vmon_omit_run(' ', SYS_VM_INACTIVE_KB_WHITESPACE) -vmon_datum_ulong( inactive_kb, SYS_VM_INACTIVE_KB, "Inactive", "Inactive pages") -vmon_omit_literal(" kB\n", SYS_VM_INACTIVE_KB_UNIT_NL) -vmon_omit_literal("Active(anon):", SYS_VM_ANON_ACTIVE_KB_LABEL) -vmon_omit_run(' ', SYS_VM_ANON_ACTIVE_KB_WHITESPACE) -vmon_datum_ulong( anon_active_kb, SYS_VM_ANON_ACTIVE_KB, "AnonActive", "Active anonymous pages") -vmon_omit_literal(" kB\n", SYS_VM_ANON_ACTIVE_KB_UNIT_NL) -vmon_omit_literal("Inactive(anon):", SYS_VM_ANON_INACTIVE_KB_LABEL) -vmon_omit_run(' ', SYS_VM_ANON_INACTIVE_KB_WHITESPACE) -vmon_datum_ulong( anon_inactive_kb, SYS_VM_ANON_INACTIVE_KB, "AnonInactive", "Inactive anonymous pages") -vmon_omit_literal(" kB\n", SYS_VM_ANON_INACTIVE_KB_UNIT_NL) -vmon_omit_literal("Active(file):", SYS_VM_FILE_ACTIVE_KB_LABEL) -vmon_omit_run(' ', SYS_VM_FILE_ACTIVE_KB_WHITESPACE) -vmon_datum_ulong( file_active_kb, SYS_VM_FILE_ACTIVE_KB, "FileActive", "Active file pages") -vmon_omit_literal(" kB\n", SYS_VM_FILE_ACTIVE_KB_UNIT_NL) -vmon_omit_literal("Inactive(file):", SYS_VM_FILE_INACTIVE_KB_LABEL) -vmon_omit_run(' ', SYS_VM_FILE_INACTIVE_KB_WHITESPACE) -vmon_datum_ulong( file_inactive_kb, SYS_VM_FILE_INACTIVE_KB, "FileInactive", "Inactive file pages") -vmon_omit_literal(" kB\n", SYS_VM_FILE_INACTIVE_KB_UNIT_NL) -vmon_omit_literal("Unevictable:", SYS_VM_UNEVICTABLE_KB_LABEL) -vmon_omit_run(' ', SYS_VM_UNEVICTABLE_KB_WHITESPACE) -vmon_datum_ulong( unevictable_kb, SYS_VM_UNEVICTABLE_KB, "Unevictable", "Unevictable pages") -vmon_omit_literal(" kB\n", SYS_VM_UNEVICTABLE_KB_UNIT_NL) -vmon_omit_literal("Mlocked:", SYS_VM_MLOCKED_KB_LABEL) -vmon_omit_run(' ', SYS_VM_MLOCKED_KB_WHITESPACE) -vmon_datum_ulong( mlocked_kb, SYS_VM_MLOCKED_KB, "Mlocked", "Locked pages") -vmon_omit_literal(" kB\n", SYS_VM_MLOCKED_KB_UNIT_NL) -vmon_omit_literal("SwapTotal:", SYS_VM_SWAP_TOTAL_KB_LABEL) -vmon_omit_run(' ', SYS_VM_SWAP_TOTAL_KB_WHITESPACE) -vmon_datum_ulong( swap_total_kb, SYS_VM_SWAP_TOTAL_KB, "SwapTotal", "Total swap") -vmon_omit_literal(" kB\n", SYS_VM_SWAP_TOTAL_KB_UNIT_NL) -vmon_omit_literal("SwapFree:", SYS_VM_SWAP_FREE_KB_LABEL) -vmon_omit_run(' ', SYS_VM_SWAP_FREE_KB_WHITESPACE) -vmon_datum_ulong( swap_free_kb, SYS_VM_SWAP_FREE_KB, "SwapFree", "Free swap") -vmon_omit_literal(" kB\n", SYS_VM_SWAP_FREE_KB_UNIT_NL) -vmon_omit_literal("Dirty:", SYS_VM_DIRTY_KB_LABEL) -vmon_omit_run(' ', SYS_VM_DIRTY_KB_WHITESPACE) -vmon_datum_ulong( dirty_kb, SYS_VM_DIRTY_KB, "Dirty", "Dirty pages") -vmon_omit_literal(" kB\n", SYS_VM_DIRTY_KB_UNIT_NL) -vmon_omit_literal("Writeback:", SYS_VM_WRITEBACK_KB_LABEL) -vmon_omit_run(' ', SYS_VM_WRITEBACK_KB_WHITESPACE) -vmon_datum_ulong( writeback_kb, SYS_VM_WRITEBACK_KB, "Writeback", "Dirtied pages in the process of being written back") -vmon_omit_literal(" kB\n", SYS_VM_WRITEBACK_KB_UNIT_NL) -vmon_omit_literal("AnonPages:", SYS_VM_ANONPAGES_KB_LABEL) -vmon_omit_run(' ', SYS_VM_ANONPAGES_KB_WHITESPACE) -vmon_datum_ulong( anonpages_kb, SYS_VM_ANONPAGES_KB, "AnonPages", "Anonymous pages") -vmon_omit_literal(" kB\n", SYS_VM_ANONPAGES_KB_UNIT_NL) -vmon_omit_literal("Mapped:", SYS_VM_MAPPED_KB_LABEL) -vmon_omit_run(' ', SYS_VM_MAPPED_KB_WHITESPACE) -vmon_datum_ulong( mapped_kb, SYS_VM_MAPPED_KB, "Mapped", "Mapped pages") -vmon_omit_literal(" kB\n", SYS_VM_MAPPED_KB_UNIT_NL) -vmon_omit_literal("Shmem:", SYS_VM_SHMEM_KB_LABEL) -vmon_omit_run(' ', SYS_VM_SHMEM_KB_WHITESPACE) -vmon_datum_ulong( shmem_kb, SYS_VM_SHMEM_KB, "Shmem", "SysV IPC shmem") -vmon_omit_literal(" kB\n", SYS_VM_SHMEM_KB_UNIT_NL) -vmon_omit_literal("Slab:", SYS_VM_SLAB_KB_LABEL) -vmon_omit_run(' ', SYS_VM_SLAB_KB_WHITESPACE) -vmon_datum_ulong( slab_kb, SYS_VM_SLAB_KB, "Slab", "Slab memory") -vmon_omit_literal(" kB\n", SYS_VM_SLAB_KB_UNIT_NL) -vmon_omit_literal("SReclaimable:", SYS_VM_SRECLAIMABLE_KB_LABEL) -vmon_omit_run(' ', SYS_VM_SRECLAIMABLE_KB_WHITESPACE) -vmon_datum_ulong( sreclaimable_kb, SYS_VM_SRECLAIMABLE_KB, "SReclaimable", "Slab (reclaimable) memory") -vmon_omit_literal(" kB\n", SYS_VM_SRECLAIMABLE_KB_UNIT_NL) -vmon_omit_literal("SUnreclaim:", SYS_VM_SUNRECLAIMABLE_KB_LABEL) -vmon_omit_run(' ', SYS_VM_SUNRECLAIMABLE_KB_WHITESPACE) -vmon_datum_ulong( sunreclaimable_kb, SYS_VM_SUNRECLAIMABLE_KB, "SUnreclaim", "Slab (unreclaimable) memory") -vmon_omit_literal(" kB\n", SYS_VM_SUNRECLAIMABLE_KB_UNIT_NL) -vmon_omit_literal("KernelStack:", SYS_VM_KERNELSTACK_KB_LABEL) -vmon_omit_run(' ', SYS_VM_KERNELSTACK_KB_WHITESPACE) -vmon_datum_ulong( kernelstack_kb, SYS_VM_KERNELSTACK_KB, "KernelStack", "Kernel stack") -vmon_omit_literal(" kB\n", SYS_VM_KERNELSTACK_KB_UNIT_NL) -vmon_omit_literal("PageTables:", SYS_VM_PAGETABLES_KB_LABEL) -vmon_omit_run(' ', SYS_VM_PAGETABLES_KB_WHITESPACE) -vmon_datum_ulong( pagetables_kb, SYS_VM_PAGETABLES_KB, "PageTables", "Page tables") -vmon_omit_literal(" kB\n", SYS_VM_PAGETABLES_KB_UNIT_NL) -vmon_omit_literal("NFS_Unstable:", SYS_VM_NFS_UNSTABLE_KB_LABEL) -vmon_omit_run(' ', SYS_VM_NFS_UNSTABLE_KB_WHITESPACE) -vmon_datum_ulong( nfs_unstable_kb, SYS_VM_NFS_UNSTABLE_KB, "NFS_Unstable", "NFS unstable") -vmon_omit_literal(" kB\n", SYS_VM_NFS_UNSTABLE_KB_UNIT_NL) -vmon_omit_literal("Bounce:", SYS_VM_BOUNCE_KB_LABEL) -vmon_omit_run(' ', SYS_VM_BOUNCE_KB_WHITESPACE) -vmon_datum_ulong( bounce_kb, SYS_VM_BOUNCE_KB, "Bounce", "Bounce") -vmon_omit_literal(" kB\n", SYS_VM_BOUNCE_KB_UNIT_NL) -vmon_omit_literal("WritebackTmp:", SYS_VM_WRITEBACKTMP_KB_LABEL) -vmon_omit_run(' ', SYS_VM_WRITEBACKTMP_KB_WHITESPACE) -vmon_datum_ulong( writebacktmp_kb, SYS_VM_WRITEBACKTMP_KB, "WritebackTmp", "Writeback temp") -vmon_omit_literal(" kB\n", SYS_VM_WRITEBACKTMP_KB_UNIT_NL) -vmon_omit_literal("CommitLimit:", SYS_VM_COMMITLIMIT_KB_LABEL) -vmon_omit_run(' ', SYS_VM_COMMITLIMIT_KB_WHITESPACE) -vmon_datum_ulong( commitlimit_kb, SYS_VM_COMMITLIMIT_KB, "CommitLimit", "Commit limit") -vmon_omit_literal(" kB\n", SYS_VM_COMMITLIMIT_KB_UNIT_NL) -vmon_omit_literal("Committed_AS:", SYS_VM_COMMITTED_AS_KB_LABEL) -vmon_omit_run(' ', SYS_VM_COMMITTED_AS_KB_WHITESPACE) -vmon_datum_ulong( commited_as_kb, SYS_VM_COMMITTED_AS_KB, "Commited_AS", "Commited address space? TODO ") -vmon_omit_literal(" kB\n", SYS_VM_COMMITTED_AS_KB_UNIT_NL) -vmon_omit_literal("VmallocTotal:", SYS_VM_VMALLOC_TOTAL_KB_LABEL) -vmon_omit_run(' ', SYS_VM_VMALLOC_KB_WHITESPACE) -vmon_datum_ulong( vmalloctotal_kb, SYS_VM_VMALLOC_TOTAL_KB, "VmallocTotal", "Vmalloc total") -vmon_omit_literal(" kB\n", SYS_VM_VMALLOC_TOTAL_KB_UNIT_NL) -vmon_omit_literal("VmallocUsed:", SYS_VM_VMALLOC_USED_KB_LABEL) -vmon_omit_run(' ', SYS_VM_VMALLOC_USED_KB_WHITESPACE) -vmon_datum_ulong( vmallocused_kb, SYS_VM_VMALLOC_USED_KB, "VmallocUsed", "Vmalloc used") -vmon_omit_literal(" kB\n", SYS_VM_VMALLOC_USED_KB_UNIT_NL) -vmon_omit_literal("VmallocChunk:", SYS_VM_VMALLOC_CHUNK_KB_LABEL) -vmon_omit_run(' ', SYS_VM_VMALLOC_CHUNK_KB_WHITESPACE) -vmon_datum_ulong( vmallocchunk_kb, SYS_VM_VMALLOC_CHUNK_KB, "VmallocChunk", "Vmalloc chunk") -vmon_omit_literal(" kB\n", SYS_VM_VMALLOC_CHUNK_KB_UNIT_NL) -vmon_omit_literal("HugePages_Total:", SYS_VM_HUGEPAGES_TOTAL_LABEL) -vmon_omit_run(' ', SYS_VM_HUGEPAGES_TOTAL_WHITESPACE) -vmon_datum_ulong( hugepages_total, SYS_VM_HUGEPAGES_TOTAL, "HugePages_Total", "HugePages total") -vmon_omit_literal("\n", SYS_VM_HUGEPAGES_TOTAL_NL) -vmon_omit_literal("HugePages_Free:", SYS_VM_HUGEPAGES_FREE_LABEL) -vmon_omit_run(' ', SYS_VM_HUGEPAGES_FREE_WHITESPACE) -vmon_datum_ulong( hugepages_free, SYS_VM_HUGEPAGES_FREE, "HugePages_Free", "HugePages free") -vmon_omit_literal("\n", SYS_VM_HUGEPAGES_FREE_NL) -vmon_omit_literal("HugePages_Rsvd:", SYS_VM_HUGEPAGES_RESERVED_LABEL) -vmon_omit_run(' ', SYS_VM_HUGEPAGES_RESERVED_WHITESPACE) -vmon_datum_ulong( hugepages_reserved, SYS_VM_HUGEPAGES_RESERVED, "HugePages_Rsvd", "HugePages reserved") -vmon_omit_literal("\n", SYS_VM_HUGEPAGES_RESERVED_UNIT_NL) -vmon_omit_literal("HugePages_Surp:", SYS_VM_HUGEPAGES_SURPLUS_LABEL) -vmon_omit_run(' ', SYS_VM_HUGEPAGES_SURPLUS_WHITESPACE) -vmon_datum_ulong( hugepages_surplus, SYS_VM_HUGEPAGES_SURPLUS, "HugePages_Surp", "HugePages surplus") -vmon_omit_literal("\n", SYS_VM_HUGEPAGES_SURPLUS_NL) -vmon_omit_literal("Hugepagesize:", SYS_VM_HUGEPAGE_SIZE_KB_LABEL) -vmon_omit_run(' ', SYS_VM_HUGEPAGE_SIZE_KB_WHITESPACE) -vmon_datum_ulong( hugepage_size_kb, SYS_VM_HUGEPAGE_SIZE_KB, "HugePage_Size", "HugePage page size") -vmon_omit_literal(" kB\n", SYS_VM_HUGEPAGE_SIZE_KB_UNIT_NL) -vmon_omit_literal("DirectMap4k:", SYS_VM_DIRECTMAP_4K_KB_LABEL) -vmon_omit_run(' ', SYS_VM_DIRECTMAP_4K_KB_WHITESPACE) -vmon_datum_ulong( directmap4k_kb, SYS_VM_DIRECTMAP_4K_KB, "DirectMap4k", "DirectMap 4K") -vmon_omit_literal(" kB\n", SYS_VM_DIRECTMAP_4K_KB_UNIT_NL) -vmon_omit_literal("DirectMap4M:", SYS_VM_DIRECTMAP_4M_KB_LABEL) -vmon_omit_run(' ', SYS_VM_DIRECTMAP_4M_KB_WHITESPACE) -vmon_datum_ulong( directmap2m_kb, SYS_VM_DIRECTMAP_4M_KB, "DirectMap4M", "DirectMap 4M") -vmon_omit_literal(" kB\n", SYS_VM_DIRECTMAP_4M_KB_UNIT_NL) - -/* TODO: /proc/vmstat */ - -#include "_end.def" diff --git a/libvmon/defs/sys_wants.def b/libvmon/defs/sys_wants.def deleted file mode 100644 index 750d7bb..0000000 --- a/libvmon/defs/sys_wants.def +++ /dev/null @@ -1,7 +0,0 @@ -#include "_begin.def" - -/* the available sys-wide wants */ -vmon_want(SYS_STAT, sys_stat, sys_sample_stat) -vmon_want(SYS_VM, sys_vm, sys_sample_vm) - -#include "_end.def" diff --git a/libvmon/vmon.c b/libvmon/vmon.c deleted file mode 100644 index 7d2b2a0..0000000 --- a/libvmon/vmon.c +++ /dev/null @@ -1,1634 +0,0 @@ -/* - * libvmon - a lightweight linux system/process monitoring library, - * intended for linking directly into gpl programs. - * - * This has been written specifically for use in vwm, my window manager, - * but includes some facilities for other uses. - * - * Copyright (c) 2012-2014 Vito Caputo - - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 3 as - * published by the Free Software Foundation. - * - * 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 . - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "list.h" - -#include "vmon.h" - -#define VMON_INTERNAL_PROC_IS_THREAD (1L << 31) /* used to communicate to vmon_proc_monitor() that the pid is a tid */ - -/* valid return values for the sampler functions, these are private to the library */ -typedef enum _sample_ret_t { - SAMPLE_CHANGED, /* this sampler invocation has changes */ - SAMPLE_UNCHANGED, /* this sampler invocation has no changes */ - SAMPLE_ERROR, /* this sampler invocation encountered errors (XXX it may be interesting to support indicating changing & errors) */ - DTOR_FREE, /* this dtor(sampler) invocation wants the caller to free the store */ - DTOR_NOFREE /* this dtor(sampler) invocation does not want the caller to perform a free on the store */ -} sample_ret_t; - - -/* some private convenience functions */ -static void try_free(void **ptr) -{ - if((*ptr)) { - free((*ptr)); - (*ptr) = NULL; - } -} - - -static void try_close(int *fd) -{ - if((*fd) != -1) { - close((*fd)); - (*fd) = -1; - } -} - - -static void try_closedir(DIR **dir) -{ - if((*dir)) { - closedir((*dir)); - (*dir) = NULL; - } -} - - -/* these have been wrapped to suppress syscall overhead when we have a bad file descriptor without cluttering the samplers with checks */ -static off_t try_lseek(int fd, off_t offset, int whence) -{ - if(fd != -1) { - return lseek(fd, offset, whence); - } else { - errno = EBADF; - return fd; - } -} - - -static ssize_t try_read(int fd, void *buf, size_t count) -{ - if(fd != -1) { - return read(fd, buf, count); - } else { - errno = EBADF; - return fd; - } -} - - -/* this does a copy from src to dest - * sets the bit specified by changed_pos in the bitmap *changed if what was copied to src was different from what was already there */ -static void memcmpcpy(void *dest, const void *src, size_t n, char *changed, int changed_pos) -{ - size_t i = 0; - - /* if the changed bit is set on entry we don't execute the comparison-copy */ - if(!BITTEST(changed, changed_pos)) { - /* a simple slow compare and copy loop, break out if we've found a change */ - /* XXX TODO: an obvious optimization would be to compare and copy words at a time... */ - for(; i < n; i++) { - if(((char *)dest)[i] != ((char *)src)[i]) { - BITSET(changed, changed_pos); - break; - } - ((char *)dest)[i] = ((char *)src)[i]; - } - } - - /* memcpy whatever remains */ - if(n - i) { - memcpy(&((char *)dest)[i], &((char *)src)[i], n - i); - } -} - - -typedef enum _vmon_load_flags_t { - LOAD_FLAGS_NONE = 0, - LOAD_FLAGS_NOTRUNCATE = 1L -} vmon_load_flags_t; - -/* we enlarge *alloc if necessary, but never shrink it. changed[changed_pos] bit is set if a difference is detected, supply LOAD_FLAGS_NOTRUNCATE if we don't want empty contents to truncate last-known data */ -static char * load_contents_fd(vmon_t *vmon, vmon_char_array_t *array, int fd, vmon_load_flags_t flags, char *changed, int changed_pos) -{ - int total = 0, len, alloc_len = array->alloc_len; - char *alloc = array->array, *tmp; - - while((len = read(fd, vmon->buf, sizeof(vmon->buf))) > 0) { - if(total + len > alloc_len) { - /* realloc to accomodate the new total */ - tmp = realloc(alloc, total + len); - if(!tmp) { - return NULL; - } - - alloc_len = total + len; - alloc = tmp; - } - - memcmpcpy(&alloc[total], vmon->buf, len, changed, changed_pos); - - total += len; - } - - array->array = alloc; - array->alloc_len = alloc_len; - - /* if we read something or didn't encounter an error, store the new total */ - if(total || (len == 0 && !(flags & LOAD_FLAGS_NOTRUNCATE))) { - /* if the new length differs ensure the changed bit is set */ - if(array->len != total) { - BITSET(changed, changed_pos); - } - - array->len = total; - } - - return alloc; -} - - -/* convenience function for opening a path using a format string, path is temporarily assembled in vmon->buf */ -static int openf(vmon_t *vmon, int flags, DIR *dir, char *fmt, ...) -{ - int fd; - va_list va_arg; - - va_start(va_arg, fmt); - vsnprintf(vmon->buf, sizeof(vmon->buf), fmt, va_arg); /* XXX accepting the possibility of truncating the path */ - va_end(va_arg); - - fd = openat(dirfd(dir), vmon->buf, flags); - - return fd; -} - - -/* convenience function for opening a directory using a format string, path is temporarily assembled in vmon->buf */ -static DIR * opendirf(vmon_t *vmon, DIR *dir, char *fmt, ...) -{ - int fd; - va_list va_arg; - - va_start(va_arg, fmt); - vsnprintf(vmon->buf, sizeof(vmon->buf), fmt, va_arg); /* XXX accepting the possibility of truncating the path */ - va_end(va_arg); - - fd = openat(dirfd(dir), vmon->buf, O_RDONLY); - if(fd == -1) { - return NULL; - } - - return fdopendir(fd); -} - - -/* enlarge an array by the specified amount */ -static int grow_array(vmon_char_array_t *array, int amount) -{ - char *tmp; - - tmp = realloc(array->array, array->alloc_len + amount); - if(!tmp) { - return 0; - } - - array->alloc_len += amount; - array->array = tmp; - - return 1; -} - - -/* load the contents of a symlink, dir is not optional */ -#define READLINKF_GROWINIT 10 -#define READLINKF_GROWBY 2 -static char * readlinkf(vmon_t *vmon, vmon_char_array_t *array, DIR *dir, char *fmt, ...) -{ - va_list va_arg; - int len; - - va_start(va_arg, fmt); - vsnprintf(vmon->buf, sizeof(vmon->buf), fmt, va_arg); - va_end(va_arg); - - if(!array->array && !grow_array(array, READLINKF_GROWINIT)) { - goto _fail; - } - - do { - len = readlinkat(dirfd(dir), vmon->buf, array->array, (array->alloc_len - 1)); - } while(len != -1 && len == (array->alloc_len - 1) && (len = grow_array(array, READLINKF_GROWBY))); - - if(len <= 0) { - goto _fail; - } - - array->len = len; - array->array[array->len] = '\0'; - - return array->array; - -_fail: - return NULL; -} - - -/* here starts private per-process samplers and other things like following children implementation etc. */ - -/* sample stat process stats */ -typedef enum _vmon_proc_stat_fsm_t { -#define VMON_ENUM_PARSER_STATES -#include "defs/proc_stat.def" -} vmon_proc_stat_fsm_t; - -static sample_ret_t proc_sample_stat(vmon_t *vmon, vmon_proc_t *proc, vmon_proc_stat_t **store) -{ - int changes = 0; - int i, len; - char *arg; - int argn, prev_argc; - vmon_proc_stat_fsm_t state = VMON_PARSER_STATE_PROC_STAT_PID; -#define VMON_PREPARE_PARSER -#include "defs/proc_stat.def" - - if(!proc) { /* dtor */ - try_close(&(*store)->comm_fd); - try_free((void **)&(*store)->comm); - try_close(&(*store)->cmdline_fd); - try_free((void **)&(*store)->cmdline); - try_close(&(*store)->wchan_fd); - try_close(&(*store)->stat_fd); - try_free((void **)&(*store)->exe); - - return DTOR_FREE; - } - -_retry: - if(!(*store)) { /* ctor */ - - *store = calloc(1, sizeof(vmon_proc_stat_t)); - - if(proc->is_thread) { - (*store)->comm_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/task/%i/comm", proc->pid, proc->pid); - (*store)->cmdline_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/task/%i/cmdline", proc->pid, proc->pid); - (*store)->wchan_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/task/%i/wchan", proc->pid, proc->pid); - (*store)->stat_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/task/%i/stat", proc->pid, proc->pid); - } else { - (*store)->comm_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/comm", proc->pid); - (*store)->cmdline_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/cmdline", proc->pid); - (*store)->wchan_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/wchan", proc->pid); - (*store)->stat_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/stat", proc->pid); - } - - /* initially everything is considered changed */ - memset((*store)->changed, 0xff, sizeof((*store)->changed)); - } else { - try_lseek((*store)->comm_fd, 0, SEEK_SET); - try_lseek((*store)->cmdline_fd, 0, SEEK_SET); - try_lseek((*store)->wchan_fd, 0, SEEK_SET); - try_lseek((*store)->stat_fd, 0, SEEK_SET); - - /* clear the entire changed bitmap */ - memset((*store)->changed, 0, sizeof((*store)->changed)); - } - - /* XXX TODO: integrate load_contents_fd() calls into changes++ maintenance */ - /* /proc/$pid/comm */ - load_contents_fd(vmon, &(*store)->comm, (*store)->comm_fd, LOAD_FLAGS_NOTRUNCATE, (*store)->changed, VMON_PROC_STAT_COMM); - - /* /proc/$pid/cmdline */ - load_contents_fd(vmon, &(*store)->cmdline, (*store)->cmdline_fd, LOAD_FLAGS_NOTRUNCATE, (*store)->changed, VMON_PROC_STAT_CMDLINE); - for(prev_argc = (*store)->argc, (*store)->argc = 0, i = 0; i < (*store)->cmdline.len; i++) { - if(!(*store)->cmdline.array[i]) { - (*store)->argc++; - } - } - - /* if the cmdline has changed, allocate argv array and store ptrs to the fields within it */ - if(BITTEST((*store)->changed, VMON_PROC_STAT_CMDLINE)) { - if(prev_argc != (*store)->argc) { - try_free((void **)&(*store)->argv); /* XXX could realloc */ - (*store)->argv = malloc((*store)->argc * sizeof(char *)); - } - - for(argn = 0, arg = (*store)->cmdline.array, i = 0; i < (*store)->cmdline.len; i++) { - if(!(*store)->cmdline.array[i]) { - (*store)->argv[argn++] = arg; - arg = &(*store)->cmdline.array[i + 1]; - } - } - } - - /* /proc/$pid/wchan */ - load_contents_fd(vmon, &(*store)->wchan, (*store)->wchan_fd, LOAD_FLAGS_NOTRUNCATE, (*store)->changed, VMON_PROC_STAT_WCHAN); - - /* /proc/$pid/exe */ - if((*store)->cmdline.len) { /* kernel threads have no cmdline, and always fail readlinkf() on exe, skip readlinking the exe for them using this heuristic */ - readlinkf(vmon, &(*store)->exe, vmon->proc_dir, "%i/exe", proc->pid); - } - - /* XXX TODO: there's a race between discovering comm_len from /proc/$pid/comm and applying it in the parsing of /proc/$pid/stat, detect the race - * scenario and retry the sample when detected by goto _retry */ - - /* read in stat and parse it assigning the stat members accordingly */ - while((len = try_read((*store)->stat_fd, vmon->buf, sizeof(vmon->buf))) > 0) { - for(i = 0; i < len; i++) { - /* parse the fields from the file, stepping through... */ - input = vmon->buf[i]; - switch(state) { -#define VMON_PARSER_DELIM ' ' /* TODO XXX eliminate the need for this, I want the .def's to include all the data format knowledge */ -#define VMON_IMPLEMENT_PARSER -#include "defs/proc_stat.def" - default: - /* we're finished parsing once we've fallen off the end of the symbols */ - break; - } - } - } - - return changes ? SAMPLE_CHANGED : SAMPLE_UNCHANGED; -} - - -/* implements the children following */ -static int proc_follow_children(vmon_t *vmon, vmon_proc_t *proc, vmon_proc_follow_children_t **store) -{ - int changes = 0; - int len, i, child_pid = 0, found; - vmon_proc_t *tmp, *_tmp; - list_head_t *cur, *start; - - if(!proc) { /* dtor */ - try_close(&(*store)->children_fd); - - return DTOR_FREE; - } - - if(proc->is_thread) { /* don't follow children of threads */ - return SAMPLE_UNCHANGED; - } - - if(!(*store)) { /* implicit ctor on first sample */ - *store = calloc(1, sizeof(vmon_proc_follow_children_t)); - - (*store)->children_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/task/%i/children", proc->pid, proc->pid); - } else { - try_lseek((*store)->children_fd, 0, SEEK_SET); - } - - /* unmonitor stale children on entry, this concludes the two-phase removal of a process */ - list_for_each_entry_safe(tmp, _tmp, &proc->children, siblings) { - if(tmp->is_stale) { - vmon_proc_unmonitor(vmon, tmp, NULL, NULL); - } -#ifdef _MOVE_STALE_TO_FRONT - else { - break; - } -#endif - } - - /* if we have a parent, and our parent has become stale, ensure this, the child, becomes stale as well */ - if(proc->parent && proc->parent->is_stale) { - proc->is_stale = 1; - proc->parent->children_changed = 1; - return SAMPLE_CHANGED; - } - - /* maintain our awareness of children, if we detect a new child initiate monitoring for it, existing children get their generation number updated */ - start = &proc->children; - while((len = try_read((*store)->children_fd, vmon->buf, sizeof(vmon->buf))) > 0) { - for(i = 0; i < len; i++) { - switch(vmon->buf[i]) { - case '0' ... '9': - /* PID component, accumulate it */ - child_pid *= 10; - child_pid += (vmon->buf[i] - '0'); - break; - - case ' ': - /* separator, terminates a PID, search for it in the childrens list */ - found = 0; - list_for_each(cur, start) { - if(list_entry(cur, vmon_proc_t, siblings)->pid == child_pid) { - /* found the child already monitored, update its generation number and stop searching */ - tmp = list_entry(cur, vmon_proc_t, siblings); - tmp->generation = vmon->generation; - found = 1; - tmp->is_new = 0; - break; - } - } - - if(found || (tmp = vmon_proc_monitor(vmon, proc, child_pid, proc->wants, NULL, NULL))) { - /* position the process in the siblings list, and update the start */ - /* move to front breaks vwm, we rely on the stale processes maintaining their position! maybe make it an option to vmon_init() since it can be a useful optimization. */ -#ifdef _MOVE_STALE_TO_FRONT - list_move_tail(&tmp->siblings, start); -#endif - start = &tmp->siblings; - } /* else { vmon_proc_monitor failed just move on } */ - - child_pid = 0; - break; - } - } - } - - /* look for children which seem to no longer exist (found by stale generation numbers) and queue them for unmonitoring, flag this as a children change too */ - found = 0; - list_for_each_entry(tmp, &proc->children, siblings) { - if(tmp->generation != vmon->generation) { - /* set children not found to stale status so the caller can respond and on our next sample invocation we will unmonitor them */ - found = tmp->is_stale = 1; - } -#ifdef _MOVE_STALE_TO_FRONT - /* this depends on the moving of stale entries to the start of the list optimization which breaks vwm, disabled for now */ - else { - break; - } -#endif - } - - /* XXX TODO: does it makes sense for shit to happen here? */ - if(found) { - if(proc->parent) { - proc->parent->children_changed = 1; - } else { - vmon->processes_changed = 1; - } - } - - return changes ? SAMPLE_CHANGED : SAMPLE_UNCHANGED; -} - - -/* implements the thread following */ -static int proc_follow_threads(vmon_t *vmon, vmon_proc_t *proc, vmon_proc_follow_threads_t **store) -{ - int changes = 0; - struct dirent dentry, *dentry_res; - list_head_t *cur, *start; - vmon_proc_t *tmp, *_tmp; - int found; - - if(!proc) { /* dtor */ - try_closedir(&(*store)->task_dir); - - return DTOR_FREE; - } - - if(proc->is_thread) { /* bypass following the threads of threads */ - return SAMPLE_UNCHANGED; - } - - if(!proc->stores || !proc->stores[VMON_STORE_PROC_STAT] || (((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->num_threads <= 1 && list_empty(&proc->threads))) { - /* bypass following of threads if we either can't determine the number from the proc stat sample or if the sample says there's 1 or less (and an empty threads list, handling stale exited threads) */ - /* XXX I'm not sure if this is always the right thing to do, there may be some situations where one could play games with clone() directly - * and escape the monitoring library with a lone thread having had the main thread exit, leaving the count at 1 while having a process - * descriptor distinguished from the single thread XXX */ - return SAMPLE_UNCHANGED; - } - - if(!(*store)) { /* implicit ctor on first sample */ - *store = calloc(1, sizeof(vmon_proc_follow_threads_t)); - - (*store)->task_dir = opendirf(vmon, vmon->proc_dir, "%i/task", proc->pid); - } else if((*store)->task_dir) { - seekdir((*store)->task_dir, 0); - } - - if(!(*store)->task_dir) { - return SAMPLE_ERROR; - } - - /* unmonitor stale threads on entry, this concludes the two-phase removal of a thread (just like follow_children) */ - list_for_each_entry_safe(tmp, _tmp, &proc->threads, threads) { - if(tmp->is_stale) { - vmon_proc_unmonitor(vmon, tmp, NULL, NULL); - } -#ifdef _MOVE_STALE_TO_FRONT - else { - break; - } -#endif - } - - start = &proc->threads; - while(!readdir_r((*store)->task_dir, &dentry, &dentry_res) && dentry_res) { - int tid; - - if(dentry.d_name[0] == '.' && (dentry.d_name[1] == '\0' || (dentry.d_name[1] == '.' && dentry.d_name[2] == '\0'))) { - /* skip . and .. */ - continue; - } - - tid = atoi(dentry.d_name); - - found = 0; - list_for_each(cur, start) { - if(cur == &proc->threads) { /* take care to skip the head node */ - continue; - } - - if(list_entry(cur, vmon_proc_t, threads)->pid == tid) { - /* found the thread already monitored, update its generation number and stop searching */ - tmp = list_entry(cur, vmon_proc_t, threads); - tmp->generation = vmon->generation; - found = 1; - tmp->is_new = 0; - break; - } - } - - if(found || (tmp = vmon_proc_monitor(vmon, proc, tid, (proc->wants | VMON_INTERNAL_PROC_IS_THREAD), NULL, NULL))) { - /* position the thread in the threads list, and update the start */ -#ifdef _MOVE_STALE_TO_FRONT - list_move_tail(&tmp->threads, start); -#endif - start = &tmp->threads; - } /* else { vmon_proc_monitor failed just move on } */ - } - - list_for_each_entry_safe(tmp, _tmp, &proc->threads, threads) { - if(tmp->generation != vmon->generation) { - /* set children not found to stale status so the caller can respond and on our next sample invocation we will unmonitor them */ - tmp->is_stale = 1; - } -#ifdef _MOVE_STALE_TO_FRONT - else { - break; - } -#endif - } - - return changes ? SAMPLE_CHANGED : SAMPLE_UNCHANGED; -} - - -/* helper for maintaining reference counted global objects table */ -static vmon_fobject_t * fobject_lookup_hinted(vmon_t *vmon, const char *path, vmon_fobject_t *hint) -{ - vmon_fobject_t *fobject = NULL, *tmp = NULL; - uint64_t inum; - - /* TODO maintain the fobject hash tables, they should probably be isolated/scoped based on the string before the : */ - /* in reality there needs to be a list somewhere of the valid prefixes we wish to support, and that list should associate - * the prefixes with the kind of contextual information details we monitor for each of those types. Then when new - * fobject types are added to libvmon, the rest of the code automatically reflects the additions due to the mechanization. - */ - if(!path || strncmp(path, "pipe:", 5)) { - return NULL; /* XXX TODO: for now we're only dealing with pipes */ - } - - sscanf(&path[6], "%" SCNu64 "]", &inum); - - if(hint && hint->inum == inum) { - /* the hint matches, skip the search */ - return hint; - } - - /* search for the inode, if we can't find it, allocate a new fobject XXX this needs optimizing but silly until we have all object types handled... */ - list_for_each_entry(tmp, &vmon->fobjects, bucket) { - if(tmp->inum == inum) { - fobject = tmp; - break; - } - } - - if(!fobject) { - /* create a new fobject */ - fobject = malloc(sizeof(vmon_fobject_t)); - - fobject->type = VMON_FOBJECT_TYPE_PIPE; - fobject->inum = inum; - INIT_LIST_HEAD(&fobject->ref_fds); - INIT_LIST_HEAD(&fobject->bucket); - fobject->refcnt = 0; - fobject->foo = NULL; - list_add_tail(&fobject->bucket, &vmon->fobjects); - vmon->fobjects_nr++; - - if(vmon->fobject_ctor_cb) { - vmon->fobject_ctor_cb(vmon, fobject); - } - } - - return fobject; -} - - -/* add a reference to an fobject, fd_ref is optional (should be present if the reference is due to an open fd, which may not be the case) */ -static void fobject_ref(vmon_t *vmon, vmon_fobject_t *fobject, vmon_proc_fd_t *fd_ref) -{ - fobject->refcnt++; - - if(fd_ref) { - list_add_tail(&fd_ref->ref_fds, &fobject->ref_fds); - } -} - - -/* fobject is required and is the object being unrefereced, fd_ref is optional but represents the per-process fd reference being used to access this fobject via */ -static int fobject_unref(vmon_t *vmon, vmon_fobject_t *fobject, vmon_proc_fd_t *fd_ref) -{ - if(fd_ref) { - list_del(&fd_ref->ref_fds); - } - - fobject->refcnt--; - - if(!fobject->refcnt) { - /* after the refcnt drops to zero we discard the fobject */ - list_del(&fobject->bucket); - vmon->fobjects_nr--; - - if(vmon->fobject_dtor_cb) { - vmon->fobject_dtor_cb(vmon, fobject); - } - - free(fobject); - return 1; - } - - return 0; -} - - -/* helper for deleting an fd from the per-process fds list list */ -static void del_fd(vmon_t *vmon, vmon_proc_fd_t *fd) -{ - list_del(&fd->fds); - if(fd->object) { - fobject_unref(vmon, fd->object, fd); /* note we supply both the fobject ptr and proc_fd ptr (fd) */ - } - try_free((void **)&fd->object_path); - free(fd); -} - - -/* implements the open file descriptors (/proc/$pid/fd/...) sampling */ -static sample_ret_t proc_sample_files(vmon_t *vmon, vmon_proc_t *proc, vmon_proc_files_t **store) -{ - int changes = 0; - struct dirent dentry, *dentry_res; - int fdnum; - list_head_t *cur, *start; - vmon_proc_fd_t *fd, *_fd; - vmon_fobject_t *cur_object = NULL; - - if(!proc) { - /* dtor implementation */ - if(--((*store)->refcnt)) { /* suppress dtor while references exist, the store is shared */ - return DTOR_NOFREE; - } - - try_closedir(&(*store)->fd_dir); - - list_for_each_entry_safe(fd, _fd, &(*store)->fds, fds) { - del_fd(vmon, fd); - } - - return DTOR_FREE; - } - - if(proc->is_thread) { - /* don't monitor the open files of threads, instead, share the files store of the parent process by adding a reference to it */ - /* XXX TODO: use kcmp CMP_FILES in the future instead of assuming all threads share open files */ - if(!(*store) && ((*store) = proc->parent->stores[VMON_STORE_PROC_FILES])) { - (*store)->refcnt++; - } - return SAMPLE_UNCHANGED; /* XXX TODO: we actually want to reflect/copy the activity state of the parent */ - } - - if(!(*store)) { /* implicit ctor on first sample */ - *store = calloc(1, sizeof(vmon_proc_files_t)); - - (*store)->refcnt = 1; - (*store)->fd_dir = opendirf(vmon, vmon->proc_dir, "%i/fd", proc->pid); - - INIT_LIST_HEAD(&(*store)->fds); - } else if((*store)->fd_dir) { - /* we have a directory handle, and we're reentering the function with the directory positioned at the end */ - seekdir((*store)->fd_dir, 0); - } - - if(!(*store)->fd_dir) { - /* we have no directory handle on reentry */ - /* XXX TODO: this happens when we don't have permission, this hsould be handled more elegantly/cleanly, and we don't - * make any attempt to ever reopen the directory because the ctor has already run. */ - goto _fail; - } - - start = &(*store)->fds; - while(!readdir_r((*store)->fd_dir, &dentry, &dentry_res) && dentry_res) { - if(dentry.d_name[0] == '.' && (dentry.d_name[1] == '\0' || (dentry.d_name[1] == '.' && dentry.d_name[2] == '\0'))) { - /* skip . and .. */ - continue; - } - - fdnum = atoi(dentry.d_name); - - /* search the process' files list for this fdnum */ - fd = NULL; - list_for_each(cur, start) { - if(cur == &(*store)->fds) { - continue; /* skip the head node as it's not boxed */ - } - if(list_entry(cur, vmon_proc_fd_t, fds)->fdnum == fdnum) { - fd = list_entry(cur, vmon_proc_fd_t, fds); - break; - } - } - - if(!fd) { - fd = calloc(1, sizeof(vmon_proc_fd_t)); - if(!fd) { - /* TODO: errors */ - goto _fail; - } - fd->fdnum = fdnum; - fd->process = proc; - INIT_LIST_HEAD(&fd->ref_fds); - list_add_tail(&fd->fds, start); - } else { - list_move_tail(&fd->fds, start); - } - - fd->generation = vmon->generation; - - /* Always readlink the fd path, since we have no way of knowing if it's a repurposed fdnum even when we've found a match. - * It would be nice if say.. the mtime of the /proc/$pid/fd directory changed if there's been any fd activity so we could skip the entire - * readdir+readlink loop in idle times, worth investigating. */ - readlinkf(vmon, &fd->object_path, vmon->proc_dir, "%i/fd/%s", proc->pid, dentry.d_name); - - cur_object = fd->object; /* stow the current object reference before we potentially replace it so we may unreference it if needed */ - fd->object = fobject_lookup_hinted(vmon, fd->object_path.array, cur_object); - if(cur_object != fd->object) { - if(cur_object) { - fobject_unref(vmon, cur_object, fd); - } - - if(fd->object) { - fobject_ref(vmon, fd->object, fd); - } - } /* else { lookup returned the same object as before (or NULL), is there anything to do? } */ - - start = &fd->fds; /* update the search start to this fd */ - } - - /* search for stale (closed) fds, remove references for any we find */ - list_for_each_entry_safe(fd, _fd, &(*store)->fds, fds) { - if(fd->generation != vmon->generation) { - del_fd(vmon, fd); - } else { - break; - } - } - - return changes ? SAMPLE_CHANGED : SAMPLE_UNCHANGED; - -_fail: - return SAMPLE_ERROR; -} - - -/* implements the vm utilization sampling */ -typedef enum _vmon_proc_vm_fsm_t { -#define VMON_ENUM_PARSER_STATES -#include "defs/proc_vm.def" -} vmon_proc_vm_fsm_t; - -static sample_ret_t proc_sample_vm(vmon_t *vmon, vmon_proc_t *proc, vmon_proc_vm_t **store) -{ - int i, len; - int changes = 0; - vmon_proc_vm_fsm_t state = VMON_PARSER_STATE_PROC_VM_SIZE_PAGES; -#define VMON_PREPARE_PARSER -#include "defs/proc_vm.def" - - if(!proc) { /* dtor */ - try_close(&(*store)->statm_fd); - - return DTOR_FREE; - } - - if(!(*store)) { /* ctor */ - (*store) = calloc(1, sizeof(vmon_proc_vm_t)); - if(proc->is_thread) { - (*store)->statm_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/task/%i/statm", proc->pid, proc->pid); - } else { - (*store)->statm_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/statm", proc->pid); - } - - /* initially everything is considered changed */ - memset((*store)->changed, 0xff, sizeof((*store)->changed)); - } else { - try_lseek((*store)->statm_fd, 0, SEEK_SET); - - /* clear the entire changed bitmap */ - memset((*store)->changed, 0, sizeof((*store)->changed)); - } - - /* read in statm and parse it assigning the vm members accordingly */ - while((len = try_read((*store)->statm_fd, vmon->buf, sizeof(vmon->buf))) > 0) { - for(i = 0; i < len; i++) { - /* parse the fields from the file, stepping through... */ - input = vmon->buf[i]; - switch(state) { -#define VMON_IMPLEMENT_PARSER -#include "defs/proc_vm.def" - default: - /* we're finished parsing once we've fallen off the end of the symbols */ - break; - } - } - } - - return changes ? SAMPLE_CHANGED : SAMPLE_UNCHANGED; -} - - -/* implements the io utilization sampling */ -typedef enum _vmon_proc_io_fsm_t { -#define VMON_ENUM_PARSER_STATES -#include "defs/proc_io.def" -} vmon_proc_io_fsm_t; - -static sample_ret_t proc_sample_io(vmon_t *vmon, vmon_proc_t *proc, vmon_proc_io_t **store) -{ - int i, len; - int changes = 0; - vmon_proc_io_fsm_t state = VMON_PARSER_STATE_PROC_IO_RCHAR_LABEL; -#define VMON_PREPARE_PARSER -#include "defs/proc_io.def" - - if(!proc) { /* dtor */ - try_close(&(*store)->io_fd); - - return DTOR_FREE; - } - - if(!(*store)) { /* ctor */ - (*store) = calloc(1, sizeof(vmon_proc_io_t)); - if(proc->is_thread) { - (*store)->io_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/task/%i/io", proc->pid, proc->pid); - } else { - (*store)->io_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/io", proc->pid); - } - - /* initially everything is considered changed */ - memset((*store)->changed, 0xff, sizeof((*store)->changed)); - } else { - try_lseek((*store)->io_fd, 0, SEEK_SET); - - /* clear the entire changed bitmap */ - memset((*store)->changed, 0, sizeof((*store)->changed)); - } - - /* read in io and parse it assigning the io members accordingly */ - while((len = try_read((*store)->io_fd, vmon->buf, sizeof(vmon->buf))) > 0) { - for(i = 0; i < len; i++) { - /* parse the fields from the file, stepping through... */ - input = vmon->buf[i]; - switch(state) { -#define VMON_IMPLEMENT_PARSER -#include "defs/proc_io.def" - default: - /* we're finished parsing once we've fallen off the end of the symbols */ - break; - } - } - } - - return changes ? SAMPLE_CHANGED : SAMPLE_UNCHANGED; -} - - -/* here starts the private system-wide samplers */ - -typedef enum _vmon_sys_stat_fsm_t { -#define VMON_ENUM_PARSER_STATES -#include "defs/sys_stat.def" -} vmon_sys_stat_fsm_t; - -/* system-wide stat sampling, things like CPU usages, stuff in /proc/stat */ -static sample_ret_t sys_sample_stat(vmon_t *vmon, vmon_sys_stat_t **store) -{ - int i, len; - int changes = 0; - vmon_sys_stat_fsm_t state = VMON_PARSER_STATE_SYS_STAT_CPU_PREFIX; /* this could be defined as the "VMON_PARSER_INITIAL_STATE" */ -#define VMON_PREPARE_PARSER -#include "defs/sys_stat.def" - - if(!vmon) { /* dtor */ - try_close(&(*store)->stat_fd); - return DTOR_FREE; - } - - if(!(*store)) { /* ctor */ - (*store) = calloc(1, sizeof(vmon_sys_stat_t)); - (*store)->stat_fd = openat(dirfd(vmon->proc_dir), "stat", O_RDONLY); - } else { - try_lseek((*store)->stat_fd, 0, SEEK_SET); - } - - while((len = try_read((*store)->stat_fd, vmon->buf, sizeof(vmon->buf))) > 0) { - for(i = 0; i < len; i++) { - input = vmon->buf[i]; - switch(state) { -#define VMON_PARSER_DELIM ' ' /* TODO XXX eliminate the need for this, I want the .def's to include all the data format knowledge */ -#define VMON_IMPLEMENT_PARSER -#include "defs/sys_stat.def" - default: - /* we're finished parsing once we've fallen off the end of the symbols */ - break; - } - } - } - - return changes ? SAMPLE_CHANGED : SAMPLE_UNCHANGED; -} - - -/* system-wide vm sampling, /proc/meminfo & /proc/vmstat */ -typedef enum _vmon_sys_vm_fsm_t { -#define VMON_ENUM_PARSER_STATES -#include "defs/sys_vm.def" -} vmon_sys_vm_fsm_t; - -static sample_ret_t sys_sample_vm(vmon_t *vmon, vmon_sys_vm_t **store) -{ - int i, len; - int changes = 0; - vmon_sys_vm_fsm_t state = VMON_PARSER_STATE_SYS_VM_TOTAL_KB_LABEL; /* this could be defined as the "VMON_PARSER_INITIAL_STATE" */ -#define VMON_PREPARE_PARSER -#include "defs/sys_vm.def" - - if(!vmon) { /* dtor */ - try_close(&(*store)->meminfo_fd); - return DTOR_FREE; - } - - if(!(*store)) { /* ctor */ - (*store) = calloc(1, sizeof(vmon_sys_vm_t)); - (*store)->meminfo_fd = openat(dirfd(vmon->proc_dir), "meminfo", O_RDONLY); - - /* initially everything is considered changed */ - memset((*store)->changed, 0xff, sizeof((*store)->changed)); - } else { - try_lseek((*store)->meminfo_fd, 0, SEEK_SET); - memset((*store)->changed, 0, sizeof((*store)->changed)); - } - - while((len = try_read((*store)->meminfo_fd, vmon->buf, sizeof(vmon->buf))) > 0) { - for(i = 0; i < len; i++) { - input = vmon->buf[i]; - switch(state) { -#define VMON_PARSER_DELIM ' ' /* TODO XXX eliminate the need for this, I want the .def's to include all the data format knowledge */ -#define VMON_IMPLEMENT_PARSER -#include "defs/sys_vm.def" - default: - /* we're finished parsing once we've fallen off the end of the symbols */ - break; - } - } - } - - return changes ? SAMPLE_CHANGED : SAMPLE_UNCHANGED; -} - - -/* here begins the public interface */ - -/* initialize a vmon instance, proc_wants is a default wants mask, optionally inherited vmon_proc_monitor() calls */ -int vmon_init(vmon_t *vmon, vmon_flags_t flags, vmon_sys_wants_t sys_wants, vmon_proc_wants_t proc_wants) -{ - int i; - - if((flags & VMON_FLAG_PROC_ALL) && (proc_wants & VMON_WANT_PROC_FOLLOW_CHILDREN)) { - return 0; - } - - if(!(vmon->proc_dir = opendir("/proc"))) { - return 0; - } - - INIT_LIST_HEAD(&vmon->processes); - INIT_LIST_HEAD(&vmon->orphans); - - for(i = 0; i < VMON_HTAB_SIZE; i++) { - INIT_LIST_HEAD(&vmon->htab[i]); - } - - memset(vmon->stores, 0, sizeof(vmon->stores)); - - /* TODO XXX: rename to something processes-specific! see vmon.h */ - vmon->array = NULL; - vmon->array_allocated_nr = vmon->array_active_nr = vmon->array_hint_free = 0; - - /* TODO XXX: this is temporary, see vmon.h */ - INIT_LIST_HEAD(&vmon->fobjects); - vmon->fobjects_nr = 0; - - vmon->flags = flags; - vmon->sys_wants = sys_wants; - vmon->proc_wants = proc_wants; - - /* here we populate the sys and proc function tables */ -#define vmon_want(_sym, _name, _func) \ - vmon->sys_funcs[VMON_STORE_ ## _sym] = (int(*)(vmon_t *, void **))_func; -#include "defs/sys_wants.def" - -#define vmon_want(_sym, _name, _func) \ - vmon->proc_funcs[VMON_STORE_ ## _sym] = (int(*)(vmon_t *, vmon_proc_t *, void **))_func; -#include "defs/proc_wants.def" - - vmon->sample_cb = NULL; - vmon->proc_ctor_cb = NULL; - vmon->proc_dtor_cb = NULL; - vmon->fobject_ctor_cb = NULL; - vmon->fobject_dtor_cb = NULL; - - return 1; -} - - -/* destroy vmon instance */ -void vmon_destroy(vmon_t *vmon) -{ - /* TODO: do we want to forcibly unmonitor everything being monitored still, or require the caller to have done that beforehand? */ - /* TODO: cleanup other shit, like closedir(vmon->proc_dir), etc */ -} - - -/* helper for searching for the process in the process array, specify NULL to find a free slot */ -static int find_proc_in_array(vmon_t *vmon, vmon_proc_t *proc, int hint) -{ - int ret = -1; - - if(hint >= 0 && hint < vmon->array_allocated_nr && vmon->array[hint] == proc) { - /* the hint was accurate, bypass the search */ - ret = hint; - } else { - int i; - - /* search for the entry in the array */ - for(i = 0; i < vmon->array_allocated_nr; i++) { - if(vmon->array[i] == proc) { - ret = i; - break; - } - } - } - - if(!proc && ret == -1) { - vmon_proc_t **tmp; - - /* enlarge the array */ - tmp = realloc(vmon->array, (vmon->array_allocated_nr + VMON_ARRAY_GROWBY) * sizeof(vmon_proc_t *)); - if(tmp) { - memset(&tmp[vmon->array_allocated_nr], 0, VMON_ARRAY_GROWBY * sizeof(vmon_proc_t *)); - ret = vmon->array_hint_free = vmon->array_allocated_nr; - vmon->array_allocated_nr += VMON_ARRAY_GROWBY; - vmon->array = tmp; - } /* XXX TODO: handle realloc failure */ - } - - return ret; -} - - -/* simple helper for installing callbacks on the callback lists, currently only used for the per-process sample callbacks */ -/* will not install the same callback function & arg combination more than once, and will not install NULL-functioned callbacks at all! */ -static int maybe_install_proc_callback(vmon_t *vmon, list_head_t *callbacks, void (*func)(vmon_t *, vmon_proc_t *, void *), void *arg) -{ - if(func) { - vmon_proc_callback_t *cb; - - list_for_each_entry(cb, callbacks, callbacks) { - if(cb->func == func && cb->arg == arg) { - break; - } - } - - if(&cb->callbacks == callbacks) { - cb = malloc(sizeof(vmon_proc_callback_t)); - if(!cb) { - return 0; - } - cb->func = func; - cb->arg = arg; - list_add_tail(&cb->callbacks, callbacks); - } - } - - return 1; -} - - -/* monitor a process under a given vmon instance, the public interface. - * XXX note it's impossible to say "none" for wants per-process, just "inherit", if vmon_init() was told a proc_wants of "inherit" then it's like having "none" - * proc_wants for all proceses, perhaps improve this if there's a pressure to support this use case */ -vmon_proc_t * vmon_proc_monitor(vmon_t *vmon, vmon_proc_t *parent, int pid, vmon_proc_wants_t wants, void (*sample_cb)(vmon_t *, vmon_proc_t *, void *), void *sample_cb_data) -{ - vmon_proc_t *proc; - int hash = (pid % VMON_HTAB_SIZE), i; - int is_thread = (wants & VMON_INTERNAL_PROC_IS_THREAD) ? 1 : 0; - - wants &= ~VMON_INTERNAL_PROC_IS_THREAD; - - if(pid < 0) return NULL; - - list_for_each_entry(proc, &vmon->htab[hash], bucket) { - /* search for the process to see if it's already monitored, we allow threads to exist with the same pid hence the additional is_thread comparison */ - if(proc->pid == pid && proc->is_thread == is_thread) { - if(!maybe_install_proc_callback(vmon, &proc->sample_callbacks, sample_cb, sample_cb_data)) { - return NULL; - } - - proc->wants = wants; /* we can alter wants this way, though it clearly needs more consideration XXX */ - proc->refcnt++; - /* This is a predicament. If the top-level (externally-established) process monitor wins the race, the process has no parent and is on the vmon->processes list. - * Then the follow_children-established monitor comes along and wants to assign a parent, this isn't such a big deal, and we should be able to permit it, however, - * we're in the process of iterating the top-level processes list when we run the follow_children() sampler of a descendant which happens to also be the parent. - * We can't simply remove the process from the top-level processes list mid-iteration and stick it on the children list of the parent, the iterator could wind up - * following the new pointer into the parents children. - * - * What I'm doing for now is allowing the assignment of a parent when there is no parent, but we don't perform the vmon->processes to parent->children migration - * until the top-level sample_siblings() function sees the node with the parent. At that point, the node will migrate to the parent's children list. - */ - if(parent && !proc->parent) { - /* if a parent was supplied, and there is no current parent, the process is a top-level currently by external callers, but now appears to be a child of something as well, - * so in this scenario, we'll remove it from the top-level siblings list, and make it a child of the new parent. I don't think there needs to be concern about its being a thread here. */ - /* Note we can't simply move the process from its current processes list and add it to the supplied parent's children list, as that would break the iterator above us at the top-level, so - * we must defer the migration until the processes iterator context can do it for us - but this is tricky because we're in the middle of traversing our heirarchy and this process may - * be in a critical is_new state which must be realized this sample at its location in the heirarchy for correctness, there will be no reappearance of that critical state in the correct - * tree position for users like vwm. */ - /* the VMON_FLAG_2PASS flag has been introduced for users like vwm */ - proc->parent = parent; - } /* else if(parent && proc->parent) { XXX TODO: it shouldn't be possible to have conflicting parents, but may want to log an error if it happens. */ - - return proc; - } - } - - proc = (vmon_proc_t *)malloc(sizeof(vmon_proc_t)); - if(proc == NULL) { - /* TODO: report an error */ - return NULL; - } - - proc->pid = pid; - proc->wants = wants; - proc->generation = vmon->generation; - proc->refcnt = 1; - proc->is_new = 1; /* newly created process */ - proc->is_stale = 0; /* implicitly not stale, since it is new */ - proc->is_thread = is_thread; - memset(proc->stores, 0, sizeof(proc->stores)); - proc->parent = parent; - INIT_LIST_HEAD(&proc->sample_callbacks); - INIT_LIST_HEAD(&proc->children); - INIT_LIST_HEAD(&proc->siblings); - INIT_LIST_HEAD(&proc->threads); - - if(!maybe_install_proc_callback(vmon, &proc->sample_callbacks, sample_cb, sample_cb_data)) { - free(proc); - return NULL; - } - - if(parent) { - /* if a parent is specified, attach this process to the parent's children or threads with its siblings */ - if(is_thread) { - list_add_tail(&proc->threads, &parent->threads); - parent->threads_changed = 1; - } else { - list_add_tail(&proc->siblings, &parent->children); - parent->children_changed = 1; - } - } else { - /* if no parent is specified, this is a toplevel process, attach it to the vmon->processes list with its siblings */ - /* XXX ignoring is_thread if no parent is specified, it shouldn't occur, unless I want to support external callers monitoring specific threads explicitly, maybe... */ - list_add_tail(&proc->siblings, &vmon->processes); - vmon->processes_changed = 1; - } - - /* add this process to the hash table */ - list_add_tail(&proc->bucket, &vmon->htab[hash]); - - /* if process table maintenance is enabled acquire a free slot for this process */ - if((vmon->flags & VMON_FLAG_PROC_ARRAY) && (i = find_proc_in_array(vmon, NULL, vmon->array_hint_free)) != -1) { - vmon->array[i] = proc; - - /* cache where we get inserted into the array */ - proc->array_hint_pos = i; - } - - /* invoke ctor callback if set, note it's only called when a new vmon_proc_t has been instantiated */ - if(vmon->proc_ctor_cb) { - vmon->proc_ctor_cb(vmon, proc); - } - - return proc; -} - - -/* stop monitoring a process under a given vmon instance, a caller who supplied a sample_cb & sample_cb_data pair @ monitor() must also supply it @ unmonitor! */ -void vmon_proc_unmonitor(vmon_t *vmon, vmon_proc_t *proc, void (*sample_cb)(vmon_t *, vmon_proc_t *, void *), void *sample_cb_data) -{ - vmon_proc_t *child, *_child; - int i; - - if(sample_cb) { /* uninstall callback */ - vmon_proc_callback_t *cb, *_cb; - - list_for_each_entry_safe(cb, _cb, &proc->sample_callbacks, callbacks) { - if(cb->func == sample_cb && cb->arg == sample_cb_data) { - list_del(&cb->callbacks); - free(cb); - break; - } - } - } - - if(--(proc->refcnt)) { /* if the process still has references, don't free it */ - return; - } - - /* recursively unmonitor any children processes being monitored */ - list_for_each_entry_safe(child, _child, &proc->children, siblings) { - if(child->parent == proc) { - child->parent = NULL; /* children we're currently a parent of, we're going bye bye, so make them orphans */ - list_add_tail(&child->siblings, &vmon->orphans); /* if the child becomes actually dtor'd in the nxt step it immediately will be discarded from the orphans list ... */ - } - vmon_proc_unmonitor(vmon, child, NULL, NULL); - } - - /* unmonitor all threads being monitored, suppressed if this process is a thread itself, as threads don't have children */ - if(!proc->is_thread) { - list_for_each_entry_safe(child, _child, &proc->threads, threads) { - vmon_proc_unmonitor(vmon, child, NULL, NULL); - } - } - - /* if maintaining a process array NULL out the entry */ - if((vmon->flags & VMON_FLAG_PROC_ARRAY) && (i = find_proc_in_array(vmon, proc, proc->array_hint_pos)) != -1) { - vmon->array[i] = NULL; - /* store its index if the current free hint isn't free, or it's lower than the current free hint, making the hint useful */ - if(vmon->array[vmon->array_hint_free] || i < vmon->array_hint_free) { - vmon->array_hint_free = i; - } - } - - list_del(&proc->siblings); - if(proc->is_thread) { - list_del(&proc->threads); - } - list_del(&proc->bucket); - - if(proc->parent) { /* XXX TODO: verify this works ok for unmonitored orphans */ - /* set the children changed flag in the parent */ - if(proc->is_thread) { - proc->parent->threads_changed = 1; - } else { - proc->parent->children_changed = 1; /* XXX TODO: for now I modify children_changed for both when the child dtor occurs and is_stale gets set */ - } - } else { - /* or the toplevel processes changed flag if parentless/toplevel */ - vmon->processes_changed = 1; - } - - for(i = 0; i < sizeof(vmon->proc_funcs) / sizeof(vmon->proc_funcs[VMON_STORE_PROC_STAT]); i++) { - if(proc->stores[i] != NULL) { /* any non-NULL stores must have a function installed and must have been sampled, invoke the dtor branch */ - if(vmon->proc_funcs[i](vmon, NULL, &proc->stores[i]) == DTOR_FREE) { - free(proc->stores[i]); - } - proc->stores[i] = NULL; - } - } - - /* invoke the dtor if set, note it only happens when the vmon_proc_t instance is about to be freed, not when it transitions to proc.is_stale=1 */ - if(vmon->proc_dtor_cb) { - vmon->proc_dtor_cb(vmon, proc); - } - - free(proc); -} - - -/* internal sampling helper, perform sampling for a given process */ -static void sample(vmon_t *vmon, vmon_proc_t *proc) -{ - int i, wants, cur; - - /* load this process monitors wants, or inherit the default */ - wants = proc->wants ? proc->wants : vmon->proc_wants; - - proc->activity = 0; - for(i = 0, cur = 1; wants; cur <<= 1, i++) { - if(wants & cur) { - if(vmon->proc_funcs[i](vmon, proc, &proc->stores[i]) == SAMPLE_CHANGED) { - proc->activity |= cur; - } - wants &= ~cur; - } - } -} - - -/* internal sampling helper, perform sampling for all sibling processes in the provided siblings list */ -static int sample_threads(vmon_t *vmon, list_head_t *threads) -{ - vmon_proc_t *proc; - - list_for_each_entry(proc, threads, threads) { - sample(vmon, proc); - -#if 0 - /* callbacks can't be installed currently on threads */ - vmon_proc_callback_t *cb; - - list_for_each_entry(cb, &proc->sample_callbacks, callbacks) { - cb->func(vmon, proc, cb->arg); - } -#endif - } - - return 1; -} - - -/* internal single-pass sampling helper, recursively perform sampling and callbacks for all sibling processes in the provided siblings list */ -static int sample_siblings(vmon_t *vmon, list_head_t *siblings) -{ - vmon_proc_t *proc, *_proc; - - list_for_each_entry_safe(proc, _proc, siblings, siblings) { - vmon_proc_callback_t *cb; - int entered_new = 0; - - /* prepare to transition top-level processes out of the is_new state, there's no sampler acting on behalf of top-level processes */ - if(proc->is_new) { - entered_new = 1; - } - - sample(vmon, proc); /* invoke samplers for this node */ - sample_threads(vmon, &proc->threads); /* invoke samplers for this node's threads */ - sample_siblings(vmon, &proc->children); /* invoke samplers for this node's children, and their callbacks, by recursing into this function */ - /* XXX TODO: error returns */ - - /* if this is the top-level processes list, and proc has found a parent through the above sampling, migrate it to the parent's children list */ - if(siblings == &vmon->processes && proc->parent) { - list_del(&proc->siblings); - list_add_tail(&proc->siblings, &proc->parent->children); - continue; - } - - /* XXX note that sample_callbacks are called only after all the descendants have had their sampling performed (and their potential callbacks invoked) - * this enables the installation of a callback at a specific node in the process heirarchy which can also perform duties on behalf of the children - * being monitored, handy when automatically following children, an immediately relevant use case (vwm) - */ - list_for_each_entry(cb, &proc->sample_callbacks, callbacks) { - cb->func(vmon, proc, cb->arg); - } - - /* transition new to non-new processes where we're responsible, this is a slight problem */ - if(!proc->parent && entered_new) { - proc->is_new = 0; - } - } - - /* if we've just finished the top-level processes, and we have some orphans, we want to make the orphans top-level processes and sample them as such */ - if(siblings == &vmon->processes && !list_empty(&vmon->orphans)) { - /* XXX TODO: do I need to get these orphans sampled immediately for this sample? Are they getting skipped this sample? - * TODO: instrument the samplers to see if generation is > 1 behind to detect drops... */ - list_splice_init(&vmon->orphans, vmon->processes.prev); - } - - return 1; -} - - -/* 2pass version of the internal heirarchical sampling helper */ -static int sample_siblings_pass1(vmon_t *vmon, list_head_t *siblings) -{ - vmon_proc_t *proc, *_proc; - - /* invoke samplers */ - list_for_each_entry_safe(proc, _proc, siblings, siblings) { - sample(vmon, proc); /* invoke samplers for this node */ - sample_threads(vmon, &proc->threads); /* invoke samplers for this node's threads */ - sample_siblings_pass1(vmon, &proc->children); /* invoke samplers for this node's children, by recursing into this function */ - /* XXX TODO: error returns */ - - /* if this is the top-level processes list, and proc has found a parent through the above sampling, migrate it to the parent's children list */ - /* XXX: clarification; a process may have been monitored explicitly by an external caller which then becomes monitored as the followed child of - * another process, here we detect that and move the process out of the top-level processes list and down to the children list it belongs to. */ - if(siblings == &vmon->processes) { - /* XXX: nobody maintains the generation numbers for the top-level processes, so it's done here... - * TODO: detect exited top-level processes and do something useful? */ - proc->generation = vmon->generation; - - if(proc->parent) { - list_del(&proc->siblings); - list_add_tail(&proc->siblings, &proc->parent->children); - } - } - } - - if(siblings == &vmon->processes && !list_empty(&vmon->orphans)) { - /* XXX TODO: do I need to get these orphans sampled immediately for this sample? Are they getting skipped this sample? - * TODO: instrument the samplers to see if generation is > 1 behind to detect drops and log as bugs... */ - list_splice_init(&vmon->orphans, vmon->processes.prev); - } - - return 1; -} - - -static int sample_siblings_pass2(vmon_t *vmon, list_head_t *siblings) -{ - vmon_proc_t *proc; - - /* invoke callbacks */ - list_for_each_entry(proc, siblings, siblings) { - vmon_proc_callback_t *cb; - - sample_siblings_pass2(vmon, &proc->children); /* recurse into children, we invoke callbacks as encountered on nodes from the leaves up */ - - list_for_each_entry(cb, &proc->sample_callbacks, callbacks) { - cb->func(vmon, proc, cb->arg); - } - - if(!proc->parent && proc->is_new) { /* top-level processes aren't managed by a follower/sampler, so we need to clear their is_new flag, this approach is slightly deviant from the managed case, - * as the managed case will actually allow the process to retain its is_new flag across a vmon_sample() cycle, where we're clearing it @ exit. It makes - * no difference to the callbacks, but if someone walks the tree after vmon_sample() relying on is_new, they'll be confused. XXX TODO FIXME - * May be able to leverage the generation number and turn the top-level sampler into more of a follower analog??? - */ - proc->is_new = 0; - } - } - - return 1; -} - - -/* collect information for all monitored processes, this is the interesting part, call it periodically at a regular interval */ -int vmon_sample(vmon_t *vmon) -{ - int i, wants, cur, ret = 1; - - vmon->generation++; - - /* first manage the "all processes monitored" use case, this doesn't do any sampling, it just maintains the top-level list of processes being monitored */ - /* note this doesn't cover threads, as linux doesn't expose threads in the readdir of /proc, even though you can directly look them up at /proc/$tid */ - if((vmon->flags & VMON_FLAG_PROC_ALL)) { - struct dirent dentry, *dentry_res; - list_head_t *tmp, *_tmp = &vmon->processes; - - /* if VMON_FLAG_PROC_ALL flag is set, quite a different code path is used which simply readdir()'s /proc, treating every numeric directory found - * as a process to monitor. The list of toplevel processes being monitored is kept in sync with these, automatically monitoring - * new processes found, and unmonitoring processes now absent, in a fashion very similar to the proc_sample_files() code. */ - seekdir(vmon->proc_dir, 0); - while(!readdir_r(vmon->proc_dir, &dentry, &dentry_res) && dentry_res) { - int pid, found; - - if(dentry.d_type != DT_DIR || dentry.d_name[0] < '0' || dentry.d_name[0] > '9') { - /* skip non-directories and non-numeric directories */ - continue; - } - - pid = atoi(dentry.d_name); - - found = 0; - list_for_each(tmp, _tmp) { /* note how we use _tmp as the head for the processes iteration, resuming from the last process' node */ - if(tmp == &vmon->processes) { - continue; /* must take care to skip the processes list_head_t, as it's not a vmon_proc_t */ - } - - if(list_entry(tmp, vmon_proc_t, siblings)->pid == pid) { - found = 1; - break; - } - } - - if(!found) { - /* monitor the process */ - vmon_proc_t *proc = vmon_proc_monitor(vmon, NULL, pid, vmon->proc_wants, NULL, NULL); - - if(!proc) { - /* TODO error */ - continue; - } - - tmp = &proc->siblings; - } - - list_move_tail(tmp, _tmp); /* place this process next to the current start (XXX there are cases where it's already there) */ - - list_entry(tmp, vmon_proc_t, siblings)->generation = vmon->generation; /* for identifying stale nodes */ - - _tmp = tmp; /* set this node as the head to start the next search from */ - } - - list_for_each_safe(tmp, _tmp, &vmon->processes) { /* XXX safe version needed since vmon_proc_unmonitor() deletes from the processes list */ - if(list_entry(tmp, vmon_proc_t, siblings)->generation != vmon->generation) { - vmon_proc_unmonitor(vmon, list_entry(tmp, vmon_proc_t, siblings), NULL, NULL); - } else { - /* we can stop looking for stale processes upon finding a non-stale one, since they've been sorted by the above algorithm */ - break; - } - } - } - - /* now for actual sampling */ - - /* first the sys-wide samplers */ - wants = vmon->sys_wants; /* the caller-requested sys-wide wants */ - vmon->activity = 0; - for(i = 0, cur = 1; wants; cur <<= 1, i++) { - if(wants & cur) { - if(vmon->sys_funcs[i](vmon, &vmon->stores[i]) == SAMPLE_CHANGED) { - vmon->activity |= cur; - } - wants &= ~cur; - } - } - - if(vmon->sample_cb) { - vmon->sample_cb(vmon); - } - - /* then the per-process samplers */ - if((vmon->flags & VMON_FLAG_PROC_ARRAY)) { - int j; - /* TODO: determine if this really makes sense, if we always maintain a heirarchy even in array mode, then we - * should probably always sample in the heirarchical order, or maybe make it caller-specified. - * There is a benefit to invoking the callbacks in heirarchical order, the callbacks can make assumptions about the children - * having the callbacks invoked prior to the current node, if done in depth-first order.... - * XXX this is a problem, figure out what to do with this, for now we don't even maintain the heirarchy in VMON_FLAG_PROC_ALL - * mode, only FOLLOW_CHILDREN mode, and it's likely PROC_ARRAY will generally be used together with PROC_ALL, so no heirarchy - * is available to traverse even if we wanted to. - */ - - /* flat process-array ordered sampling, in this mode threads and processes are all placed flatly in the array, - * so this does the sampling for all monitored in no particular order */ - for(j = 0; j < vmon->array_allocated_nr; j++) { - vmon_proc_t *proc; - - if((proc = vmon->array[j])) { - vmon_proc_callback_t *cb; - - sample(vmon, proc); - - list_for_each_entry(cb, &proc->sample_callbacks, callbacks) { - cb->func(vmon, proc, cb->arg); - } - - /* age process, we use the presence of a parent as a flag indicating if the process is managed ala follow children/threads - * XXX TODO: should probably change the public _monitor() api to not contain a parent param then */ - if(!proc->parent && proc->is_new) { - proc->is_new = 0; - } - } - } - } else if((vmon->flags & VMON_FLAG_2PASS)) { - /* recursive heirarchical depth-first processes tree sampling, at each node threads come before children, done in two passes: - * Pass 1. samplers - * Pass 2. callbacks - * XXX this is the path vwm utilizes, everything else is for other uses, like implementing top-like programs. - */ - ret = sample_siblings_pass1(vmon, &vmon->processes); /* XXX TODO: errors */ - ret = sample_siblings_pass2(vmon, &vmon->processes); - } else { - /* recursive heirarchical depth-first processes tree sampling, at each node threads come before children, done in a single pass: - * Pass 1. samplers; callbacks (for every node) - */ - ret = sample_siblings(vmon, &vmon->processes); - } - - return ret; -} diff --git a/libvmon/vmon.h b/libvmon/vmon.h deleted file mode 100644 index 06a062b..0000000 --- a/libvmon/vmon.h +++ /dev/null @@ -1,308 +0,0 @@ -#ifndef _VMON_H -#define _VMON_H - -#include -#include -#include -#include /* I use strcmp() in the type comparator definitions */ - -#include "bitmap.h" -#include "list.h" - -#define VMON_HTAB_SIZE 128 /* number of buckets in the processes hash table */ -#define VMON_ARRAY_GROWBY 5 /* number of elements to grow the processes array */ - -typedef enum _vmon_flags_t { - VMON_FLAG_NONE = 0, - VMON_FLAG_PROC_ARRAY = 1L, /* maintain a process array (useful if you need to do things like implement top(1) */ - VMON_FLAG_PROC_ALL = 1L << 1, /* monitor all the processes in the system (XXX this has some follow_children implications...) */ - VMON_FLAG_2PASS = 1L << 2, /* perform all sampling/wants in a first pass, then invoke all callbacks in second in vmon_sample(), important if your callbacks are layout-sensitive (vwm) */ -} vmon_flags_t; - -/* store ids, used as indices into the stores array, and shift offsets for the wants mask */ -typedef enum _vmon_sys_store_t { -#define vmon_want(_sym, _name, _func) VMON_STORE_ ## _sym, -#include "defs/sys_wants.def" - VMON_STORE_SYS_NR -} vmon_sys_store_t; - -typedef enum _vmon_sys_wants_t { - VMON_WANT_SYS_NONE = 0, -#define vmon_want(_sym, _name, _func) VMON_WANT_ ## _sym = 1L << VMON_STORE_ ## _sym, -#include "defs/sys_wants.def" -} vmon_sys_wants_t; - -typedef enum _vmon_proc_store_t { -#define vmon_want(_sym, _name, _func) VMON_STORE_ ## _sym, -#include "defs/proc_wants.def" - VMON_STORE_PROC_NR -} vmon_proc_store_t; - -typedef enum _vmon_proc_wants_t { - VMON_WANT_PROC_INHERIT = 0, -#define vmon_want(_sym, _name, _func) VMON_WANT_ ## _sym = 1L << VMON_STORE_ ## _sym, -#include "defs/proc_wants.def" - /* XXX: note proc_wants is internally overloaded in libvmon to communicate when a process is a thread-child of a process, so not all bits are available. */ -} vmon_proc_wants_t; - - -/* we add some new complex types */ -typedef struct _vmon_char_array_t { - char *array; - int len; - int alloc_len; -} vmon_char_array_t; - -typedef struct _vmon_str_array_t { - char **array; - int len; - int alloc_len; -} vmon_str_array_t; - - -/* system stat stuff (/proc/stat...) */ -typedef enum _vmon_sys_stat_sym_t { -#define VMON_ENUM_SYMBOLS -#include "defs/sys_stat.def" - VMON_SYS_STAT_NR /* append this symbol to the end so we have a count */ -} vmon_sys_stat_sym_t; - -typedef struct _vmon_sys_stat_t { - int stat_fd; - - char changed[BITNSLOTS(VMON_SYS_STAT_NR)]; /* bitmap for indicating changed fields */ - -#define VMON_DECLARE_MEMBERS -#include "defs/sys_stat.def" -} vmon_sys_stat_t; - - -/* system vm/mem stuff (/proc/meminfo, /proc/vmstat...) */ -typedef enum _vmon_sys_vm_sym_t { -#define VMON_ENUM_SYMBOLS -#include "defs/sys_vm.def" - VMON_SYS_VM_NR /* append this symbol to the end so we have a count */ -} vmon_sys_vm_sym_t; - -typedef struct _vmon_sys_vm_t { - int meminfo_fd; - - char changed[BITNSLOTS(VMON_SYS_VM_NR)]; /* bitmap for indicating changed fields */ - -#define VMON_DECLARE_MEMBERS -#include "defs/sys_vm.def" -} vmon_sys_vm_t; - - -/* stat things we always monitor for a process, regardless of the caller's wants */ -typedef enum _vmon_proc_stat_sym_t { -#define VMON_ENUM_SYMBOLS -#include "defs/proc_stat.def" - VMON_PROC_STAT_NR /* append this symbol to the end so we have a count */ -} vmon_proc_stat_sym_t; - -typedef struct _vmon_proc_stat_t { - int cmdline_fd, comm_fd, wchan_fd, stat_fd; /* per-process stat monitoring /proc/$pid/{wchan,stat} file handles */ - - char changed[BITNSLOTS(VMON_PROC_STAT_NR)]; /* bitmap for indicating changed fields */ - -#define VMON_DECLARE_MEMBERS -#include "defs/proc_stat.def" -} vmon_proc_stat_t; - - -/* vm-related per-process things we can monitor */ -typedef enum _vmon_proc_vm_sym_t { -#define VMON_ENUM_SYMBOLS -#include "defs/proc_vm.def" - VMON_PROC_VM_NR /* append this symbol to the end so we have a count */ -} vmon_proc_vm_sym_t; - -typedef struct _vmon_proc_vm_t { - int statm_fd; /* per-process vm monitoring /proc/$pid/statm file handle */ - - char changed[BITNSLOTS(VMON_PROC_VM_NR)]; /* bitmap for indicating changed fields */ - -#define VMON_DECLARE_MEMBERS -#include "defs/proc_vm.def" -} vmon_proc_vm_t; - - -/* io-related per-process things we can monitor */ -typedef enum _vmon_proc_io_sym_t { -#define VMON_ENUM_SYMBOLS -#include "defs/proc_io.def" - VMON_PROC_IO_NR /* append this symbol to the end so we have a count */ -} vmon_proc_io_sym_t; - -typedef struct _vmon_proc_io_t { - int io_fd; /* per-process io monitoring /proc/$pid/io file handle */ - - char changed[BITNSLOTS(VMON_PROC_IO_NR)]; /* bitmap for indicating changed fields */ - -#define VMON_DECLARE_MEMBERS -#include "defs/proc_io.def" -} vmon_proc_io_t; - - -/* follow children want context */ -typedef struct _vmon_proc_follow_children_t { - int children_fd; /* per-process children following /proc/$pid/task/$pid/children file handle */ -} vmon_proc_follow_children_t; - - -/* follow threads want context */ -typedef struct _vmon_proc_follow_threads_t { - DIR *task_dir; /* per-process threads monitoring /proc/$pid/task handle */ -} vmon_proc_follow_threads_t; - - -/* open files monitoring */ -typedef enum _vmon_proc_files_sym_t { -#define VMON_ENUM_SYMBOLS -#include "defs/proc_files.def" -} vmon_proc_files_sym_t; - -typedef enum _vmon_fobject_type_t { - VMON_FOBJECT_TYPE_UNRECOGNIZED = 0, - /* TODO, enumerate the possible opened fobject types, this should come out of a .def */ - VMON_FOBJECT_TYPE_PIPE, - VMON_FOBJECT_TYPE_SOCKET, - VMON_FOBJECT_TYPE_ANON, - VMON_FOBJECT_TYPE_NR -} vmon_fobject_type_t; - -typedef struct _vmon_fobject_t { - list_head_t bucket; /* fobjects hash table bucket this fobject belongs to */ - uint64_t inum; /* inode number */ - list_head_t ref_fds; /* referring fds list, this is a list of proc_fd_t's which appear to have this object open */ - int refcnt; /* reference count, this may be greater than the # of nodes in ref_fds, for instance the - monitoring of /proc/net/unix will maintain references to fobjects for every row, without - maintaing nodes on ref_fds. But there are certain fobjects which simply emerge due to - processes having them open (pipes) which are not explicitly monitored elsewhere, in those - cases the refcnt and number of nodes in ref_fds shall match. */ - vmon_fobject_type_t type; /* type for this fobject */ - - - /* TODO: possibly hook into the object-type-specific information here, if so, it should come out of .defs */ - /* XXX the question is do I want to introduce that resource allocation here as part of the fobject, or do I want - * it elsewhere and potentially optional? I think it makes sense to make it optional and triggered by asking for - * fobject detail monitoring, so instead of a union here we should have a pointer, and that pointer becomes useful - * when fobject-type monitors become active */ - void *foo; /* hook for caller's data, if needed (expected to be used together with fobject_[cd]tor_cb) */ -} vmon_fobject_t; - -typedef struct _vmon_proc_fd_t { - list_head_t fds; /* per-process files list node */ - int generation; /* generation number, for convenient detection of closed files */ - struct _vmon_proc_t *process; /* process this fd belongs to (annoying, but enables linking processes with fobject refs) */ - list_head_t ref_fds; /* ref_fds list node */ - vmon_fobject_t *object; /* the object instance this fd refers to (this object also contains the head for the refs list) */ - -#define VMON_DECLARE_MEMBERS -#include "defs/proc_files.def" -} vmon_proc_fd_t; - -typedef struct _vmon_proc_files_t { - int refcnt; /* reference count for dealing with sharing of open files (like threads...) */ - DIR *fd_dir; /* per-process files /proc/$pid/fd handle */ - list_head_t fds; /* per-process files linked list head */ -} vmon_proc_files_t; - - -/* TODO per-process VM stats monitoring */ - -struct _vmon_t; - - -/* list of callbacks is maintained for the per-process callbacks, it's convenient to do things like update multiple dynamic contexts associated with a given process monitor (think multiple windows) */ -typedef struct _vmon_proc_callback_t { - void (*func)(struct _vmon_t *, struct _vmon_proc_t *, void *); - void *arg; - list_head_t callbacks; -} vmon_proc_callback_t; - -typedef struct _vmon_proc_t { - list_head_t bucket; /* processes hash table bucket this process belongs to */ - - list_head_t children; /* head of the children of this process, empty when no children */ - list_head_t siblings; /* node in siblings list */ - list_head_t threads; /* head or node for the threads list, empty when process has no threads */ - - struct _vmon_proc_t *parent; /* reference to the parent */ - - int array_hint_pos; /* hint for the process's position in the array (when array maintenance has been requested) */ - - int pid; /* the PID of the process being monitored */ - - int generation; /* generation number, for convenient detection of exited processes */ - int refcnt; /* reference count on this node */ - vmon_proc_wants_t wants; /* wants @ this node */ - - vmon_proc_wants_t activity; /* bits updated when there's activity on the respective wants (stores have changes) */ - void *stores[VMON_STORE_PROC_NR]; /* pointers to the per-want per-monitored-process storage space */ - - /* callbacks invoked after sampling wants at and below this node */ - list_head_t sample_callbacks; /* list of callbacks to invoke sample_cb on behalf of (and supply as parameteres to) */ - void *foo; /* another per-process hook for whatever per-process uses the caller may have, but not managed by the api */ - - int children_changed:1; /* gets set when any of my immediate children have had is_new or is_stale set in the last sample */ - int threads_changed:1; /* gets set when any of my threads have had is_new or is_stale set in the last sample */ - int is_new:1; /* process is new in the most recent sample, automatically cleared on subsequent sample */ - int is_stale:1; /* process became stale in the most recent sample, automatically cleared on subsequent sample (process will be discarded) */ - int is_thread:1; /* process is a thread belonging to parent */ -} vmon_proc_t; - - -typedef struct _vmon_t { - DIR *proc_dir; /* /proc is opened @ vmon_init() */ - - /* TODO: rename this to something more contextually processes-specific */ - /* these array members are only relevant when array maintenance has been requested via VMON_FLAG_PROC_ARRAY @ vmon_init() */ - vmon_proc_t **array; /* array of processes being monitored (flat) */ - int array_allocated_nr; /* number of entries in the table */ - int array_active_nr; /* number of processes present in the table (including stale) */ - int array_hint_free; /* hint for a free element in the list */ - - list_head_t htab[VMON_HTAB_SIZE]; /* hash table for quickly finding processes being monitored */ - list_head_t processes; /* top of the processes heirarchy */ - list_head_t orphans; /* ephemeral list of processes orphaned this sample, orphans wind up becoming top-level processes */ - int processes_changed:1; /* flag set when the toplevel processes list changes */ - - list_head_t fobjects; /* XXX TODO: temporary single fobjects table, in the future this will be an array of type-indexed - * fobject hash tables */ - int fobjects_nr; /* XXX TODO: temporary simple counter of number of fobjects, this will change into something - * more like we have for the proceses array */ - vmon_flags_t flags; /* instance flags */ - vmon_sys_wants_t sys_wants; /* system-wide wants mask */ - vmon_proc_wants_t proc_wants; /* inherited per-process wants mask */ - - /* function tables for mapping of wants bits to functions (sys-wide and per-process) */ - int (*sys_funcs[VMON_STORE_SYS_NR])(struct _vmon_t *, void **); - int (*proc_funcs[VMON_STORE_PROC_NR])(struct _vmon_t *, vmon_proc_t *, void **); - - vmon_sys_wants_t activity; /* bits updated when there's activity on the respective wants (stores have changes) */ - void *stores[VMON_STORE_SYS_NR]; /* stores for the sys-wide wants */ - void (*sample_cb)(struct _vmon_t *); /* callback invoked after executing the selected sys wants (once per vmon_sample() call)) */ - - char buf[8192]; /* scratch buffer for private use XXX: it may make sense to dynamically size these... */ - char buf_bis[8192]; /* secondary scratch buffer for private use */ - int generation; /* generation counter for whatever might need it, increments with vmon_sample() calls */ - - /* callbacks we'll invoke in response to processes becoming instantiated and destroyed, when set */ - void (*proc_ctor_cb)(struct _vmon_t *, vmon_proc_t *); - void (*proc_dtor_cb)(struct _vmon_t *, vmon_proc_t *); - - /* callbacks we'll invoke in response to fobjects becoming instantiated and destroyed, when set */ - void (*fobject_ctor_cb)(struct _vmon_t *, vmon_fobject_t *); - void (*fobject_dtor_cb)(struct _vmon_t *, vmon_fobject_t *); -} vmon_t; - - -int vmon_init(vmon_t *, vmon_flags_t, vmon_sys_wants_t, vmon_proc_wants_t); -void vmon_destroy(vmon_t *); -vmon_proc_t * vmon_proc_monitor(vmon_t *, vmon_proc_t *, int, vmon_proc_wants_t, void (*)(vmon_t *, vmon_proc_t *, void *), void *); -void vmon_proc_unmonitor(vmon_t *, vmon_proc_t *, void (*)(vmon_t *, vmon_proc_t *, void *), void *); -int vmon_sample(vmon_t *); - -#endif diff --git a/list.h b/list.h deleted file mode 100644 index 48bca36..0000000 --- a/list.h +++ /dev/null @@ -1,252 +0,0 @@ -#ifndef __LIST_H -#define __LIST_H - -/* linux kernel linked list interface */ - -/* - * Simple doubly linked list implementation. - * - * Some of the internal functions ("__xxx") are useful when - * manipulating whole lists rather than single entries, as - * sometimes we already know the next/prev entries and we can - * generate better code by using them directly rather than - * using the generic single-entry routines. - */ - -typedef struct list_head { - struct list_head *next, *prev; -} list_head_t; - -#define LIST_HEAD_INIT(name) { &(name), &(name) } - -#define LIST_HEAD(name) \ - struct list_head name = LIST_HEAD_INIT(name) - -#define INIT_LIST_HEAD(ptr) do { \ - (ptr)->next = (ptr); (ptr)->prev = (ptr); \ -} while (0) - -/* - * Insert a new entry between two known consecutive entries. - * - * This is only for internal list manipulation where we know - * the prev/next entries already! - */ -static inline void __list_add(struct list_head *new, - struct list_head *prev, - struct list_head *next) -{ - next->prev = new; - new->next = next; - new->prev = prev; - prev->next = new; -} - -/** - * list_add - add a new entry - * @new: new entry to be added - * @head: list head to add it after - * - * Insert a new entry after the specified head. - * This is good for implementing stacks. - */ -static inline void list_add(struct list_head *new, struct list_head *head) -{ - __list_add(new, head, head->next); -} - -/** - * list_add_tail - add a new entry - * @new: new entry to be added - * @head: list head to add it before - * - * Insert a new entry before the specified head. - * This is useful for implementing queues. - */ -static inline void list_add_tail(struct list_head *new, struct list_head *head) -{ - __list_add(new, head->prev, head); -} - -/* - * Delete a list entry by making the prev/next entries - * point to each other. - * - * This is only for internal list manipulation where we know - * the prev/next entries already! - */ -static inline void __list_del(struct list_head *prev, struct list_head *next) -{ - next->prev = prev; - prev->next = next; -} - -/** - * list_del - deletes entry from list. - * @entry: the element to delete from the list. - * Note: list_empty on entry does not return true after this, the entry is in an undefined state. - */ -static inline void list_del(struct list_head *entry) -{ - __list_del(entry->prev, entry->next); - entry->next = (void *) 0; - entry->prev = (void *) 0; -} - -/** - * list_del_init - deletes entry from list and reinitialize it. - * @entry: the element to delete from the list. - */ -static inline void list_del_init(struct list_head *entry) -{ - __list_del(entry->prev, entry->next); - INIT_LIST_HEAD(entry); -} - -/** - * list_move - delete from one list and add as another's head - * @list: the entry to move - * @head: the head that will precede our entry - */ -static inline void list_move(struct list_head *list, struct list_head *head) -{ - __list_del(list->prev, list->next); - list_add(list, head); -} - -/** - * list_move_tail - delete from one list and add as another's tail - * @list: the entry to move - * @head: the head that will follow our entry - */ -static inline void list_move_tail(struct list_head *list, - struct list_head *head) -{ - __list_del(list->prev, list->next); - list_add_tail(list, head); -} - -/** - * list_empty - tests whether a list is empty - * @head: the list to test. - */ -static inline int list_empty(struct list_head *head) -{ - return head->next == head; -} - -static inline void __list_splice(struct list_head *list, - struct list_head *head) -{ - struct list_head *first = list->next; - struct list_head *last = list->prev; - struct list_head *at = head->next; - - first->prev = head; - head->next = first; - - last->next = at; - at->prev = last; -} - -/** - * list_splice - join two lists - * @list: the new list to add. - * @head: the place to add it in the first list. - */ -static inline void list_splice(struct list_head *list, struct list_head *head) -{ - if (!list_empty(list)) - __list_splice(list, head); -} - -/** - * list_splice_init - join two lists and reinitialise the emptied list. - * @list: the new list to add. - * @head: the place to add it in the first list. - * - * The list at @list is reinitialised - */ -static inline void list_splice_init(struct list_head *list, - struct list_head *head) -{ - if (!list_empty(list)) { - __list_splice(list, head); - INIT_LIST_HEAD(list); - } -} - -/** - * list_entry - get the struct for this entry - * @ptr: the &struct list_head pointer. - * @type: the type of the struct this is embedded in. - * @member: the name of the list_struct within the struct. - */ -#define list_entry(ptr, type, member) \ - ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member))) - -/** - * list_for_each - iterate over a list - * @pos: the &struct list_head to use as a loop counter. - * @head: the head for your list. - */ -#define list_for_each(pos, head) \ - for (pos = (head)->next; pos != (head); \ - pos = pos->next) -/** - * list_for_each_prev - iterate over a list backwards - * @pos: the &struct list_head to use as a loop counter. - * @head: the head for your list. - */ -#define list_for_each_prev(pos, head) \ - for (pos = (head)->prev; pos != (head); \ - pos = pos->prev) - -/** - * list_for_each_safe - iterate over a list safe against removal of list entry - * @pos: the &struct list_head to use as a loop counter. - * @n: another &struct list_head to use as temporary storage - * @head: the head for your list. - */ -#define list_for_each_safe(pos, n, head) \ - for (pos = (head)->next, n = pos->next; pos != (head); \ - pos = n, n = pos->next) - -/** - * list_for_each_entry - iterate over list of given type - * @pos: the type * to use as a loop counter. - * @head: the head for your list. - * @member: the name of the list_struct within the struct. - */ -#define list_for_each_entry(pos, head, member) \ - for (pos = list_entry((head)->next, typeof(*pos), member); \ - &pos->member != (head); \ - pos = list_entry(pos->member.next, typeof(*pos), member)) - -/** - * list_for_each_entry_prev - iterate over list of given type backwards - * @pos: the type * to use as a loop counter. - * @head: the head for your list. - * @member: the name of the list_struct within the struct. - */ -#define list_for_each_entry_prev(pos, head, member) \ - for (pos = list_entry((head)->prev, typeof(*pos), member); \ - &pos->member != (head); \ - pos = list_entry(pos->member.prev, typeof(*pos), member)) - - -/** - * list_for_each_entry_safe - iterate over list of given type safe against removal of list entry - * @pos: the type * to use as a loop counter. - * @n: another type * to use as temporary storage - * @head: the head for your list. - * @member: the name of the list_struct within the struct. - */ -#define list_for_each_entry_safe(pos, n, head, member) \ - for (pos = list_entry((head)->next, typeof(*pos), member), \ - n = list_entry(pos->member.next, typeof(*pos), member); \ - &pos->member != (head); \ - pos = n, n = list_entry(n->member.next, typeof(*n), member)) - - -#endif diff --git a/src/clickety.c b/src/clickety.c new file mode 100644 index 0000000..a64e6d7 --- /dev/null +++ b/src/clickety.c @@ -0,0 +1,244 @@ +/* + * \/\/\ + * + * Copyright (C) 2012-2016 Vito Caputo - + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3 as published + * by the Free Software Foundation. + * + * 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 . + */ + /* input event handling stuff */ + +#include + +#include "clickety.h" +#include "desktop.h" +#include "vwm.h" +#include "window.h" +#include "xwindow.h" + +/* simple little state machine for managing mouse click/drag/release sequences so we don't need another event loop */ +typedef enum _vwm_adjust_mode_t { + VWM_ADJUST_RESIZE, + VWM_ADJUST_MOVE +} vwm_adjust_mode_t; + +typedef struct _vwm_clickety_t { + vwm_window_t *vwin; + vwm_adjust_mode_t mode; + XWindowAttributes orig, lastrect; + int impetus_x, impetus_y, impetus_x_root, impetus_y_root; +} vwm_clickety_t; + +static vwm_clickety_t clickety; + +/* helper function for resizing the window, how the motion is applied depends on where in the window the impetus event occurred */ +static void compute_resize(XEvent *terminus, XWindowAttributes *new) +{ + vwm_window_t *vwin; + int dw = (clickety.orig.width / 2); + int dh = (clickety.orig.height / 2); + int xdelta = (terminus->xbutton.x_root - clickety.impetus_x_root); + int ydelta = (terminus->xbutton.y_root - clickety.impetus_y_root); + int min_width = 0, min_height = 0; + int width_inc = 1, height_inc = 1; + + /* TODO: there's a problem here WRT border width, I should be considering it, I just haven't bothered to fix it since it doesn't seem to matter */ + if ((vwin = clickety.vwin) && vwin->hints) { + if ((vwin->hints_supplied & PMinSize)) { + min_width = vwin->hints->min_width; + min_height = vwin->hints->min_height; + VWM_TRACE("window size hints exist and minimum sizes are w=%i h=%i", min_width, min_height); + } + + if ((vwin->hints_supplied & PResizeInc)) { + width_inc = vwin->hints->width_inc; + height_inc = vwin->hints->height_inc; + VWM_TRACE("window size hints exist and resize increments are w=%i h=%i", width_inc, height_inc); + if (!width_inc) width_inc = 1; + if (!height_inc) height_inc = 1; + } + } + + xdelta = xdelta / width_inc * width_inc; + ydelta = ydelta / height_inc * height_inc; + + if (clickety.impetus_x < dw && clickety.impetus_y < dh) { + /* grabbed top left */ + new->x = clickety.orig.x + xdelta; + new->y = clickety.orig.y + ydelta; + new->width = clickety.orig.width - xdelta; + new->height = clickety.orig.height - ydelta; + } else if (clickety.impetus_x > dw && clickety.impetus_y < dh) { + /* grabbed top right */ + new->x = clickety.orig.x; + new->y = clickety.orig.y + ydelta; + new->width = clickety.orig.width + xdelta; + new->height = clickety.orig.height - ydelta; + } else if (clickety.impetus_x < dw && clickety.impetus_y > dh) { + /* grabbed bottom left */ + new->x = clickety.orig.x + xdelta; + new->y = clickety.orig.y; + new->width = clickety.orig.width - xdelta; + new->height = clickety.orig.height + ydelta; + } else if (clickety.impetus_x > dw && clickety.impetus_y > dh) { + /* grabbed bottom right */ + new->x = clickety.orig.x; + new->y = clickety.orig.y; + new->width = clickety.orig.width + xdelta; + new->height = clickety.orig.height + ydelta; + } + + /* constrain the width and height of the window according to the minimums */ + if (new->width < min_width) { + if (clickety.orig.x != new->x) new->x -= (min_width - new->width); + new->width = min_width; + } + + if (new->height < min_height) { + if (clickety.orig.y != new->y) new->y -= (min_height - new->height); + new->height = min_height; + } +} + + +void vwm_clickety_motion(vwm_t *vwm, Window win, XMotionEvent *motion) +{ + XWindowChanges changes = { .border_width = WINDOW_BORDER_WIDTH }; + + if (!clickety.vwin) return; + + /* TODO: verify win matches clickety.vwin? */ + switch (clickety.mode) { + case VWM_ADJUST_MOVE: + changes.x = clickety.orig.x + (motion->x_root - clickety.impetus_x_root); + changes.y = clickety.orig.y + (motion->y_root - clickety.impetus_y_root); + XConfigureWindow(vwm->display, win, CWX | CWY | CWBorderWidth, &changes); + break; + + case VWM_ADJUST_RESIZE: { + XWindowAttributes resized; + + /* XXX: it just so happens the XMotionEvent structure is identical to XButtonEvent in the fields + * needed by compute_resize... */ + compute_resize((XEvent *)motion, &resized); + /* TODO: this is probably broken with compositing active, but it doesn't seem to be too messed up in practice */ + /* erase the last rectangle */ + XDrawRectangle(vwm->display, VWM_XROOT(vwm), vwm->gc, clickety.lastrect.x, clickety.lastrect.y, clickety.lastrect.width, clickety.lastrect.height); + /* draw a frame @ resized coordinates */ + XDrawRectangle(vwm->display, VWM_XROOT(vwm), vwm->gc, resized.x, resized.y, resized.width, resized.height); + /* remember the last rectangle */ + clickety.lastrect = resized; + break; + } + + default: + break; + } +} + + +void vwm_clickety_released(vwm_t *vwm, Window win, XButtonPressedEvent *terminus) +{ + XWindowChanges changes = { .border_width = WINDOW_BORDER_WIDTH }; + + if (!clickety.vwin) return; + + switch (clickety.mode) { + case VWM_ADJUST_MOVE: + changes.x = clickety.orig.x + (terminus->x_root - clickety.impetus_x_root); + changes.y = clickety.orig.y + (terminus->y_root - clickety.impetus_y_root); + XConfigureWindow(vwm->display, win, CWX | CWY | CWBorderWidth, &changes); + break; + + case VWM_ADJUST_RESIZE: { + XWindowAttributes resized; + compute_resize((XEvent *)terminus, &resized); + /* move and resize the window @ resized */ + XDrawRectangle(vwm->display, VWM_XROOT(vwm), vwm->gc, clickety.lastrect.x, clickety.lastrect.y, clickety.lastrect.width, clickety.lastrect.height); + changes.x = resized.x; + changes.y = resized.y; + changes.width = resized.width; + changes.height = resized.height; + XConfigureWindow(vwm->display, win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &changes); + XUngrabServer(vwm->display); + break; + } + + default: + break; + } + /* once you manipulate the window it's no longer fullscreened, simply hitting Mod1+Return once will restore fullscreened mode */ + clickety.vwin->autoconfigured = VWM_WIN_AUTOCONF_NONE; + + clickety.vwin = NULL; /* reset clickety */ + + XFlush(vwm->display); + XUngrabPointer(vwm->display, CurrentTime); +} + + +/* on pointer buttonpress we initiate a clickety sequence; setup clickety with the window and impetus coordinates.. */ +int vwm_clickety_pressed(vwm_t *vwm, Window win, XButtonPressedEvent *impetus) +{ + vwm_window_t *vwin; + + /* verify the window still exists */ + if (!XGetWindowAttributes(vwm->display, win, &clickety.orig)) goto _fail; + + if (!(vwin = vwm_win_lookup(vwm, win))) goto _fail; + + if (impetus->state & WM_GRAB_MODIFIER) { + + /* always set the input focus to the clicked window, note if we allow this to happen on the root window, it enters sloppy focus mode + * until a non-root window is clicked, which is an interesting hybrid but not how I prefer it. */ + if (vwin != vwm->focused_desktop->focused_window && vwin->xwindow->id != VWM_XROOT(vwm)) { + vwm_win_focus(vwm, vwin); + vwm_win_mru(vwm, vwin); + } + + switch (impetus->button) { + case Button1: + /* immediately raise the window if we're relocating, + * resizes are supported without raising (which also enables NULL resizes to focus without raising) */ + clickety.mode = VWM_ADJUST_MOVE; + XRaiseWindow(vwm->display, win); + break; + + case Button3: + /* grab the server on resize for the xor rubber-banding's sake */ + XGrabServer(vwm->display); + XSync(vwm->display, False); + + /* FIXME: none of the resize DrawRectangle() calls consider the window border. */ + XDrawRectangle(vwm->display, VWM_XROOT(vwm), vwm->gc, clickety.orig.x, clickety.orig.y, clickety.orig.width, clickety.orig.height); + clickety.lastrect = clickety.orig; + + clickety.mode = VWM_ADJUST_RESIZE; + break; + + default: + goto _fail; + } + clickety.vwin = vwin; + clickety.impetus_x_root = impetus->x_root; + clickety.impetus_y_root = impetus->y_root; + clickety.impetus_x = impetus->x; + clickety.impetus_y = impetus->y; + } + + return 1; + +_fail: + XUngrabPointer(vwm->display, CurrentTime); + + return 0; +} diff --git a/src/clickety.h b/src/clickety.h new file mode 100644 index 0000000..b2b51f1 --- /dev/null +++ b/src/clickety.h @@ -0,0 +1,12 @@ +#ifndef _CLICKETY_H +#define _CLICKETY_H + +#include + +#include "vwm.h" + +void vwm_clickety_motion(vwm_t *vwm, Window win, XMotionEvent *motion); +void vwm_clickety_released(vwm_t *vwm, Window win, XButtonPressedEvent *terminus); +int vwm_clickety_pressed(vwm_t *vwm, Window win, XButtonPressedEvent *impetus); + +#endif diff --git a/src/colors.def b/src/colors.def new file mode 100644 index 0000000..97c0dc9 --- /dev/null +++ b/src/colors.def @@ -0,0 +1,6 @@ +color(focused_window_border, "Green") +color(shelved_window_border, "purple") +color(unfocused_window_border, "DarkGray") +color(shelved_console_border, "red") +color(rubberband, "Orange") +color(logo, "LimeGreen") diff --git a/src/composite.c b/src/composite.c new file mode 100644 index 0000000..afa4add --- /dev/null +++ b/src/composite.c @@ -0,0 +1,331 @@ +/* + * \/\/\ + * + * Copyright (C) 2012-2016 Vito Caputo - + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3 as published + * by the Free Software Foundation. + * + * 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 . + */ + +/* The compositing code is heavily influenced by Keith Packard's xcompmgr. + */ + +#include +#include +#include +#include +#include + +#include "xwindow.h" +#include "vwm.h" + + /* compositing manager stuff */ +typedef enum _vwm_compositing_mode_t { + VWM_COMPOSITING_OFF = 0, /* non-composited, no redirected windows, most efficient */ + VWM_COMPOSITING_MONITORS = 1 /* composited process monitoring overlays, slower but really useful. */ +} vwm_compositing_mode_t; + +static vwm_compositing_mode_t compositing_mode = VWM_COMPOSITING_OFF; /* current compositing mode */ +static XserverRegion combined_damage = None; +static Picture root_picture = None, root_buffer = None; /* compositing gets double buffered */ +static XWindowAttributes root_attrs; +static XRenderPictureAttributes pa_inferiors = { .subwindow_mode = IncludeInferiors }; +static int repaint_needed; + +/* bind the window to a "namewindowpixmap" and create a picture from it (compositing) */ +static void bind_namewindow(vwm_t *vwm, vwm_xwindow_t *xwin) +{ + xwin->pixmap = XCompositeNameWindowPixmap(vwm->display, xwin->id); + xwin->picture = XRenderCreatePicture(vwm->display, xwin->pixmap, + XRenderFindVisualFormat(vwm->display, xwin->attrs.visual), + CPSubwindowMode, &pa_inferiors); + XFreePixmap(vwm->display, xwin->pixmap); +} + +/* free the window's picture for accessing its redirected contents (compositing) */ +static void unbind_namewindow(vwm_t *vwm, vwm_xwindow_t *xwin) +{ + XRenderFreePicture(vwm->display, xwin->picture); +} + +void vwm_composite_xwin_create(vwm_t *vwm, vwm_xwindow_t *xwin) +{ + if (!compositing_mode) return; + + bind_namewindow(vwm, xwin); + xwin->damage = XDamageCreate(vwm->display, xwin->id, XDamageReportNonEmpty); +} + +void vwm_composite_xwin_destroy(vwm_t *vwm, vwm_xwindow_t *xwin) +{ + if (!compositing_mode) return; + + unbind_namewindow(vwm, xwin); + XDamageDestroy(vwm->display, xwin->damage); +} + +/* add damage to the global combined damage queue where we accumulate damage between calls to paint_all() */ +void vwm_composite_damage_add(vwm_t *vwm, XserverRegion damage) +{ + if (combined_damage != None) { + XFixesUnionRegion(vwm->display, combined_damage, combined_damage, damage); + XFixesDestroyRegion(vwm->display, damage); + } else { + combined_damage = damage; + } +} + +/* helper to damage an entire window including the border */ +void vwm_composite_damage_win(vwm_t *vwm, vwm_xwindow_t *xwin) +{ + XserverRegion region; + XRectangle rect = { xwin->attrs.x, + xwin->attrs.y, + xwin->attrs.width + xwin->attrs.border_width * 2, + xwin->attrs.height + xwin->attrs.border_width * 2 }; + + if (!compositing_mode) return; + + region = XFixesCreateRegion(vwm->display, &rect, 1); + vwm_composite_damage_add(vwm, region); +} + + +void vwm_composite_handle_configure(vwm_t *vwm, vwm_xwindow_t *xwin, XWindowAttributes *new_attrs) { + if (!compositing_mode) return; + + /* damage the old and new window areas */ + XserverRegion region; + XRectangle rects[2] = { { xwin->attrs.x, + xwin->attrs.y, + xwin->attrs.width + xwin->attrs.border_width * 2, + xwin->attrs.height + xwin->attrs.border_width * 2 }, + { new_attrs->x, + new_attrs->y, + new_attrs->width + new_attrs->border_width * 2, + new_attrs->height + new_attrs->border_width * 2 } }; + + region = XFixesCreateRegion(vwm->display, rects, 2); + vwm_composite_damage_add(vwm, region); + unbind_namewindow(vwm, xwin); + bind_namewindow(vwm, xwin); +} + + +void vwm_composite_handle_map(vwm_t *vwm, vwm_xwindow_t *xwin) { + if (!compositing_mode) return; + + vwm_composite_damage_win(vwm, xwin); + unbind_namewindow(vwm, xwin); + bind_namewindow(vwm, xwin); +} + +/* take what regions of the damaged window have been damaged, subtract them from the per-window damage object, and add them to the combined damage */ +void vwm_composite_damage_event(vwm_t *vwm, XDamageNotifyEvent *ev) +{ + XserverRegion region; + vwm_xwindow_t *xwin; + + xwin = vwm_xwin_lookup(vwm, ev->drawable); + if (!xwin) { + VWM_ERROR("damaged unknown drawable %x", (unsigned int)ev->drawable); + return; + } + + region = XFixesCreateRegion(vwm->display, NULL, 0); + XDamageSubtract(vwm->display, xwin->damage, None, region); + XFixesTranslateRegion(vwm->display, region, xwin->attrs.x + xwin->attrs.border_width, xwin->attrs.y + xwin->attrs.border_width); + vwm_composite_damage_add(vwm, region); +} + + +/* throw away our double buffered root pictures so they get recreated on the next paint_all() */ +/* used in response to screen configuration changes... */ +void vwm_composite_invalidate_root(vwm_t *vwm) +{ + if (!compositing_mode) return; + + if (root_picture) XRenderFreePicture(vwm->display, root_picture); + root_picture = None; + if (root_buffer) XRenderFreePicture(vwm->display, root_picture); + root_buffer = None; +} + +void vwm_composite_repaint_needed(vwm_t *vwm) +{ + if (!compositing_mode) return; + + repaint_needed = 1; +} + +/* consume combined_damage by iterating the xwindows list from the top down, drawing visible windows as encountered, subtracting their area from combined_damage */ +/* when compositing is active this is the sole function responsible for making things show up on the screen */ +void vwm_composite_paint_all(vwm_t *vwm) +{ + vwm_xwindow_t *xwin; + XRenderColor bgcolor = {0x0000, 0x00, 0x00, 0xffff}; + Region occluded = XCreateRegion(); + static XserverRegion undamage_region = None; + + /* if there's no damage to repaint, short-circuit, this happens when compositing for overlays is disabled. */ + if (!compositing_mode || (combined_damage == None && !repaint_needed)) return; + + repaint_needed = 0; + + if (!undamage_region) undamage_region = XFixesCreateRegion(vwm->display, NULL, 0); + + /* (re)create the root picture from the root window and allocate a double buffer for the off-screen composition of the damaged contents */ + if (root_picture == None) { + Pixmap root_pixmap; + + XGetWindowAttributes(vwm->display, VWM_XROOT(vwm), &root_attrs); + root_picture = XRenderCreatePicture(vwm->display, VWM_XROOT(vwm), + XRenderFindVisualFormat(vwm->display, VWM_XVISUAL(vwm)), + CPSubwindowMode, &pa_inferiors); + root_pixmap = XCreatePixmap(vwm->display, VWM_XROOT(vwm), root_attrs.width, root_attrs.height, VWM_XDEPTH(vwm)); + root_buffer = XRenderCreatePicture(vwm->display, root_pixmap, XRenderFindVisualFormat(vwm->display, VWM_XVISUAL(vwm)), 0, 0); + XFreePixmap(vwm->display, root_pixmap); + } + + /* compose overlays for all visible windows up front in a separate pass (kind of lame, but it's simpler since compose_overlay() adds to combined_damage) */ + list_for_each_entry_prev(xwin, &vwm->xwindows, xwindows) { + XRectangle r; + + if (!vwm_xwin_is_mapped(vwm, xwin)) continue; /* if !mapped skip */ + + /* Everything mapped next goes through an occlusion check. + * Since the composite extension stops delivery of VisibilityNotify events for redirected windows, + * (it assumes redirected windows should be treated as part of a potentially transparent composite, and provides no api to alter this assumption) + * we can't simply select the VisibilityNotify events on all windows and cache their visibility state in vwm_xwindow_t then skip + * xwin->state==VisibilityFullyObscured windows here to avoid the cost of pointlessly composing overlays and rendering fully obscured windows :(. + * + * Instead we accumulate an occluded region (starting empty) of painted windows from the top-down on every paint_all(). + * Before we compose_overlay() a window, we check if the window's rectangle fits entirely within the occluded region. + * If it does, no compose_overlay() is performed. + * If it doesn't, compose_overlay() is called, and the window's rect is added to the occluded region. + * The occluded knowledge is also cached for the XRenderComposite() loop immediately following, where we skip the rendering of + * occluded windows as well. + * This does technically break SHAPE windows (xeyes, xmms), but only when monitoring is enabled which covers them with rectangular overlays anyways. + */ + r.x = xwin->attrs.x; + r.y = xwin->attrs.y; + r.width = xwin->attrs.width + xwin->attrs.border_width * 2; + r.height = xwin->attrs.height + xwin->attrs.border_width * 2; + if (XRectInRegion(occluded, r.x, r.y, r.width, r.height) != RectangleIn) { + /* the window isn't fully occluded, compose it and add it to occluded */ + if (xwin->monitor && !xwin->attrs.override_redirect) vwm_overlay_xwin_compose(vwm, xwin); + XUnionRectWithRegion(&r, occluded, occluded); + xwin->occluded = 0; + } else { + xwin->occluded = 1; + VWM_TRACE("window %#x occluded, skipping compose_overlay()", (int)xwin->id); + } + } + XDestroyRegion(occluded); + + /* start with the clip regions set to the damaged area accumulated since the previous paint_all() */ + XFixesSetPictureClipRegion(vwm->display, root_buffer, 0, 0, combined_damage); /* this is the double buffer where the in-flight screen contents are staged */ + XFixesSetPictureClipRegion(vwm->display, root_picture, 0, 0, combined_damage); /* this is the visible root window */ + + /* since translucent windows aren't supported in vwm, I can do this more efficiently */ + list_for_each_entry_prev(xwin, &vwm->xwindows, xwindows) { + XRectangle r; + + if (!vwm_xwin_is_mapped(vwm, xwin) || xwin->occluded) continue; /* if !mapped or occluded skip */ + + /* these coordinates + dimensions incorporate the border (since XCompositeNameWindowPixmap is being used) */ + r.x = xwin->attrs.x; + r.y = xwin->attrs.y; + r.width = xwin->attrs.width + xwin->attrs.border_width * 2; + r.height = xwin->attrs.height + xwin->attrs.border_width * 2; + + /* render the redirected window contents into root_buffer, note root_buffer has the remaining combined_damage set as the clip region */ + XRenderComposite(vwm->display, PictOpSrc, xwin->picture, None, root_buffer, + 0, 0, 0, 0, /* src x, y, mask x, y */ + r.x, r.y, /* dst x, y */ + r.width, r.height); + + if (xwin->monitor && !xwin->attrs.override_redirect && xwin->overlay.width) { + /* draw the monitoring overlay atop the window, note we stay within the window borders here. */ + XRenderComposite(vwm->display, PictOpOver, xwin->overlay.picture, None, root_buffer, + 0, 0, 0, 0, /* src x,y, maxk x, y */ + xwin->attrs.x + xwin->attrs.border_width, /* dst x */ + xwin->attrs.y + xwin->attrs.border_width, /* dst y */ + xwin->attrs.width, vwm_overlay_xwin_composed_height(vwm, xwin)); /* w, h */ + } + + /* subtract the region of the window from the combined damage and update the root_buffer clip region to reflect the remaining damage */ + XFixesSetRegion(vwm->display, undamage_region, &r, 1); + XFixesSubtractRegion(vwm->display, combined_damage, combined_damage, undamage_region); + XFixesSetPictureClipRegion(vwm->display, root_buffer, 0, 0, combined_damage); + } + + /* at this point all of the visible windows have been subtracted from the clip region, so paint any root window damage (draw background) */ + XRenderFillRectangle(vwm->display, PictOpSrc, root_buffer, &bgcolor, 0, 0, root_attrs.width, root_attrs.height); + + /* discard the root_buffer clip region and copy root_buffer to root_picture, root_picture still has the combined damage as its clip region */ + XFixesSetPictureClipRegion(vwm->display, root_buffer, 0, 0, None); + XRenderComposite(vwm->display, PictOpSrc, root_buffer, None, root_picture, 0, 0, 0, 0, 0, 0, root_attrs.width, root_attrs.height); + + /* fin */ + XFixesDestroyRegion(vwm->display, combined_damage); + combined_damage = None; + XSync(vwm->display, False); +} + + +/* toggle compositing/monitoring overlays on/off */ +void vwm_composite_toggle(vwm_t *vwm) +{ + vwm_xwindow_t *xwin; + + XGrabServer(vwm->display); + XSync(vwm->display, False); + + switch (compositing_mode) { + case VWM_COMPOSITING_OFF: + VWM_TRACE("enabling compositing"); + compositing_mode = VWM_COMPOSITING_MONITORS; + XCompositeRedirectSubwindows(vwm->display, VWM_XROOT(vwm), CompositeRedirectManual); + list_for_each_entry_prev(xwin, &vwm->xwindows, xwindows) { + bind_namewindow(vwm, xwin); + xwin->damage = XDamageCreate(vwm->display, xwin->id, XDamageReportNonEmpty); + } + /* damage everything */ + /* TODO: keep a list of rects reflecting all the current screens and create a region from that... */ + vwm_composite_damage_add(vwm, XFixesCreateRegionFromWindow(vwm->display, VWM_XROOT(vwm), WindowRegionBounding)); + break; + + case VWM_COMPOSITING_MONITORS: { + XEvent ev; + + VWM_TRACE("disabling compositing"); + compositing_mode = VWM_COMPOSITING_OFF; + list_for_each_entry_prev(xwin, &vwm->xwindows, xwindows) { + unbind_namewindow(vwm, xwin); + XDamageDestroy(vwm->display, xwin->damage); + } + XCompositeUnredirectSubwindows(vwm->display, VWM_XROOT(vwm), CompositeRedirectManual); + vwm_composite_invalidate_root(vwm); + + /* if there's any damage queued up discard it so we don't enter paint_all() until compositing is reenabled again. */ + if (combined_damage) { + XFixesDestroyRegion(vwm->display, combined_damage); + combined_damage = None; + } + while (XCheckTypedEvent(vwm->display, vwm->damage_event + XDamageNotify, &ev) != False); + break; + } + } + + XUngrabServer(vwm->display); +} diff --git a/src/composite.h b/src/composite.h new file mode 100644 index 0000000..fb4f623 --- /dev/null +++ b/src/composite.h @@ -0,0 +1,24 @@ +#ifndef _COMPOSITE_H +#define _COMPOSITE_H + +#include +#include +#include + +typedef struct _vwm_t vwm_t; +typedef struct _vwm_xwindow_t vwm_xwindow_t; + +void vwm_composite_xwin_create(vwm_t *vwm, vwm_xwindow_t *xwin); +void vwm_composite_xwin_destroy(vwm_t *vwm, vwm_xwindow_t *xwin); +void vwm_composite_damage_add(vwm_t *vwm, XserverRegion damage); +void vwm_composite_damage_win(vwm_t *vwm, vwm_xwindow_t *xwin); +void vwm_composite_handle_configure(vwm_t *vwm, vwm_xwindow_t *xwin, XWindowAttributes *new_attrs); +void vwm_composite_handle_map(vwm_t *vwm, vwm_xwindow_t *xwin); +void vwm_composite_damage_event(vwm_t *vwm, XDamageNotifyEvent *ev); +void vwm_composite_damage_win(vwm_t *vwm, vwm_xwindow_t *xwin); +void vwm_composite_paint_all(vwm_t *vwm); +void vwm_composite_invalidate_root(vwm_t *vwm); +void vwm_composite_repaint_needed(vwm_t *vwm); +void vwm_composite_toggle(vwm_t *vwm); + +#endif diff --git a/src/context.c b/src/context.c new file mode 100644 index 0000000..cede8a9 --- /dev/null +++ b/src/context.c @@ -0,0 +1,97 @@ +/* + * \/\/\ + * + * Copyright (C) 2012-2016 Vito Caputo - + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3 as published + * by the Free Software Foundation. + * + * 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 . + */ + /* desktop/shelf context handling */ + +#include + +#include "context.h" +#include "desktop.h" +#include "vwm.h" +#include "xwindow.h" +#include "window.h" + +/* switch to the desired context if it isn't already the focused one, inform caller if anything happened */ +int vwm_context_focus(vwm_t *vwm, vwm_context_t desired_context) +{ + vwm_context_t entry_context = vwm->focused_context; + + switch (vwm->focused_context) { + vwm_xwindow_t *xwin; + vwm_window_t *vwin; + + case VWM_CONTEXT_SHELF: + if (desired_context == VWM_CONTEXT_SHELF) break; + + /* desired == DESKTOP && focused == SHELF */ + + VWM_TRACE("unmapping shelf window \"%s\"", vwm->focused_shelf->xwindow->name); + vwm_win_unmap(vwm, vwm->focused_shelf); + XFlush(vwm->display); /* for a more responsive feel */ + + /* map the focused desktop, from the top of the stack down */ + list_for_each_entry_prev(xwin, &vwm->xwindows, xwindows) { + if (!(vwin = xwin->managed)) continue; + if (vwin->desktop == vwm->focused_desktop && !vwin->shelved) { + VWM_TRACE("Mapping desktop window \"%s\"", xwin->name); + vwm_win_map(vwm, vwin); + } + } + + if (vwm->focused_desktop->focused_window) { + VWM_TRACE("Focusing \"%s\"", vwm->focused_desktop->focused_window->xwindow->name); + XSetInputFocus(vwm->display, vwm->focused_desktop->focused_window->xwindow->id, RevertToPointerRoot, CurrentTime); + } + + vwm->focused_context = VWM_CONTEXT_DESKTOP; + break; + + case VWM_CONTEXT_DESKTOP: + /* unmap everything, map the shelf */ + if (desired_context == VWM_CONTEXT_DESKTOP) break; + + /* desired == SHELF && focused == DESKTOP */ + + /* there should be a focused shelf if the shelf contains any windows, we NOOP the switch if the shelf is empty. */ + if (vwm->focused_shelf) { + /* unmap everything on the current desktop */ + list_for_each_entry(xwin, &vwm->xwindows, xwindows) { + if (!(vwin = xwin->managed)) continue; + if (vwin->desktop == vwm->focused_desktop) { + VWM_TRACE("Unmapping desktop window \"%s\"", xwin->name); + vwm_win_unmap(vwm, vwin); + } + } + + XFlush(vwm->display); /* for a more responsive feel */ + + VWM_TRACE("Mapping shelf window \"%s\"", vwm->focused_shelf->xwindow->name); + vwm_win_map(vwm, vwm->focused_shelf); + vwm_win_focus(vwm, vwm->focused_shelf); + + vwm->focused_context = VWM_CONTEXT_SHELF; + } + break; + + default: + VWM_BUG("unexpected focused context %x", vwm->focused_context); + break; + } + + /* return if the context has been changed, the caller may need to branch differently if nothing happened */ + return (vwm->focused_context != entry_context); +} diff --git a/src/context.h b/src/context.h new file mode 100644 index 0000000..1604bd3 --- /dev/null +++ b/src/context.h @@ -0,0 +1,14 @@ +#ifndef _CONTEXT_H +#define _CONTEXT_H + +typedef struct _vwm_t vwm_t; + +typedef enum _vwm_context_t { + VWM_CONTEXT_DESKTOP = 0, /* focus the desktop context */ + VWM_CONTEXT_SHELF, /* focus the shelf context */ + VWM_CONTEXT_OTHER /* focus the other context relative to the current one */ +} vwm_context_t; + +int vwm_context_focus(vwm_t *vwm, vwm_context_t desired_context); + +#endif diff --git a/src/desktop.c b/src/desktop.c new file mode 100644 index 0000000..d3fdd13 --- /dev/null +++ b/src/desktop.c @@ -0,0 +1,158 @@ +/* + * \/\/\ + * + * Copyright (C) 2012-2016 Vito Caputo - + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3 as published + * by the Free Software Foundation. + * + * 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 . + */ + /* virtual desktops */ + +#include +#include + +#include "list.h" +#include "context.h" +#include "desktop.h" +#include "vwm.h" +#include "xwindow.h" + +/* make the specified desktop the most recently used one */ +void vwm_desktop_mru(vwm_t *vwm, vwm_desktop_t *desktop) +{ + VWM_TRACE("MRU desktop: %p", desktop); + list_move(&desktop->desktops_mru, &vwm->desktops_mru); +} + + +/* focus a virtual desktop */ +/* this switches to the desktop context if necessary, maps and unmaps windows accordingly if necessary */ +int vwm_desktop_focus(vwm_t *vwm, vwm_desktop_t *desktop) +{ + XGrabServer(vwm->display); + XSync(vwm->display, False); + + /* if the context switched and the focused desktop is the desired desktop there's nothing else to do */ + if ((vwm_context_focus(vwm, VWM_CONTEXT_DESKTOP) && vwm->focused_desktop != desktop) || vwm->focused_desktop != desktop) { + vwm_xwindow_t *xwin; + vwm_window_t *vwin; + + /* unmap the windows on the currently focused desktop, map those on the newly focused one */ + list_for_each_entry(xwin, &vwm->xwindows, xwindows) { + if (!(vwin = xwin->managed) || vwin->shelved) continue; + if (vwin->desktop == vwm->focused_desktop) vwm_win_unmap(vwm, vwin); + } + + XFlush(vwm->display); + + list_for_each_entry_prev(xwin, &vwm->xwindows, xwindows) { + if (!(vwin = xwin->managed) || vwin->shelved) continue; + if (vwin->desktop == desktop) vwm_win_map(vwm, vwin); + } + + vwm->focused_desktop = desktop; + } + + /* directly focus the desktop's focused window if there is one, we don't use vwm_win_focus() intentionally XXX */ + if (vwm->focused_desktop->focused_window) { + VWM_TRACE("Focusing \"%s\"", vwm->focused_desktop->focused_window->xwindow->name); + XSetInputFocus(vwm->display, vwm->focused_desktop->focused_window->xwindow->id, RevertToPointerRoot, CurrentTime); + } + + XUngrabServer(vwm->display); + + return 1; +} + +/* return next MRU desktop relative to the supplied desktop */ +vwm_desktop_t * vwm_desktop_next_mru(vwm_t *vwm, vwm_desktop_t *desktop) { + list_head_t *next; + + /* this dance is necessary because the list head @ vwm->desktops_mru has no vwm_desktop_t container, + * and we're exploiting the circular nature of the doubly linked lists, so we need to take care to skip + * past the container-less head. + */ + if (desktop->desktops_mru.next == &vwm->desktops_mru) { + next = desktop->desktops_mru.next->next; + } else { + next = desktop->desktops_mru.next; + } + + return list_entry(next, vwm_desktop_t, desktops_mru); +} + +/* return next desktop spatially relative to the supplied desktop, no wrap-around */ +vwm_desktop_t * vwm_desktop_next(vwm_t *vwm, vwm_desktop_t *desktop) { + if (desktop->desktops.next != &vwm->desktops) { + desktop = list_entry(desktop->desktops.next, vwm_desktop_t, desktops); + } + + return desktop; +} + + +/* return previous desktop spatially relative to the supplied desktop, no wrap-around */ +vwm_desktop_t * vwm_desktop_prev(vwm_t *vwm, vwm_desktop_t *desktop) { + if (desktop->desktops.prev != &vwm->desktops) { + desktop = list_entry(desktop->desktops.prev, vwm_desktop_t, desktops); + } + + return desktop; +} + +/* create a virtual desktop */ +vwm_desktop_t * vwm_desktop_create(vwm_t *vwm, char *name) +{ + vwm_desktop_t *desktop; + + desktop = malloc(sizeof(vwm_desktop_t)); + if (desktop == NULL) { + VWM_PERROR("Failed to allocate desktop"); + goto _fail; + } + + desktop->name = name == NULL ? name : strdup(name); + desktop->focused_window = NULL; + + list_add_tail(&desktop->desktops, &vwm->desktops); + list_add_tail(&desktop->desktops_mru, &vwm->desktops_mru); + + return desktop; + +_fail: + return NULL; +} + + +/* destroy a virtual desktop */ +void vwm_desktop_destroy(vwm_t *vwm, vwm_desktop_t *desktop) +{ + /* silently refuse to destroy a desktop having windows (for now) */ + /* there's _always_ a focused window on a desktop having mapped windows */ + /* also silently refuse to destroy the last desktop (for now) */ + if (desktop->focused_window || (desktop->desktops.next == desktop->desktops.prev)) return; + + /* focus the MRU desktop that isn't this one if we're the focused desktop */ + if (desktop == vwm->focused_desktop) { + vwm_desktop_t *next_desktop; + + list_for_each_entry(next_desktop, &vwm->desktops_mru, desktops_mru) { + if (next_desktop != desktop) { + vwm_desktop_focus(vwm, next_desktop); + break; + } + } + } + + list_del(&desktop->desktops); + list_del(&desktop->desktops_mru); +} diff --git a/src/desktop.h b/src/desktop.h new file mode 100644 index 0000000..cc6df38 --- /dev/null +++ b/src/desktop.h @@ -0,0 +1,25 @@ +#ifndef _DESKTOP_H +#define _DESKTOP_H + +#include "list.h" +#include "window.h" + +typedef struct _vwm_t vwm_t; +typedef struct _vwm_window_t vwm_window_t; + +typedef struct _vwm_desktop_t { + list_head_t desktops; /* global list of (virtual) desktops */ + list_head_t desktops_mru; /* global list of (virtual) desktops in MRU order */ + char *name; /* name of the desktop (TODO) */ + vwm_window_t *focused_window; /* the focused window on this virtual desktop */ +} vwm_desktop_t; + +void vwm_desktop_mru(vwm_t *vwm, vwm_desktop_t *desktop); +int vwm_desktop_focus(vwm_t *vwm, vwm_desktop_t *desktop); +vwm_desktop_t * vwm_desktop_create(vwm_t *vwm, char *name); +void vwm_desktop_destroy(vwm_t *vwm, vwm_desktop_t *desktop); +vwm_desktop_t * vwm_desktop_next_mru(vwm_t *vwm, vwm_desktop_t *desktop); +vwm_desktop_t * vwm_desktop_next(vwm_t *vwm, vwm_desktop_t *desktop); +vwm_desktop_t * vwm_desktop_prev(vwm_t *vwm, vwm_desktop_t *desktop); + +#endif diff --git a/src/key.c b/src/key.c new file mode 100644 index 0000000..7a15ed0 --- /dev/null +++ b/src/key.c @@ -0,0 +1,371 @@ +/* + * \/\/\ + * + * Copyright (C) 2012-2016 Vito Caputo - + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3 as published + * by the Free Software Foundation. + * + * 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 . + */ + +#include +#include +#include + +#include "composite.h" +#include "desktop.h" +#include "launch.h" +#include "list.h" +#include "vwm.h" +#include "window.h" +#include "xwindow.h" + +static int key_is_grabbed; /* flag for tracking keyboard grab state */ + +/* Poll the keyboard state to see if _any_ keys are pressed */ +static int keys_pressed(vwm_t *vwm) { + int i; + char state[32]; + + XQueryKeymap(vwm->display, state); + + for (i = 0; i < sizeof(state); i++) { + if (state[i]) return 1; + } + + return 0; +} + +/* Called in response to KeyRelease events, for now only interesting for detecting when Mod1 is released termintaing + * window cycling for application of MRU on the focused window */ +void vwm_key_released(vwm_t *vwm, Window win, XKeyReleasedEvent *keyrelease) +{ + vwm_window_t *vwin; + KeySym sym; + + switch ((sym = XLookupKeysym(keyrelease, 0))) { + case XK_Alt_R: + case XK_Alt_L: /* TODO: actually use the modifier mapping, for me XK_Alt_[LR] is Mod1. XGetModifierMapping()... */ + VWM_TRACE("XK_Alt_[LR] released"); + + /* aborted? try restore focused_origin */ + if (key_is_grabbed > 1 && vwm->focused_origin) { + VWM_TRACE("restoring %p on %p", vwm->focused_origin, vwm->focused_origin->desktop); + vwm_desktop_focus(vwm, vwm->focused_origin->desktop); + vwm_win_focus(vwm, vwm->focused_origin); + } + + /* make the focused window the most recently used */ + if ((vwin = vwm_win_focused(vwm))) vwm_win_mru(vwm, vwin); + + /* make the focused desktop the most recently used */ + if (vwm->focused_context == VWM_CONTEXT_DESKTOP && vwm->focused_desktop) vwm_desktop_mru(vwm, vwm->focused_desktop); + + break; + + default: + VWM_TRACE("Unhandled keycode: %x", (unsigned int)sym); + break; + } + + if (key_is_grabbed && !keys_pressed(vwm)) { + XUngrabKeyboard(vwm->display, CurrentTime); + XFlush(vwm->display); + key_is_grabbed = 0; + vwm->fence_mask = 0; /* reset the fence mask on release for VWM_FENCE_MASKED_VIOLATE */ + } +} + + +/* Called in response to KeyPress events, I currenly only grab Mod1 keypress events */ +void vwm_key_pressed(vwm_t *vwm, Window win, XKeyPressedEvent *keypress) +{ + vwm_window_t *vwin; + KeySym sym; + static KeySym last_sym; + static typeof(keypress->state) last_state; + static int repeat_cnt = 0; + int do_grab = 0; + char *quit_console_args[] = {"/bin/sh", "-c", "screen -dr " CONSOLE_SESSION_STRING " -X quit", NULL}; + + sym = XLookupKeysym(keypress, 0); + + /* detect repeaters, note repeaters do not span interrupted Mod1 sequences! */ + if (key_is_grabbed && sym == last_sym && keypress->state == last_state) { + repeat_cnt++; + } else { + repeat_cnt = 0; + } + + vwin = vwm_win_focused(vwm); + + switch (sym) { + +#define launcher(_sym, _label, _argv)\ + case _sym: \ + { \ + char *args[] = {"/bin/sh", "-c", "screen -dr " CONSOLE_SESSION_STRING " -X screen /bin/sh -i -x -c \"" _argv " || sleep 86400\"", NULL};\ + vwm_launch(vwm, args, VWM_LAUNCH_MODE_BG);\ + break; \ + } +#include "launchers.def" +#undef launcher + case XK_Alt_L: /* transaction abort */ + case XK_Alt_R: + if (key_is_grabbed) key_is_grabbed++; + VWM_TRACE("aborting with origin %p", vwm->focused_origin); + break; + + case XK_grave: /* toggle shelf visibility */ + vwm_context_focus(vwm, VWM_CONTEXT_OTHER); + break; + + case XK_Tab: /* cycle focused window */ + do_grab = 1; /* update MRU window on commit (Mod1 release) */ + + /* focus the next window, note this doesn't affect MRU yet, that happens on Mod1 release */ + if (vwin) { + if (keypress->state & ShiftMask) { + vwm_win_focus_next(vwm, vwin, VWM_FENCE_MASKED_VIOLATE); + } else { + vwm_win_focus_next(vwm, vwin, VWM_FENCE_RESPECT); + } + } + break; + + case XK_space: { /* cycle focused desktop utilizing MRU */ + vwm_desktop_t *next_desktop = vwm_desktop_next_mru(vwm, vwm->focused_desktop); + + do_grab = 1; /* update MRU desktop on commit (Mod1 release) */ + + if (keypress->state & ShiftMask) { + /* migrate the focused window with the desktop focus to the most recently used desktop */ + if (vwin) vwm_win_migrate(vwm, vwin, next_desktop); + } else { + vwm_desktop_focus(vwm, next_desktop); + } + break; + } + + case XK_d: /* destroy focused */ + if (vwin) { + if (keypress->state & ShiftMask) { /* brutally destroy the focused window */ + XKillClient(vwm->display, vwin->xwindow->id); + } else { /* kindly destroy the focused window */ + vwm_xwin_message(vwm, vwin->xwindow, vwm->wm_protocols_atom, vwm->wm_delete_atom); + } + } else if (vwm->focused_context == VWM_CONTEXT_DESKTOP) { + /* destroy the focused desktop when destroy occurs without any windows */ + vwm_desktop_destroy(vwm, vwm->focused_desktop); + } + break; + + case XK_Escape: /* leave VWM rudely, after triple press */ + do_grab = 1; + + if (repeat_cnt == 2) { + vwm_launch(vwm, quit_console_args, VWM_LAUNCH_MODE_FG); + exit(42); + } + break; + + case XK_v: /* instantiate (and focus) a new (potentially empty, unless migrating) virtual desktop */ + do_grab = 1; /* update MRU desktop on commit (Mod1 release) */ + + if (keypress->state & ShiftMask) { + if (vwin) { + /* migrate the focused window to a newly created virtual desktop, focusing the new desktop simultaneously */ + vwm_win_migrate(vwm, vwin, vwm_desktop_create(vwm, NULL)); + } + } else { + vwm_desktop_focus(vwm, vwm_desktop_create(vwm, NULL)); + vwm_desktop_mru(vwm, vwm->focused_desktop); + } + break; + + case XK_h: /* previous virtual desktop, if we're in the shelf context this will simply switch to desktop context */ + do_grab = 1; /* update MRU desktop on commit (Mod1 release) */ + + if (keypress->state & ShiftMask) { + if (vwin) { + /* migrate the focused window with the desktop focus to the previous desktop */ + vwm_win_migrate(vwm, vwin, vwm_desktop_prev(vwm, vwin->desktop)); + } + } else { + if (vwm->focused_context == VWM_CONTEXT_SHELF) { + /* focus the focused desktop instead of the shelf */ + vwm_context_focus(vwm, VWM_CONTEXT_DESKTOP); + } else { + /* focus the previous desktop */ + vwm_desktop_focus(vwm, vwm_desktop_prev(vwm, vwm->focused_desktop)); + } + } + break; + + case XK_l: /* next virtual desktop, if we're in the shelf context this will simply switch to desktop context */ + do_grab = 1; /* update MRU desktop on commit (Mod1 release) */ + + if (keypress->state & ShiftMask) { + if (vwin) { + /* migrate the focused window with the desktop focus to the next desktop */ + vwm_win_migrate(vwm, vwin, vwm_desktop_next(vwm, vwin->desktop)); + } + } else { + if (vwm->focused_context == VWM_CONTEXT_SHELF) { + /* focus the focused desktop instead of the shelf */ + vwm_context_focus(vwm, VWM_CONTEXT_DESKTOP); + } else { + /* focus the next desktop */ + vwm_desktop_focus(vwm, vwm_desktop_next(vwm, vwm->focused_desktop)); + } + } + break; + + case XK_k: /* raise or shelve the focused window */ + if (vwin) { + if (keypress->state & ShiftMask) { /* shelf the window and focus the shelf */ + if (vwm->focused_context != VWM_CONTEXT_SHELF) { + /* shelve the focused window while focusing the shelf */ + vwm_win_shelve(vwm, vwin); + vwm_context_focus(vwm, VWM_CONTEXT_SHELF); + } + } else { + do_grab = 1; + + XRaiseWindow(vwm->display, vwin->xwindow->id); + + if (repeat_cnt == 1) { + /* double: reraise & fullscreen */ + vwm_win_autoconf(vwm, vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_FULL); + } else if (repeat_cnt == 2) { + /* triple: reraise & fullscreen w/borders obscured by screen perimiter */ + vwm_win_autoconf(vwm, vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_ALL); + } else if (vwm->xinerama_screens_cnt > 1) { + if (repeat_cnt == 3) { + /* triple: reraise & fullscreen across all screens */ + vwm_win_autoconf(vwm, vwin, VWM_SCREEN_REL_TOTAL, VWM_WIN_AUTOCONF_FULL); + } else if (repeat_cnt == 4) { + /* quadruple: reraise & fullscreen w/borders obscured by screen perimiter */ + vwm_win_autoconf(vwm, vwin, VWM_SCREEN_REL_TOTAL, VWM_WIN_AUTOCONF_ALL); + } + } + XFlush(vwm->display); + } + } + break; + + case XK_j: /* lower or unshelve the focused window */ + if (vwin) { + if (keypress->state & ShiftMask) { /* unshelf the window to the focused desktop, and focus the desktop */ + if (vwm->focused_context == VWM_CONTEXT_SHELF) { + /* unshelve the focused window, focus the desktop it went to */ + vwm_win_migrate(vwm, vwin, vwm->focused_desktop); + } + } else { + if (vwin->autoconfigured == VWM_WIN_AUTOCONF_ALL) { + vwm_win_autoconf(vwm, vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_FULL); + } else { + XLowerWindow(vwm->display, vwin->xwindow->id); + } + XFlush(vwm->display); + } + } + break; + + case XK_Return: /* (full-screen / restore) focused window */ + if (vwin) { + if (vwin->autoconfigured) { + vwm_win_autoconf(vwm, vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_NONE); + } else { + vwm_win_autoconf(vwm, vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_FULL); + } + } + break; + + case XK_s: /* shelve focused window */ + if (vwin && !vwin->shelved) vwm_win_shelve(vwm, vwin); + break; + + case XK_bracketleft: /* reconfigure the focused window to occupy the left or top half of the screen or left quarters on repeat */ + if (vwin) { + do_grab = 1; + + if (keypress->state & ShiftMask) { + if (!repeat_cnt) { + vwm_win_autoconf(vwm, vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_HALF, VWM_SIDE_TOP); + } else { + vwm_win_autoconf(vwm, vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_QUARTER, VWM_CORNER_TOP_LEFT); + } + } else { + if (!repeat_cnt) { + vwm_win_autoconf(vwm, vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_HALF, VWM_SIDE_LEFT); + } else { + vwm_win_autoconf(vwm, vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_QUARTER, VWM_CORNER_BOTTOM_LEFT); + } + } + } + break; + + case XK_bracketright: /* reconfigure the focused window to occupy the right or bottom half of the screen or right quarters on repeat */ + if (vwin) { + do_grab = 1; + + if (keypress->state & ShiftMask) { + if (!repeat_cnt) { + vwm_win_autoconf(vwm, vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_HALF, VWM_SIDE_BOTTOM); + } else { + vwm_win_autoconf(vwm, vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_QUARTER, VWM_CORNER_BOTTOM_RIGHT); + } + } else { + if (!repeat_cnt) { + vwm_win_autoconf(vwm, vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_HALF, VWM_SIDE_RIGHT); + } else { + vwm_win_autoconf(vwm, vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_QUARTER, VWM_CORNER_TOP_RIGHT); + } + } + } + break; + + case XK_semicolon: /* toggle composited overlays */ + vwm_composite_toggle(vwm); + break; + + case XK_apostrophe: /* reset snowflakes of the focused window, suppressed when not compositing */ + if (vwin) { + vwm_overlay_xwin_reset_snowflakes(vwm, vwin->xwindow); + } + break; + + case XK_Right: /* increase sampling frequency */ + vwm_overlay_rate_increase(vwm); + break; + + case XK_Left: /* decrease sampling frequency */ + vwm_overlay_rate_decrease(vwm); + break; + + default: + VWM_TRACE("Unhandled keycode: %x", (unsigned int)sym); + break; + } + + /* if what we're doing requests a grab, if not already grabbed, grab keyboard */ + if (!key_is_grabbed && do_grab) { + VWM_TRACE("saving focused_origin of %p", vwin); + vwm->focused_origin = vwin; /* for returning to on abort */ + XGrabKeyboard(vwm->display, VWM_XROOT(vwm), False, GrabModeAsync, GrabModeAsync, CurrentTime); + key_is_grabbed = 1; + } + + /* remember the symbol for repeater detection */ + last_sym = sym; + last_state = keypress->state; +} diff --git a/src/key.h b/src/key.h new file mode 100644 index 0000000..d0bbb15 --- /dev/null +++ b/src/key.h @@ -0,0 +1,11 @@ +#ifndef _KEY_H +#define _KEY_H + +#include + +typedef struct _vwm_t vwm_t; + +void vwm_key_released(vwm_t *vwm, Window win, XKeyReleasedEvent *keyrelease); +void vwm_key_pressed(vwm_t *vwm, Window win, XKeyPressedEvent *keypress); + +#endif diff --git a/src/launch.c b/src/launch.c new file mode 100644 index 0000000..123e850 --- /dev/null +++ b/src/launch.c @@ -0,0 +1,45 @@ +/* + * \/\/\ + * + * Copyright (C) 2012-2016 Vito Caputo - + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3 as published + * by the Free Software Foundation. + * + * 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 . + */ + /* launching of external processes / X clients */ + +#include +#include +#include +#include +#include +#include + +#include "launch.h" +#include "vwm.h" + +#define LAUNCHED_RELATIVE_PRIORITY 10 /* the wm priority plus this is used as the priority of launched processes */ + +/* launch a child command specified in argv, mode decides if we wait for the child to exit before returning. */ +void vwm_launch(vwm_t *vwm, char **argv, vwm_launch_mode_t mode) +{ + /* XXX: in BG mode I double fork and let init inherit the orphan so I don't have to collect the return status */ + if (mode == VWM_LAUNCH_MODE_FG || !fork()) { + if (!fork()) { + /* child */ + setpriority(PRIO_PROCESS, getpid(), vwm->priority + LAUNCHED_RELATIVE_PRIORITY); + execvp(argv[0], argv); + } + if (mode == VWM_LAUNCH_MODE_BG) exit(0); + } + wait(NULL); /* TODO: could wait for the specific pid, particularly in FG mode ... */ +} diff --git a/src/launch.h b/src/launch.h new file mode 100644 index 0000000..0e279b0 --- /dev/null +++ b/src/launch.h @@ -0,0 +1,13 @@ +#ifndef _LAUNCH_H +#define _LAUNCH_H + +typedef struct _vwm_t vwm_t; + +typedef enum _vwm_launch_mode_t { + VWM_LAUNCH_MODE_FG, + VWM_LAUNCH_MODE_BG, +} vwm_launch_mode_t; + +void vwm_launch(vwm_t *vwm, char **argv, vwm_launch_mode_t mode); + +#endif diff --git a/src/launchers.def b/src/launchers.def new file mode 100644 index 0000000..2c63f96 --- /dev/null +++ b/src/launchers.def @@ -0,0 +1,8 @@ +/* it's up to you to ensure you don't conflict with the global VWM keys */ +/* keysym, label, cmd */ +launcher( XK_x, "xterm", "/usr/bin/xterm") +launcher( XK_b, "iceweasel", "/usr/bin/iceweasel -ProfileManager -no-remote") +launcher( XK_g, "gimp", "/usr/bin/gimp") +launcher( XK_period, "lock", "/usr/bin/xlock") +launcher( XK_minus, "dpms off", "/usr/bin/xset -dpms s off") +launcher( XK_equal, "dpms on", "/usr/bin/xset +dpms s on") diff --git a/src/libvmon/LICENSE b/src/libvmon/LICENSE new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/src/libvmon/LICENSE @@ -0,0 +1,674 @@ + 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 +. diff --git a/src/libvmon/bitmap.h b/src/libvmon/bitmap.h new file mode 100644 index 0000000..eacb97d --- /dev/null +++ b/src/libvmon/bitmap.h @@ -0,0 +1,15 @@ +#ifndef _BITMAP_H +#define _BITMAP_H + +/* simple implementation of general-purpose bitmap macros taken from the comp.lang.c FAQ */ + +#include /* for CHAR_BIT */ + +#define BITMASK(b) (1 << ((b) % CHAR_BIT)) +#define BITSLOT(b) ((b) / CHAR_BIT) +#define BITSET(a, b) ((a)[BITSLOT(b)] |= BITMASK(b)) +#define BITCLEAR(a, b) ((a)[BITSLOT(b)] &= ~BITMASK(b)) +#define BITTEST(a, b) ((a)[BITSLOT(b)] & BITMASK(b)) +#define BITNSLOTS(nb) ((nb + CHAR_BIT - 1) / CHAR_BIT) + +#endif diff --git a/src/libvmon/defs/_begin.def b/src/libvmon/defs/_begin.def new file mode 100644 index 0000000..047fd4d --- /dev/null +++ b/src/libvmon/defs/_begin.def @@ -0,0 +1,549 @@ +/* the common types are handled in _begin.def and _end.def, individual .def files are free to create special types as well, but should + * provide macros for all the ifdef's supported here for any additions. + */ + +/* for declaring the want-specific sample data structure (used by vmon.h) */ +#ifdef VMON_DECLARE_MEMBERS +#define vmon_datum_str(_name, _sym, _label, _desc) char *_name; +#define vmon_datum_str_array(_name, _sym, _label, _desc) char **_name; +#define vmon_datum_char(_name, _sym, _label, _desc) char _name; +#define vmon_datum_char_array(_name, _sym, _label, _desc) vmon_char_array_t _name; +#define vmon_datum_int(_name, _sym, _label, _desc) int _name; +#define vmon_datum_uint(_name, _sym, _label, _desc) unsigned int _name; +#define vmon_datum_ulong(_name, _sym, _label, _desc) unsigned long _name; +#define vmon_datum_ulonglong(_name, _sym, _label, _desc) unsigned long long _name; +#define vmon_datum_long(_name, _sym, _label, _desc) long _name; +#define vmon_datum_longlong(_name, _sym, _label, _desc) long long _name; + +/* leave omissions undefined, they'll get defined as noops at the end of this file */ +#endif + + + +/* for creating the symbolic constants enumeration (used by vmon.h) */ +#ifdef VMON_ENUM_SYMBOLS +#define vmon_datum_str(_name, _sym, _label, _desc) VMON_ ## _sym, +#define vmon_datum_str_array(_name, _sym, _label, _desc) VMON_ ## _sym, +#define vmon_datum_char(_name, _sym, _label, _desc) VMON_ ## _sym, +#define vmon_datum_char_array(_name, _sym, _label, _desc) VMON_ ## _sym, +#define vmon_datum_int(_name, _sym, _label, _desc) VMON_ ## _sym, +#define vmon_datum_uint(_name, _sym, _label, _desc) VMON_ ## _sym, +#define vmon_datum_ulong(_name, _sym, _label, _desc) VMON_ ## _sym, +#define vmon_datum_ulonglong(_name, _sym, _label, _desc) VMON_ ## _sym, +#define vmon_datum_long(_name, _sym, _label, _desc) VMON_ ## _sym, +#define vmon_datum_longlong(_name, _sym, _label, _desc) VMON_ ## _sym, + +/* leave omissions undefined, they'll get defined as noops at the end of this file */ +#endif + + + +/* for creating an offset table relating symbols to struct member offsets */ +#ifdef VMON_INITIALIZE_OFFSET_TABLE +/* TODO: error out using #error if VMON_OFFSET_TABLE_STRUCT is not defined */ +/* I use the gcc builtin here because it's convenient, otherwise we either do the double macro expansion dance or put the offsetof definition here */ +#define vmon_datum_str(_name, _sym, _label, _desc) __builtin_offsetof(VMON_OFFSET_TABLE_STRUCT, _name), +#define vmon_datum_str_array(_name, _sym, _label, _desc) __builtin_offsetof(VMON_OFFSET_TABLE_STRUCT, _name), +#define vmon_datum_char(_name, _sym, _label, _desc) __builtin_offsetof(VMON_OFFSET_TABLE_STRUCT, _name), +#define vmon_datum_char_array(_name, _sym, _label, _desc) __builtin_offsetof(VMON_OFFSET_TABLE_STRUCT, _name), +#define vmon_datum_int(_name, _sym, _label, _desc) __builtin_offsetof(VMON_OFFSET_TABLE_STRUCT, _name), +#define vmon_datum_uint(_name, _sym, _label, _desc) __builtin_offsetof(VMON_OFFSET_TABLE_STRUCT, _name), +#define vmon_datum_ulong(_name, _sym, _label, _desc) __builtin_offsetof(VMON_OFFSET_TABLE_STRUCT, _name), +#define vmon_datum_ulonglong(_name, _sym, _label, _desc) __builtin_offsetof(VMON_OFFSET_TABLE_STRUCT, _name), +#define vmon_datum_long(_name, _sym, _label, _desc) __builtin_offsetof(VMON_OFFSET_TABLE_STRUCT, _name), +#define vmon_datum_longlong(_name, _sym, _label, _desc) __builtin_offsetof(VMON_OFFSET_TABLE_STRUCT, _name), + +/* no offsets can exist for omitted members, so they're declared as nops */ +/* leave omissions undefined, they'll get defined as noops at the end of this file */ +#endif + + + +/* for creating a lookup table for the member names as strings, indexed by the enumerated symbols */ +#ifdef VMON_INITIALIZE_NAME_TABLE +#define vmon_datum_str(_name, _sym, _label, _desc) #_name , +#define vmon_datum_str_array(_name, _sym, _label, _desc) #_name , +#define vmon_datum_char(_name, _sym, _label, _desc) #_name , +#define vmon_datum_char_array(_name, _sym, _label, _desc) #_name , +#define vmon_datum_int(_name, _sym, _label, _desc) #_name , +#define vmon_datum_uint(_name, _sym, _label, _desc) #_name , +#define vmon_datum_ulong(_name, _sym, _label, _desc) #_name , +#define vmon_datum_ulonglong(_name, _sym, _label, _desc) #_name , +#define vmon_datum_long(_name, _sym, _label, _desc) #_name , +#define vmon_datum_longlong(_name, _sym, _label, _desc) #_name , + +/* leave omissions undefined, they'll get defined as noops at the end of this file */ +#endif + + + +/* for creating a lookup table for the human-readable descriptions, indexed by the enumerated symbols */ +#ifdef VMON_INITIALIZE_DESC_TABLE +#define vmon_datum_str(_name, _sym, _label, _desc) _desc , +#define vmon_datum_str_array(_name, _sym, _label, _desc) _desc , +#define vmon_datum_char(_name, _sym, _label, _desc) _desc , +#define vmon_datum_char_array(_name, _sym, _label, _desc) _desc , +#define vmon_datum_int(_name, _sym, _label, _desc) _desc , +#define vmon_datum_uint(_name, _sym, _label, _desc) _desc , +#define vmon_datum_ulong(_name, _sym, _label, _desc) _desc , +#define vmon_datum_ulonglong(_name, _sym, _label, _desc) _desc , +#define vmon_datum_long(_name, _sym, _label, _desc) _desc , +#define vmon_datum_longlong(_name, _sym, _label, _desc) _desc , + +/* leave omissions undefined, they'll get defined as noops at the end of this file */ +#endif + + + +/* these are different from the symbols, because they ignore the omissions, the definition includes all fields so we can parse the file, + * but the symbols only relate to fields we actually store in memory. */ +#ifdef VMON_ENUM_PARSER_STATES +#define vmon_datum_str(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, +#define vmon_datum_str_array(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, +#define vmon_datum_char(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, +#define vmon_datum_char_array(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, +#define vmon_datum_int(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, +#define vmon_datum_uint(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, +#define vmon_datum_ulong(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, +#define vmon_datum_ulonglong(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, +#define vmon_datum_long(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, +#define vmon_datum_longlong(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, + +#define vmon_omit_n(_n, _sym, _desc) VMON_PARSER_STATE_ ## _sym, +#define vmon_omit_literal(_lit, _sym) VMON_PARSER_STATE_ ## _sym, +#define vmon_omit_run(_char, _sym) VMON_PARSER_STATE_ ## _sym, +#define vmon_omit_str(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, +#define vmon_omit_str_array(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, +#define vmon_omit_char(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, +#define vmon_omit_char_array(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, +#define vmon_omit_int(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, +#define vmon_omit_uint(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, +#define vmon_omit_ulong(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, +#define vmon_omit_ulonglong(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, +#define vmon_omit_long(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, +#define vmon_omit_longlong(_name, _sym, _label, _desc) VMON_PARSER_STATE_ ## _sym, +#endif + + +/* most the stuff we need in scope for the parser generated via VMON_IMPLEMENT_PARSER before including the appropriate .def */ +#ifdef VMON_PREPARE_PARSER + char input; + int var_isneg = 0; + int var_int = 0; + unsigned int var_uint = 0; + long var_long = 0; + long long var_longlong = 0; + unsigned long var_ulong = 0; + unsigned long long var_ulonglong = 0; + char *var_array = NULL; + int var_array_alloc_len = 0, var_array_len = 0; + +#define vmon_datum_str(_name, _sym, _label, _desc) +#define vmon_datum_str_array(_name, _sym, _label, _desc) +#define vmon_datum_char(_name, _sym, _label, _desc) +#define vmon_datum_char_array(_name, _sym, _label, _desc) +#define vmon_datum_int(_name, _sym, _label, _desc) +#define vmon_datum_uint(_name, _sym, _label, _desc) +#define vmon_datum_ulong(_name, _sym, _label, _desc) +#define vmon_datum_ulonglong(_name, _sym, _label, _desc) +#define vmon_datum_long(_name, _sym, _label, _desc) +#define vmon_datum_longlong(_name, _sym, _label, _desc) + +#define vmon_omit_n(_n, _sym, _desc) +#define vmon_omit_literal(_lit, _sym) +#define vmon_omit_run(_char, _sym) +#define vmon_omit_str(_name, _sym, _label, _desc) +#define vmon_omit_str_array(_name, _sym, _label, _desc) +#define vmon_omit_char(_name, _sym, _label, _desc) +#define vmon_omit_char_array(_name, _sym, _label, _desc) +#define vmon_omit_int(_name, _sym, _label, _desc) +#define vmon_omit_uint(_name, _sym, _label, _desc) +#define vmon_omit_ulong(_name, _sym, _label, _desc) +#define vmon_omit_ulonglong(_name, _sym, _label, _desc) +#define vmon_omit_long(_name, _sym, _label, _desc) +#define vmon_omit_longlong(_name, _sym, _label, _desc) +#endif + + +/* implements the cases for a simple switch()-based bytestream parser */ +#ifdef VMON_IMPLEMENT_PARSER +/* TODO: error out if the following aren't defined, these are utilized by the parser FSM: + * VMON_PARSER_DELIM <-- what value to treat as a delimiter for string/char arrays (sort of like IFS in bash) + * TODO: there are a bunch of variables we assume are available and named a certain way here, + * it would be preferable to be able to define those externally and inform the x-macro of their + * names etc. + */ +#define vmon_datum_str(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ + switch(input) {\ + case VMON_PARSER_DELIM:\ + /* store accumulated string, reset tmp, and advance */\ + if(*store)->_name) {\ + if( strncmp((*store)->name, _array, var_array_len) ||\ + (*store)->name[var_array_len] != '\0') {\ + BITSET((*store)->changed, VMON_ ## _sym);\ + changes++;\ + }\ + free((*store)->name);\ + } else {\ + BITSET((*store)->changed, VMON_ ## _sym);\ + changes++;\ + }\ + (*store)->_name = strndup(var_array, var_array_len);\ + var_array_len = 0;\ + state++;\ + break;\ + default:\ + /* accumulate string */\ + var_array[var_array_len++] = input;\ + break;\ + }\ + break; + +#define vmon_datum_str_array(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ + /* TODO ? */ \ + break; + +#define vmon_datum_char(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ + if((*store)->_name != input) {\ + BITSET((*store)->changed, VMON_ ## _sym);\ + changes++;\ + (*store)->_name = input;\ + }\ + state++;\ + break; + +#define vmon_datum_char_array(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ + /* TODO */\ + /* TODO */\ + break; + +#define vmon_datum_int(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ + switch(input) {\ + case '-':\ + /* TODO: we don't verify the '-' is leading... */\ + var_isneg = 1;\ + break;\ + case '0' ... '9':\ + var_int *= 10;\ + var_int += input - '0';\ + break;\ + default:\ + if(var_isneg) {\ + var_int = -var_int;\ + var_isneg = 0;\ + }\ + if((*store)->_name != var_int) {\ + BITSET((*store)->changed, VMON_ ## _sym);\ + changes++;\ + (*store)->_name = var_int;\ + }\ + var_int = 0;\ + state++;\ + break;\ + }\ + if(state == VMON_PARSER_STATE_ ## _sym) {\ + /* we want to fall-through when the state advances */\ + break;\ + } + +#define vmon_datum_uint(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ + switch(input) {\ + case '0' ... '9':\ + var_uint *= 10;\ + var_uint += input - '0';\ + break;\ + default:\ + if((*store)->_name != var_uint) {\ + BITSET((*store)->changed, VMON_ ## _sym);\ + changes++;\ + (*store)->_name = var_uint;\ + }\ + var_uint = 0;\ + state++;\ + break;\ + }\ + if(state == VMON_PARSER_STATE_ ## _sym) {\ + /* we want to fall-through when the state advances */\ + break;\ + } + +#define vmon_datum_ulong(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ + switch(input) {\ + case '0' ... '9':\ + var_ulong *= 10;\ + var_ulong += input - '0';\ + break;\ + default:\ + if((*store)->_name != var_ulong) {\ + BITSET((*store)->changed, VMON_ ## _sym);\ + changes++;\ + (*store)->_name = var_ulong;\ + }\ + var_ulong = 0;\ + state++;\ + break;\ + }\ + if(state == VMON_PARSER_STATE_ ## _sym) {\ + /* we want to fall-through when the state advances */\ + break;\ + } + +#define vmon_datum_ulonglong(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ + switch(input) {\ + case '0' ... '9':\ + var_ulonglong *= 10;\ + var_ulonglong += input - '0';\ + break;\ + default:\ + if((*store)->_name != var_ulonglong) {\ + BITSET((*store)->changed, VMON_ ## _sym);\ + changes++;\ + (*store)->_name = var_ulonglong;\ + }\ + var_ulonglong = 0;\ + state++;\ + break;\ + }\ + if(state == VMON_PARSER_STATE_ ## _sym) {\ + /* we want to fall-through when the state advances */\ + break;\ + } + +#define vmon_datum_long(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ + switch(input) {\ + case '-':\ + /* TODO: we dont verify the '-' is leading... */\ + var_isneg = 1;\ + break;\ + case '0' ... '9':\ + var_long *= 10;\ + var_long += input - '0';\ + break;\ + default:\ + if(var_isneg) {\ + var_long = -var_long;\ + var_isneg = 0;\ + }\ + if((*store)->_name != var_long) {\ + BITSET((*store)->changed, VMON_ ## _sym);\ + changes++;\ + (*store)->_name = var_long;\ + }\ + var_long = 0;\ + state++;\ + break;\ + }\ + if(state == VMON_PARSER_STATE_ ## _sym) {\ + /* we want to fall-through when the state advances */\ + break;\ + } + +#define vmon_datum_longlong(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ + switch(input) {\ + case '-':\ + /* TODO: we dont verify the '-' is leading... */\ + var_isneg = 1;\ + break;\ + case '0' ... '9':\ + var_longlong *= 10;\ + var_longlong += input - '0';\ + break;\ + default:\ + if(var_isneg) {\ + var_longlong = -var_longlong;\ + var_isneg = 0;\ + }\ + if((*store)->_name != var_longlong) {\ + BITSET((*store)->changed, VMON_ ## _sym);\ + changes++;\ + (*store)->_name = var_longlong;\ + }\ + var_longlong = 0;\ + state++;\ + break;\ + }\ + if(state == VMON_PARSER_STATE_ ## _sym) {\ + /* we want to fall-through when the state advances */\ + break;\ + } + +/* parse but simply skip omitted fields, advance on the delimiter */ +#define vmon_omit_n(_n, _sym, _desc) case VMON_PARSER_STATE_ ## _sym:\ + var_int++;\ + if(var_int >= _n) {\ + var_int = 0;\ + state++;\ + }\ + break; + +#define vmon_omit_literal(_lit, _sym) case VMON_PARSER_STATE_ ## _sym:\ + /* TODO make this actually match the literal, for now we skip the length. */ \ + var_int++;\ + if(var_int >= (sizeof(_lit) - 1)) {\ + var_int = 0;\ + state++;\ + }\ + break; + +#define vmon_omit_run(_char, _sym) case VMON_PARSER_STATE_ ## _sym:\ + if(input != _char) {\ + state++;\ + /* XXX: we fall-through to the next case because this byte belongs to the next state */\ + } else {\ + break;\ + } + + +#define vmon_omit_str(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ + if(input == VMON_PARSER_DELIM) {\ + state++;\ + } else {\ + break;\ + } + +#define vmon_omit_str_array(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ + if(input == VMON_PARSER_DELIM) {\ + state++;\ + } else {\ + break;\ + } + +#define vmon_omit_char(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ + state++;\ + break; + +#define vmon_omit_char_array(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ + if(input == VMON_PARSER_DELIM) {\ + state++;\ + } else {\ + break;\ + } + +#define vmon_omit_int(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ + switch(input) {\ + case '0' ... '9':\ + case '-':\ + break;\ + default:\ + state++;\ + break;\ + }\ + if(state == VMON_PARSER_STATE_ ## _sym) {\ + /* we want to fall-through when the state advances */\ + break;\ + } + +#define vmon_omit_uint(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ + switch(input) {\ + case '0' ... '9':\ + break;\ + default:\ + state++;\ + break;\ + }\ + if(state == VMON_PARSER_STATE_ ## _sym) {\ + /* we want to fall-through when the state advances */\ + break;\ + } + +#define vmon_omit_ulong(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ + switch(input) {\ + case '0' ... '9':\ + break;\ + default:\ + state++;\ + break;\ + }\ + if(state == VMON_PARSER_STATE_ ## _sym) {\ + /* we want to fall-through when the state advances */\ + break;\ + } + +#define vmon_omit_ulonglong(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ + switch(input) {\ + case '0' ... '9':\ + break;\ + default:\ + state++;\ + break;\ + }\ + if(state == VMON_PARSER_STATE_ ## _sym) {\ + /* we want to fall-through when the state advances */\ + break;\ + } + +#define vmon_omit_long(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ + switch(input) {\ + case '0' ... '9':\ + case '-':\ + break;\ + default:\ + state++;\ + break;\ + }\ + if(state == VMON_PARSER_STATE_ ## _sym) {\ + /* we want to fall-through when the state advances */\ + break;\ + } + +#define vmon_omit_longlong(_name, _sym, _label, _desc) case VMON_PARSER_STATE_ ## _sym:\ + switch(input) {\ + case '0' ... '9':\ + case '-':\ + break;\ + default:\ + state++;\ + break;\ + }\ + if(state == VMON_PARSER_STATE_ ## _sym) {\ + /* we want to fall-through when the state advances */\ + break;\ + } +#endif + + +/* for convenience, if the omit macros are undefind define them as noops, since that's the most common pattern */ +/* XXX TODO: we may need to add some mechanism for informing the VMON_SUPPRESS_UNDEFS clause in _end.def when these + * have been automatically defined vs. explicitly defined. When automatically defined, we should undefine them regarldess + * of undef suppression. But when they are explicitly defined prior to entering here, we should honor the undef suppression. + * I'm going to leave it as-is for now until it bites me in the ass. + */ +#ifndef vmon_omit_n +# define vmon_omit_n(_n, _sym, _desc) +#endif +#ifndef vmon_omit_literal +# define vmon_omit_literal(_lit, _sym) +#endif +#ifndef vmon_omit_run +# define vmon_omit_run(_char, _sym) +#endif +#ifndef vmon_omit_str +# define vmon_omit_str(_name, _sym, _label, _desc) +#endif +#ifndef vmon_omit_str_array +# define vmon_omit_str_array(_name, _sym, _label, _desc) +#endif +#ifndef vmon_omit_char +# define vmon_omit_char(_name, _sym, _label, _desc) +#endif +#ifndef vmon_omit_char_array +# define vmon_omit_char_array(_name, _sym, _label, _desc) +#endif +#ifndef vmon_omit_int +# define vmon_omit_int(_name, _sym, _label, _desc) +#endif +#ifndef vmon_omit_uint +# define vmon_omit_uint(_name, _sym, _label, _desc) +#endif +#ifndef vmon_omit_ulong +# define vmon_omit_ulong(_name, _sym, _label, _desc) +#endif +#ifndef vmon_omit_ulonglong +# define vmon_omit_ulonglong(_name, _sym, _label, _desc) +#endif +#ifndef vmon_omit_long +# define vmon_omit_long(_name, _sym, _label, _desc) +#endif +#ifndef vmon_omit_longlong +# define vmon_omit_longlong(_name, _sym, _label, _desc) +#endif diff --git a/src/libvmon/defs/_end.def b/src/libvmon/defs/_end.def new file mode 100644 index 0000000..9243349 --- /dev/null +++ b/src/libvmon/defs/_end.def @@ -0,0 +1,43 @@ +#ifndef VMON_SUPPRESS_UNDEFS + +/* XXX TODO: we may need to detect and manage the automatic definition of the vmon_omit_* definitions */ + +#undef vmon_datum_str +#undef vmon_datum_str_array +#undef vmon_datum_char +#undef vmon_datum_char_array +#undef vmon_datum_int +#undef vmon_datum_uint +#undef vmon_datum_ulong +#undef vmon_datum_ulonglong +#undef vmon_datum_long +#undef vmon_datum_longlong +#undef vmon_omit_n +#undef vmon_omit_literal +#undef vmon_omit_run +#undef vmon_omit_str +#undef vmon_omit_str_array +#undef vmon_omit_char +#undef vmon_omit_char_array +#undef vmon_omit_int +#undef vmon_omit_uint +#undef vmon_omit_ulong +#undef vmon_omit_ulonglong +#undef vmon_omit_long +#undef vmon_omit_longlong +#undef VMON_DECLARE_MEMBERS +#undef VMON_DECLARE_CHANGEBITS +#undef VMON_ENUM_SYMBOLS +#undef VMON_ASSIGN_NAME_TABLE +#undef VMON_ASSIGN_DESC_TABLE +#undef VMON_ENUM_PARSER_STATES +#undef VMON_PREPARE_PARSER +#undef VMON_IMPLEMENT_PARSER +#undef VMON_PARSER_DELIM +#undef vmon_want + +#else + +#undef VMON_SUPPRESS_UNDEFS + +#endif diff --git a/src/libvmon/defs/proc_files.def b/src/libvmon/defs/proc_files.def new file mode 100644 index 0000000..6e3db98 --- /dev/null +++ b/src/libvmon/defs/proc_files.def @@ -0,0 +1,8 @@ +#include "_begin.def" + + /* member name, symbolic constant, human label, human description (think UI/help) */ + /* /proc/$pid/fd */ +vmon_datum_int( fdnum, FILES_FDNUM, "FdNum", "File descriptor number (historically 0-255)") +vmon_datum_char_array( object_path, FILES_OBJPATH, "ObjPath", "Object path this descriptor represents a handle for") + +#include "_end.def" diff --git a/src/libvmon/defs/proc_io.def b/src/libvmon/defs/proc_io.def new file mode 100644 index 0000000..0e1776d --- /dev/null +++ b/src/libvmon/defs/proc_io.def @@ -0,0 +1,33 @@ +#include "_begin.def" + + /* member name, symbolic constant, human label, human description (think UI/help) */ + /* /proc/$pid/io */ +vmon_omit_literal("rchar: ", PROC_IO_RCHAR_LABEL) +vmon_datum_ulonglong( rchars, PROC_IO_RCHAR, "CharsRead", "Characters read (all)") +vmon_omit_literal("\n", PROC_IO_RCHAR_NL) + +vmon_omit_literal("wchar: ", PROC_IO_WCHAR_LABEL) +vmon_datum_ulonglong( wchars, PROC_IO_WCHAR, "CharsWritten", "Characters written (all)") +vmon_omit_literal("\n", PROC_IO_WCHAR_NL) + +vmon_omit_literal("syscr: ", PROC_IO_SYSCR_LABEL) +vmon_datum_ulonglong( syscr, PROC_IO_SYSCR, "SysReads", "Read system calls") +vmon_omit_literal("\n", PROC_IO_SYSCR_NL) + +vmon_omit_literal("syscw: ", PROC_IO_SYSCW_LABEL) +vmon_datum_ulonglong( syscw, PROC_IO_SYSCW, "SysWrites", "Write system calls") +vmon_omit_literal("\n", PROC_IO_SYSCW_NL) + +vmon_omit_literal("read_bytes: ", PROC_IO_READBYTES_LABEL) +vmon_datum_ulonglong( read_bytes, PROC_IO_READBYTES, "BytesReadIO", "Bytes read from storage") +vmon_omit_literal("\n", PROC_IO_READBYTES_NL) + +vmon_omit_literal("write_bytes: ", PROC_IO_WRITEBYTES_LABEL) +vmon_datum_ulonglong( write_bytes, PROC_IO_WRITEBYTES, "BytesWrittenIO", "Bytes written to storage") +vmon_omit_literal("\n", PROC_IO_WRITEBYTES_NL) + +vmon_omit_literal("cancelled_write_bytes: ", PROC_IO_CANCELLED_WRITEBYTES_LABEL) +vmon_datum_ulonglong( cancelled_write_bytes, PROC_IO_CANCELLED_WRITEBYTES, "CancelledWriteBytes", "Bytes written but canceled before reaching storage (truncate)") +vmon_omit_literal("\n", PROC_IO_CANCELLED_WRITEBYTES_NL) + +#include "_end.def" diff --git a/src/libvmon/defs/proc_stat.def b/src/libvmon/defs/proc_stat.def new file mode 100644 index 0000000..db704e9 --- /dev/null +++ b/src/libvmon/defs/proc_stat.def @@ -0,0 +1,105 @@ +#include "_begin.def" + + /* member name, symbolic constant, human label, human description (think UI/help) */ + /* /proc/$pid/comm */ +vmon_datum_char_array( comm, PROC_STAT_COMM, "Cmd", "/proc/$pid/comm raw contents (with the \n substituted with \0)") + + /* /proc/$pid/cmdline */ +vmon_datum_char_array( cmdline, PROC_STAT_CMDLINE, "Cmdline", "/proc/$pid/cmdline raw contents") +vmon_datum_int( argc, PROC_STAT_ARGC, "Argc", "parsed cmdline count as if executed") +vmon_datum_str_array( argv, PROC_STAT_ARGV, "Argv", "parsed cmdline argv contents as if executed, pointers into cmdline") + + /* /proc/$pid/exe */ +vmon_datum_char_array( exe, PROC_STAT_EXE, "ExePath", "/proc/$pid/exe symlink target") + + /* /proc/$pid/wchan */ +vmon_datum_char_array( wchan, PROC_STAT_WCHAN, "WChan", "/proc/$pid/wchan raw contents (address resolved)") + + /* /proc/$pid/stat */ +vmon_datum_int( pid, PROC_STAT_PID, "PID", "the process id") +vmon_omit_n( (*store)->comm.len + 3, PROC_STAT_COMM_, "the filename of the executable, in parentheses, skipped") +vmon_datum_char( state, PROC_STAT_STATE, "State", "process state, one of \"RSDZTW\"") +vmon_omit_run( ' ', PROC_STAT_PPID_SP) +vmon_datum_longlong( ppid, PROC_STAT_PPID, "PPId", "parent pid") +vmon_omit_run( ' ', PROC_STAT_PGID_SP) +vmon_datum_longlong( pgrp, PROC_STAT_PGID, "PGId", "parent process group") +vmon_omit_run( ' ', PROC_STAT_SID_SP) +vmon_datum_longlong( sid, PROC_STAT_SID, "SessionId", "session id") +vmon_omit_run( ' ', PROC_STAT_TTY_NR_SP) +vmon_datum_longlong( tty_nr, PROC_STAT_TTY_NR, "Tty", "controlling terminal of the process") +vmon_omit_run( ' ', PROC_STAT_TPGID_SP) +vmon_datum_longlong( tpgid, PROC_STAT_TPGID, "CtrlPGid", "id of the foreground process group of the controlling terminal of the process") +vmon_omit_run( ' ', PROC_STAT_FLAGS_SP) +vmon_datum_ulonglong( flags, PROC_STAT_FLAGS, "Flags", "the kernel flags of the process (see PF_* in the non-uapi )") +vmon_omit_run( ' ', PROC_STAT_MINFLT_SP) +vmon_datum_ulonglong( minflt, PROC_STAT_MINFLT, "MnrFlts", "the number of minor faults (no hitting disk)") +vmon_omit_run( ' ', PROC_STAT_CMINFLT_SP) +vmon_datum_ulonglong( cminflt, PROC_STAT_CMINFLT, "ChldMnrFlts", "number of minor faults waited-for children have made") +vmon_omit_run( ' ', PROC_STAT_MAJFLT_SP) +vmon_datum_ulonglong( majflt, PROC_STAT_MAJFLT, "MjrFlts", "the number of major faults (hit disk)") +vmon_omit_run( ' ', PROC_STAT_CMAJFLT_SP) +vmon_datum_ulonglong( cmajflt, PROC_STAT_CMAJFLT, "ChldMjrFlts", "the number of major faults waited-for children have made") +vmon_omit_run( ' ', PROC_STAT_UTIME_SP) +vmon_datum_ulonglong( utime, PROC_STAT_UTIME, "UsrCPU", "amount of time this process has spent in user mode (ticks)") +vmon_omit_run( ' ', PROC_STAT_STIME_SP) +vmon_datum_ulonglong( stime, PROC_STAT_STIME, "SysCPU", "amount of time this process has spent in kernel mode (ticks)") +vmon_omit_run( ' ', PROC_STAT_CUTIME_SP) +vmon_datum_longlong( cutime, PROC_STAT_CUTIME, "ChldUsrCPU", "amount of time the waited-for children have spent in user mode (ticks)") +vmon_omit_run( ' ', PROC_STAT_CSTIME_SP) +vmon_datum_longlong( cstime, PROC_STAT_CSTIME, "ChldSysCPU", "amount of time the waited-for children have spent in kernel mode (ticks)") +vmon_omit_run( ' ', PROC_STAT_PRIORITY_SP) +vmon_datum_longlong( priority, PROC_STAT_PRIORITY, "Priority", "priority of the process") +vmon_omit_run( ' ', PROC_STAT_NICE_SP) +vmon_datum_longlong( nice, PROC_STAT_NICE, "Nice", "nice value") +vmon_omit_run( ' ', PROC_STAT_NUM_THREADS_SP) +vmon_datum_longlong( num_threads, PROC_STAT_NUM_THREADS, "NumThreads", "number of threads") +vmon_omit_run( ' ', PROC_STAT_ALARM_SP) +vmon_omit_ulonglong( itrealvalue, PROC_STAT_ALARM, "NextAlarm", "the time in jiffies before the next SIGALRM is sent (not maintained)") +vmon_omit_run( ' ', PROC_STAT_START_SP) +vmon_datum_ulonglong( start, PROC_STAT_START, "StartTime", "start time relative to system boot in jiffies") +vmon_omit_run( ' ', PROC_STAT_VSIZE_SP) +vmon_datum_ulonglong( vsize, PROC_STAT_VSIZE, "VirtSize", "virtual memory size (bytes)") +vmon_omit_run( ' ', PROC_STAT_RSS_SP) +vmon_datum_ulonglong( rss, PROC_STAT_RSS, "ResSize", "resident set size (bytes)") +vmon_omit_run( ' ', PROC_STAT_RSSLIM_SP) +vmon_datum_ulonglong( rsslim, PROC_STAT_RSSLIM, "ResSizeLimit", "resident set size ulimit") +vmon_omit_run( ' ', PROC_STAT_STARTCODE_SP) +vmon_omit_ulonglong( startcode, PROC_STAT_STARTCODE, "CodeStart", "address above which program text can run") +vmon_omit_run( ' ', PROC_STAT_ENDCODE_SP) +vmon_omit_ulonglong( endcode, PROC_STAT_ENDCODE, "CodeEnd", "address below which program text can run") +vmon_omit_run( ' ', PROC_STAT_STARTSTACK_SP) +vmon_omit_ulonglong( startstack, PROC_STAT_STARTSTACK, "StackStart", "address of the stack start") +vmon_omit_run( ' ', PROC_STAT_ESP_SP) +vmon_omit_ulonglong( kstkesp, PROC_STAT_ESP, "StackPtr", "current stack pointer") +vmon_omit_run( ' ', PROC_STAT_EIP_SP) +vmon_omit_ulonglong( kstkeip, PROC_STAT_EIP, "InstructnPtr", "current instruction pointer") +vmon_omit_run( ' ', PROC_STAT_SIGNAL_SP) +vmon_omit_ulonglong( signal, PROC_STAT_SIGNAL, "SigsPending", "bitmap of pending signals") +vmon_omit_run( ' ', PROC_STAT_SIGBLOCKED_SP) +vmon_omit_ulonglong( blocked, PROC_STAT_SIGBLOCKED, "SigsBlocked", "bitmap of blocked signals") +vmon_omit_run( ' ', PROC_STAT_SIGIGNORED_SP) +vmon_omit_ulonglong( ignored, PROC_STAT_SIGIGNORED, "SigsIgnored", "bitmap of ignored signals") +vmon_omit_run( ' ', PROC_STAT_SIGCAUGHT_SP) +vmon_omit_ulonglong( caught, PROC_STAT_SIGCAUGHT, "SigsCaught", "bitmap of caughtsignals") +vmon_omit_run( ' ', PROC_STAT_WCHAN_ADDR_SP) +vmon_datum_ulonglong( wchan_addr, PROC_STAT_WCHAN_ADDR, "WchanAddr", "address of the process' wchan") +vmon_omit_run( ' ', PROC_STAT_SWAPPED_SP) +vmon_omit_ulonglong( nswap, PROC_STAT_SWAPPED, "NumSwapped", "number of pages swapped (not maintained)") +vmon_omit_run( ' ', PROC_STAT_CSWAPPED_SP) +vmon_omit_ulonglong( cnswap, PROC_STAT_CSWAPPED, "ChldNumSwpd", "number of cumulative pages swapped for children (not maintained)") +vmon_omit_run( ' ', PROC_STAT_EXITSIGNAL_SP) +vmon_omit_longlong( exit_signal, PROC_STAT_EXITSIGNAL, "ExitSignal", "signal to be sent to parent when we die") +vmon_omit_run( ' ', PROC_STAT_PROCESSOR_SP) +vmon_datum_longlong( processor, PROC_STAT_PROCESSOR, "LastCPU", "CPU number last executed on") +vmon_omit_run( ' ', PROC_STAT_RT_PRIORITY_SP) +vmon_omit_ulonglong( rt_priority, PROC_STAT_RT_PRIORITY, "RTPriority", "realtime priority of the process") +vmon_omit_run( ' ', PROC_STAT_POLICY_SP) +vmon_omit_ulonglong( policy, PROC_STAT_POLICY, "SchedPolicy", "scheduling policy of the process") +vmon_omit_run( ' ', PROC_STAT_DELAY_BLKIO_SP) +vmon_datum_ulonglong( delay_blkio, PROC_STAT_DELAY_BLKIO, "BlkIODelays", "aggregated block IO delays, in ticks") +vmon_omit_run( ' ', PROC_STAT_GUEST_TIME_SP) +vmon_datum_ulonglong( guest_time, PROC_STAT_GUEST_TIME, "GuestTime", "time spent running a virtual cpu for a guest OS") +vmon_omit_run( ' ', PROC_STAT_CGUEST_TIME_SP) +vmon_datum_longlong( cguest_time, PROC_STAT_CGUEST_TIME, "ChldGuestTim", "time spent running a virtual cpu for a guest OS in (waited for?) children") + +#include "_end.def" diff --git a/src/libvmon/defs/proc_vm.def b/src/libvmon/defs/proc_vm.def new file mode 100644 index 0000000..9028272 --- /dev/null +++ b/src/libvmon/defs/proc_vm.def @@ -0,0 +1,19 @@ +#include "_begin.def" + + /* member name, symbolic constant, human label, human description (think UI/help) */ + /* /proc/$pid/statm */ +vmon_datum_ulonglong( size_pages, PROC_VM_SIZE_PAGES, "Size", "Size in pages") +vmon_omit_run( ' ', PROC_VM_RESIDENT_PAGES_SP) +vmon_datum_ulonglong( resident_pages, PROC_VM_RESIDENT_PAGES, "Resident", "Resident set size in pages") +vmon_omit_run( ' ', PROC_VM_SHARED_PAGES_SP) +vmon_datum_ulonglong( shared_pages, PROC_VM_SHARED_PAGES, "Shared", "Shared size in pages") +vmon_omit_run( ' ', PROC_VM_TEXT_PAGES_SP) +vmon_datum_ulonglong( text_pages, PROC_VM_TEXT_PAGES, "Text", "Text segment size in pages") +vmon_omit_run( ' ', PROC_VM_LIB_PAGES_SP) +vmon_omit_ulonglong( lib_pages, PROC_VM_LIB_PAGES, "Library", "Library segment size (skipped, unused in 2.6)") +vmon_omit_run( ' ', PROC_VM_DATA_PAGES_SP) +vmon_datum_ulonglong( data_pages, PROC_VM_DATA_PAGES, "Data", "Data segment size in pages") +vmon_omit_run( ' ', PROC_VM_DIRTY_PAGES_SP) +vmon_omit_ulonglong( dirty_pages, PROC_VM_DIRTY_PAGES, "Dirty", "Dirtied (skipped, unused in 2.6)") + +#include "_end.def" diff --git a/src/libvmon/defs/proc_wants.def b/src/libvmon/defs/proc_wants.def new file mode 100644 index 0000000..7f02602 --- /dev/null +++ b/src/libvmon/defs/proc_wants.def @@ -0,0 +1,14 @@ +#include "_begin.def" + +/* the available per-process wants, the order here matters, put wants which affect the sampling heirarchy first */ +/* otherwise they will change the heirarchy after samples have been collected, leaving newly introduced nodes with uninitialized sample stores after return from vmon_sample() */ + +/* sym, name, internal fulfilllment function */ +vmon_want(PROC_FOLLOW_CHILDREN, proc_follow_children, proc_follow_children) +vmon_want(PROC_FOLLOW_THREADS, proc_follow_threads, proc_follow_threads) +vmon_want(PROC_FILES, proc_files, proc_sample_files) +vmon_want(PROC_STAT, proc_stat, proc_sample_stat) +vmon_want(PROC_VM, proc_vm, proc_sample_vm) +vmon_want(PROC_IO, proc_io, proc_sample_io) + +#include "_end.def" diff --git a/src/libvmon/defs/sys_stat.def b/src/libvmon/defs/sys_stat.def new file mode 100644 index 0000000..ef8b9a7 --- /dev/null +++ b/src/libvmon/defs/sys_stat.def @@ -0,0 +1,114 @@ +#include "_begin.def" + + /* member name, symbolic constant, human label, human description (think UI/help) */ + /* /proc/stat */ + +/* a cpu row, this is shown once for the total prefixed with "cpu ", then again for every cpu prefixed with "cpuN ", newlines terminate rows */ +vmon_omit_n( 5, SYS_STAT_CPU_PREFIX, "cpu line \"cpu \" prefix") +vmon_datum_ulonglong( user, SYS_STAT_CPU_USER, "UserTime", "Time spent in user mode (ticks)") +vmon_omit_run( ' ', SYS_STAT_CPU_NICE_SP) +vmon_datum_ulonglong( nice, SYS_STAT_CPU_NICE, "NiceTime", "Time spent in user mode with low priority (ticks)") +vmon_omit_run( ' ', SYS_STAT_CPU_SYS_SP) +vmon_datum_ulonglong( system, SYS_STAT_CPU_SYS, "SysTime", "Time spent in system mode (ticks)") +vmon_omit_run( ' ', SYS_STAT_CPU_IDLE_SP) +vmon_datum_ulonglong( idle, SYS_STAT_CPU_IDLE, "IdleTime", "Time spent in the idle task (ticks)") +vmon_omit_run( ' ', SYS_STAT_CPU_IOWAIT_SP) +vmon_datum_ulonglong( iowait, SYS_STAT_CPU_IOWAIT, "IOWaitTime", "Time spent runnable but waiting for IO (ticks)") +vmon_omit_run( ' ', SYS_STAT_CPU_IRQ_SP) +vmon_datum_ulonglong( irq, SYS_STAT_CPU_IRQ, "IRQTime", "Time spent in IRQ context (ticks)") +vmon_omit_run( ' ', SYS_STAT_CPU_SIRQ_SP) +vmon_datum_ulonglong( softirq, SYS_STAT_CPU_SIRQ, "SoftIRQTime", "Time spent in the softirq context (ticks)") +vmon_omit_run( ' ', SYS_STAT_CPU_STEAL_SP) +vmon_datum_ulonglong( steal, SYS_STAT_CPU_STEAL, "StealTime", "Time spent in a virtualized environment (ticks)") +vmon_omit_run( ' ', SYS_STAT_CPU_GUEST_SP) +vmon_datum_ulonglong( guest, SYS_STAT_CPU_GUEST, "GuestTime", "Time spent in a virtual cpu (ticks)") +vmon_omit_literal( "\n", SYS_STAT_CPU_NL) + + + + +#if 0 +/* here we want to embed a list of a cpus, the cpu entries need to be a composite type which needs */ + +/* TODO: the rest of /proc/stat, need to develop the macro language further to cleanly support the variable structures like N cpu rows etc... */ +vmon_heredef_list_begin( cpus, SYS_STAT_CPUS, "CPUs", "CPU time accounts for every cpu in the system") +/* we probably should somehow express which field is to be used as an index for addressing the array elements (and growing as needed) */ +vmon_omit_n( 5, SYS_STAT_PERCPU_PREFIX, "cpu line \"cpu \" prefix") +vmon_datum_ulonglong( user, SYS_STAT_PERCPU_USER, "UserTime", "Time spent in user mode (ticks)") +vmon_omit_run( ' ', SYS_STAT_PERCPU_NICE_SP) +vmon_datum_ulonglong( nice, SYS_STAT_PERCPU_NICE, "NiceTime", "Time spent in user mode with low priority (ticks)") +vmon_omit_run( ' ', SYS_STAT_PERCPU_SYS_SP) +vmon_datum_ulonglong( system, SYS_STAT_PERCPU_SYS, "SysTime", "Time spent in system mode (ticks)") +vmon_omit_run( ' ', SYS_STAT_PERCPU_IDLE_SP) +vmon_datum_ulonglong( idle, SYS_STAT_PERCPU_IDLE, "IdleTime", "Time spent in the idle task (ticks)") +vmon_omit_run( ' ', SYS_STAT_PERCPU_IOWAIT_SP) +vmon_datum_ulonglong( iowait, SYS_STAT_PERCPU_IOWAIT, "IOWaitTime", "Time spent runnable but waiting for IO (ticks)") +vmon_omit_run( ' ', SYS_STAT_PERCPU_IRQ_SP) +vmon_datum_ulonglong( irq, SYS_STAT_PERCPU_IRQ, "IRQTime", "Time spent in IRQ context (ticks)") +vmon_omit_run( ' ', SYS_STAT_PERCPU_SIRQ_SP) +vmon_datum_ulonglong( softirq, SYS_STAT_PERCPU_SIRQ, "SoftIRQTime", "Time spent in the softirq context (ticks)") +vmon_omit_run( ' ', SYS_STAT_PERCPU_STEAL_SP) +vmon_datum_ulonglong( steal, SYS_STAT_PERCPU_STEAL, "StealTime", "Time spent in a virtualized environment (ticks)") +vmon_omit_run( ' ', SYS_STAT_PERCPU_GUEST_SP) +vmon_datum_ulonglong( guest, SYS_STAT_PERCPU_GUEST, "GuestTime", "Time spent in a virtual cpu (ticks)") +vmon_omit_literal( "\n", SYS_STAT_PERCPU_NL) +vmon_heredef_list_end( cpus, SYS_STAT_CPUS) + +/* we make the interrupts array dynamic, which is kind of annoying, since in older/simple XT-PIC systems it could be simply an array of 16 elements, + and the calling code could have made assumptions about the layout. Taking this approach to accomodate modern systems also forces calling code to + be more indirect about accessing the members of this array, less assumptions can be made, such is life. I considered using a simple static array with + named directly-accessible members in the CONFIG_GENERIC_HARDIRQS case, but that would encourage creating programs dependent on that case which would + then not work unmodified on the newer (and more common, now) complicated irq routing case. :( + */ +vmon_omit_literal("intr", SYS_STAT_IRQS_PREFIX) +vmon_heredef_array_begin( irqs, SYS_STAT_IRQS, "IRQs", "Counters for all interrupts in the system") +vmon_omit_literal(" ", SYS_STAT_IRQS_SP) +vmon_datum_ulonglong( count, SYS_STAT_PERIRQ_COUNT) +vmon_heredef_array_end( irqs, SYS_STAT_IRQS) +vmon_omit_literal("\n", SYS_STAT_IRQS_NL) + +vmon_omit_literal("ctxt ", SYS_STAT_CTXT_SWITCHES_PREFIX) +vmon_datum_ulonglong( ctxt, SYS_STAT_CTXT_SWITCHES, "CXs", "Count of context switches since boot") +vmon_omit_literal("\n", SYS_STAT_CTXT_SWITCHES_NL) + +vmon_omit_literal("btime ", SYS_STAT_BOOTTIME_PREFIX) +vmon_datum_ulong( boot_time, SYS_STAT_BOOTTIME, "BootTime", "Number of seconds since epoch the system booted at") +vmon_omit_literal("\n", SYS_STAT_BOOTTIME_NL) + +vmon_omit_literal("processes ", SYS_STAT_FORKS_PREFIX) +vmon_datum_ulong( forks, SYS_STAT_FORKS, "Forks", "Number of forks since the system booted") +vmon_omit_literal("\n", SYS_STAT_FORKS_NL) + +vmon_omit_literal("procs_running ", SYS_STAT_NRUNNABLE_PREFIX) +vmon_datum_ulong( n_runnable, SYS_STAT_NRUNNABLE, "NumRunnable", "Number of processes currently runnable (may exceed number of cpus)") +vmon_omit_literal("\n", SYS_STAT_NRUNNABLE_NL) + +vmon_omit_literal("procs_blocked ", SYS_STAT_NBLOCKED_PREFIX) +vmon_datum_ulong( n_blocked, SYS_STAT_NBLOCKED, "NumBlocked", "Number of processes currently blocked") +vmon_omit_literal("\n", SYS_STAT_NBLOCKED_NL) + +vmon_omit_literal("softirq ", SYS_STAT_SIRQS_PREFIX) +vmon_datum_ulonglong( sirq_hi, SYS_STAT_SIRQ_HI, "HiSIRQ", "Number of high priority soft interrupts (HI_SOFTIRQ)") +vmon_omit_literal(" ", SYS_STAT_SIRQ_TIMER_SP) +vmon_datum_ulonglong( sirq_timer, SYS_STAT_SIRQ_TIMER, "TimerSIRQ", "Number of timer software interrupts (TIMER_SOFTIRQ)") +vmon_omit_literal(" ", SYS_STAT_SIRQ_NET_TX_SP) +vmon_datum_ulonglong( sirq_net_tx, SYS_STAT_SIRQ_NET_TX, "NetTxSIRQ", "Number of network transmit software interrupts (NET_TX_SOFTIRQ)") +vmon_omit_literal(" ", SYS_STAT_SIRQ_NET_RX_SP) +vmon_datum_ulonglong( sirq_net_rx, SYS_STAT_SIRQ_NET_RX, "NetRxSIRQ", "Number of network receive software interrupts (NET_RX_SOFTIRQ)") +vmon_omit_literal(" ", SYS_STAT_SIRQ_BLOCK_SP) +vmon_datum_ulonglong( sirq_block, SYS_STAT_SIRQ_BLOCK, "BlockSIRQ", "Number of block software interrupts (BLOCK_SOFTIRQ)") +vmon_omit_literal(" ", SYS_STAT_SIRQ_IOPOLL_SP) +vmon_datum_ulonglong( sirq_iopoll, SYS_STAT_SIRQ_IOPOLL, "IOPollSIRQ", "Number of block IO poll software interrupts (BLOCK_IOPOLL_SOFTIRQ)") +vmon_omit_literal(" ", SYS_STAT_SIRQ_TASKLET_SP) +vmon_datum_ulonglong( sirq_tasklet, SYS_STAT_SIRQ_TASKLET, "TaskletSIRQ", "Number of tasklet software interrupts (TASKLET SOFTIRQ)") +vmon_omit_literal(" ", SYS_STAT_SIRQ_HRTIMER_SP) +vmon_datum_ulonglong( sirq_hrtimer, SYS_STAT_SIRQ_HRTIMER, "HRTimerSIRQ", "Number of hrtimer software interrupts (HRTIMER_SOFTIRQ)") +vmon_omit_literal(" ", SYS_STAT_SIRQ_RCU_SP) +vmon_datum_ulonglong( sirq_rcu, SYS_STAT_SIRQ_RCU, "RCUSIRQ", "Number of RCU software interrupts (RCU_SOFTIRQ)") +vmon_omit_literal("\n", SYS_STAT_SIRQS_NL) + + +#endif + + +#include "_end.def" diff --git a/src/libvmon/defs/sys_vm.def b/src/libvmon/defs/sys_vm.def new file mode 100644 index 0000000..33b4d3f --- /dev/null +++ b/src/libvmon/defs/sys_vm.def @@ -0,0 +1,169 @@ +#include "_begin.def" + + + /* member name, symbolic constant, human label, human description (think UI/help) */ + /* /proc/meminfo */ +vmon_omit_literal("MemTotal:", SYS_VM_TOTAL_KB_LABEL) +vmon_omit_run(' ', SYS_VM_TOTAL_KB_WHITESPACE) +vmon_datum_ulong( total_kb, SYS_VM_TOTAL_KB, "Total", "Total memory in system") +vmon_omit_literal(" kB\n", SYS_VM_TOTAL_KB_UNIT_NL) +vmon_omit_literal("MemFree:", SYS_VM_FREE_KB_LABEL) +vmon_omit_run(' ', SYS_VM_FREE_KB_WHITESPACE) +vmon_datum_ulong( free_kb, SYS_VM_FREE_KB, "Free", "Free memory in system") +vmon_omit_literal(" kB\n", SYS_VM_FREE_KB_UNIT_NL) +vmon_omit_literal("Buffers:", SYS_VM_BUFFERS_KB_LABEL) +vmon_omit_run(' ', SYS_VM_BUFFERS_KB_WHITESPACE) +vmon_datum_ulong( buffers_kb, SYS_VM_BUFFERS_KB, "Buffers", "Memory allocated to buffers") +vmon_omit_literal(" kB\n", SYS_VM_BUFFERS_KB_UNIT_NL) +vmon_omit_literal("Cached:", SYS_VM_CACHED_KB_LABEL) +vmon_omit_run(' ', SYS_VM_CACHED_KB_WHITESPACE) +vmon_datum_ulong( cached_kb, SYS_VM_CACHED_KB, "Cached", "Memory allocated to caches") +vmon_omit_literal(" kB\n", SYS_VM_CACHED_KB_UNIT_NL) +vmon_omit_literal("SwapCached:", SYS_VM_SWAPCACHED_KB_LABEL) +vmon_omit_run(' ', SYS_VM_SWAPCACHED_KB_WHITESPACE) +vmon_datum_ulong( swapcached_kb, SYS_VM_SWAPCACHED_KB, "SwapCached", "Memory allocated to swap caches") +vmon_omit_literal(" kB\n", SYS_VM_SWAPCACHED_KB_UNIT_NL) +vmon_omit_literal("Active:", SYS_VM_ACTIVE_KB_LABEL) +vmon_omit_run(' ', SYS_VM_ACTIVE_KB_WHITESPACE) +vmon_datum_ulong( active_kb, SYS_VM_ACTIVE_KB, "Active", "Active pages") +vmon_omit_literal(" kB\n", SYS_VM_ACTIVE_KB_UNIT_NL) +vmon_omit_literal("Inactive:", SYS_VM_INACTIVE_KB_LABEL) +vmon_omit_run(' ', SYS_VM_INACTIVE_KB_WHITESPACE) +vmon_datum_ulong( inactive_kb, SYS_VM_INACTIVE_KB, "Inactive", "Inactive pages") +vmon_omit_literal(" kB\n", SYS_VM_INACTIVE_KB_UNIT_NL) +vmon_omit_literal("Active(anon):", SYS_VM_ANON_ACTIVE_KB_LABEL) +vmon_omit_run(' ', SYS_VM_ANON_ACTIVE_KB_WHITESPACE) +vmon_datum_ulong( anon_active_kb, SYS_VM_ANON_ACTIVE_KB, "AnonActive", "Active anonymous pages") +vmon_omit_literal(" kB\n", SYS_VM_ANON_ACTIVE_KB_UNIT_NL) +vmon_omit_literal("Inactive(anon):", SYS_VM_ANON_INACTIVE_KB_LABEL) +vmon_omit_run(' ', SYS_VM_ANON_INACTIVE_KB_WHITESPACE) +vmon_datum_ulong( anon_inactive_kb, SYS_VM_ANON_INACTIVE_KB, "AnonInactive", "Inactive anonymous pages") +vmon_omit_literal(" kB\n", SYS_VM_ANON_INACTIVE_KB_UNIT_NL) +vmon_omit_literal("Active(file):", SYS_VM_FILE_ACTIVE_KB_LABEL) +vmon_omit_run(' ', SYS_VM_FILE_ACTIVE_KB_WHITESPACE) +vmon_datum_ulong( file_active_kb, SYS_VM_FILE_ACTIVE_KB, "FileActive", "Active file pages") +vmon_omit_literal(" kB\n", SYS_VM_FILE_ACTIVE_KB_UNIT_NL) +vmon_omit_literal("Inactive(file):", SYS_VM_FILE_INACTIVE_KB_LABEL) +vmon_omit_run(' ', SYS_VM_FILE_INACTIVE_KB_WHITESPACE) +vmon_datum_ulong( file_inactive_kb, SYS_VM_FILE_INACTIVE_KB, "FileInactive", "Inactive file pages") +vmon_omit_literal(" kB\n", SYS_VM_FILE_INACTIVE_KB_UNIT_NL) +vmon_omit_literal("Unevictable:", SYS_VM_UNEVICTABLE_KB_LABEL) +vmon_omit_run(' ', SYS_VM_UNEVICTABLE_KB_WHITESPACE) +vmon_datum_ulong( unevictable_kb, SYS_VM_UNEVICTABLE_KB, "Unevictable", "Unevictable pages") +vmon_omit_literal(" kB\n", SYS_VM_UNEVICTABLE_KB_UNIT_NL) +vmon_omit_literal("Mlocked:", SYS_VM_MLOCKED_KB_LABEL) +vmon_omit_run(' ', SYS_VM_MLOCKED_KB_WHITESPACE) +vmon_datum_ulong( mlocked_kb, SYS_VM_MLOCKED_KB, "Mlocked", "Locked pages") +vmon_omit_literal(" kB\n", SYS_VM_MLOCKED_KB_UNIT_NL) +vmon_omit_literal("SwapTotal:", SYS_VM_SWAP_TOTAL_KB_LABEL) +vmon_omit_run(' ', SYS_VM_SWAP_TOTAL_KB_WHITESPACE) +vmon_datum_ulong( swap_total_kb, SYS_VM_SWAP_TOTAL_KB, "SwapTotal", "Total swap") +vmon_omit_literal(" kB\n", SYS_VM_SWAP_TOTAL_KB_UNIT_NL) +vmon_omit_literal("SwapFree:", SYS_VM_SWAP_FREE_KB_LABEL) +vmon_omit_run(' ', SYS_VM_SWAP_FREE_KB_WHITESPACE) +vmon_datum_ulong( swap_free_kb, SYS_VM_SWAP_FREE_KB, "SwapFree", "Free swap") +vmon_omit_literal(" kB\n", SYS_VM_SWAP_FREE_KB_UNIT_NL) +vmon_omit_literal("Dirty:", SYS_VM_DIRTY_KB_LABEL) +vmon_omit_run(' ', SYS_VM_DIRTY_KB_WHITESPACE) +vmon_datum_ulong( dirty_kb, SYS_VM_DIRTY_KB, "Dirty", "Dirty pages") +vmon_omit_literal(" kB\n", SYS_VM_DIRTY_KB_UNIT_NL) +vmon_omit_literal("Writeback:", SYS_VM_WRITEBACK_KB_LABEL) +vmon_omit_run(' ', SYS_VM_WRITEBACK_KB_WHITESPACE) +vmon_datum_ulong( writeback_kb, SYS_VM_WRITEBACK_KB, "Writeback", "Dirtied pages in the process of being written back") +vmon_omit_literal(" kB\n", SYS_VM_WRITEBACK_KB_UNIT_NL) +vmon_omit_literal("AnonPages:", SYS_VM_ANONPAGES_KB_LABEL) +vmon_omit_run(' ', SYS_VM_ANONPAGES_KB_WHITESPACE) +vmon_datum_ulong( anonpages_kb, SYS_VM_ANONPAGES_KB, "AnonPages", "Anonymous pages") +vmon_omit_literal(" kB\n", SYS_VM_ANONPAGES_KB_UNIT_NL) +vmon_omit_literal("Mapped:", SYS_VM_MAPPED_KB_LABEL) +vmon_omit_run(' ', SYS_VM_MAPPED_KB_WHITESPACE) +vmon_datum_ulong( mapped_kb, SYS_VM_MAPPED_KB, "Mapped", "Mapped pages") +vmon_omit_literal(" kB\n", SYS_VM_MAPPED_KB_UNIT_NL) +vmon_omit_literal("Shmem:", SYS_VM_SHMEM_KB_LABEL) +vmon_omit_run(' ', SYS_VM_SHMEM_KB_WHITESPACE) +vmon_datum_ulong( shmem_kb, SYS_VM_SHMEM_KB, "Shmem", "SysV IPC shmem") +vmon_omit_literal(" kB\n", SYS_VM_SHMEM_KB_UNIT_NL) +vmon_omit_literal("Slab:", SYS_VM_SLAB_KB_LABEL) +vmon_omit_run(' ', SYS_VM_SLAB_KB_WHITESPACE) +vmon_datum_ulong( slab_kb, SYS_VM_SLAB_KB, "Slab", "Slab memory") +vmon_omit_literal(" kB\n", SYS_VM_SLAB_KB_UNIT_NL) +vmon_omit_literal("SReclaimable:", SYS_VM_SRECLAIMABLE_KB_LABEL) +vmon_omit_run(' ', SYS_VM_SRECLAIMABLE_KB_WHITESPACE) +vmon_datum_ulong( sreclaimable_kb, SYS_VM_SRECLAIMABLE_KB, "SReclaimable", "Slab (reclaimable) memory") +vmon_omit_literal(" kB\n", SYS_VM_SRECLAIMABLE_KB_UNIT_NL) +vmon_omit_literal("SUnreclaim:", SYS_VM_SUNRECLAIMABLE_KB_LABEL) +vmon_omit_run(' ', SYS_VM_SUNRECLAIMABLE_KB_WHITESPACE) +vmon_datum_ulong( sunreclaimable_kb, SYS_VM_SUNRECLAIMABLE_KB, "SUnreclaim", "Slab (unreclaimable) memory") +vmon_omit_literal(" kB\n", SYS_VM_SUNRECLAIMABLE_KB_UNIT_NL) +vmon_omit_literal("KernelStack:", SYS_VM_KERNELSTACK_KB_LABEL) +vmon_omit_run(' ', SYS_VM_KERNELSTACK_KB_WHITESPACE) +vmon_datum_ulong( kernelstack_kb, SYS_VM_KERNELSTACK_KB, "KernelStack", "Kernel stack") +vmon_omit_literal(" kB\n", SYS_VM_KERNELSTACK_KB_UNIT_NL) +vmon_omit_literal("PageTables:", SYS_VM_PAGETABLES_KB_LABEL) +vmon_omit_run(' ', SYS_VM_PAGETABLES_KB_WHITESPACE) +vmon_datum_ulong( pagetables_kb, SYS_VM_PAGETABLES_KB, "PageTables", "Page tables") +vmon_omit_literal(" kB\n", SYS_VM_PAGETABLES_KB_UNIT_NL) +vmon_omit_literal("NFS_Unstable:", SYS_VM_NFS_UNSTABLE_KB_LABEL) +vmon_omit_run(' ', SYS_VM_NFS_UNSTABLE_KB_WHITESPACE) +vmon_datum_ulong( nfs_unstable_kb, SYS_VM_NFS_UNSTABLE_KB, "NFS_Unstable", "NFS unstable") +vmon_omit_literal(" kB\n", SYS_VM_NFS_UNSTABLE_KB_UNIT_NL) +vmon_omit_literal("Bounce:", SYS_VM_BOUNCE_KB_LABEL) +vmon_omit_run(' ', SYS_VM_BOUNCE_KB_WHITESPACE) +vmon_datum_ulong( bounce_kb, SYS_VM_BOUNCE_KB, "Bounce", "Bounce") +vmon_omit_literal(" kB\n", SYS_VM_BOUNCE_KB_UNIT_NL) +vmon_omit_literal("WritebackTmp:", SYS_VM_WRITEBACKTMP_KB_LABEL) +vmon_omit_run(' ', SYS_VM_WRITEBACKTMP_KB_WHITESPACE) +vmon_datum_ulong( writebacktmp_kb, SYS_VM_WRITEBACKTMP_KB, "WritebackTmp", "Writeback temp") +vmon_omit_literal(" kB\n", SYS_VM_WRITEBACKTMP_KB_UNIT_NL) +vmon_omit_literal("CommitLimit:", SYS_VM_COMMITLIMIT_KB_LABEL) +vmon_omit_run(' ', SYS_VM_COMMITLIMIT_KB_WHITESPACE) +vmon_datum_ulong( commitlimit_kb, SYS_VM_COMMITLIMIT_KB, "CommitLimit", "Commit limit") +vmon_omit_literal(" kB\n", SYS_VM_COMMITLIMIT_KB_UNIT_NL) +vmon_omit_literal("Committed_AS:", SYS_VM_COMMITTED_AS_KB_LABEL) +vmon_omit_run(' ', SYS_VM_COMMITTED_AS_KB_WHITESPACE) +vmon_datum_ulong( commited_as_kb, SYS_VM_COMMITTED_AS_KB, "Commited_AS", "Commited address space? TODO ") +vmon_omit_literal(" kB\n", SYS_VM_COMMITTED_AS_KB_UNIT_NL) +vmon_omit_literal("VmallocTotal:", SYS_VM_VMALLOC_TOTAL_KB_LABEL) +vmon_omit_run(' ', SYS_VM_VMALLOC_KB_WHITESPACE) +vmon_datum_ulong( vmalloctotal_kb, SYS_VM_VMALLOC_TOTAL_KB, "VmallocTotal", "Vmalloc total") +vmon_omit_literal(" kB\n", SYS_VM_VMALLOC_TOTAL_KB_UNIT_NL) +vmon_omit_literal("VmallocUsed:", SYS_VM_VMALLOC_USED_KB_LABEL) +vmon_omit_run(' ', SYS_VM_VMALLOC_USED_KB_WHITESPACE) +vmon_datum_ulong( vmallocused_kb, SYS_VM_VMALLOC_USED_KB, "VmallocUsed", "Vmalloc used") +vmon_omit_literal(" kB\n", SYS_VM_VMALLOC_USED_KB_UNIT_NL) +vmon_omit_literal("VmallocChunk:", SYS_VM_VMALLOC_CHUNK_KB_LABEL) +vmon_omit_run(' ', SYS_VM_VMALLOC_CHUNK_KB_WHITESPACE) +vmon_datum_ulong( vmallocchunk_kb, SYS_VM_VMALLOC_CHUNK_KB, "VmallocChunk", "Vmalloc chunk") +vmon_omit_literal(" kB\n", SYS_VM_VMALLOC_CHUNK_KB_UNIT_NL) +vmon_omit_literal("HugePages_Total:", SYS_VM_HUGEPAGES_TOTAL_LABEL) +vmon_omit_run(' ', SYS_VM_HUGEPAGES_TOTAL_WHITESPACE) +vmon_datum_ulong( hugepages_total, SYS_VM_HUGEPAGES_TOTAL, "HugePages_Total", "HugePages total") +vmon_omit_literal("\n", SYS_VM_HUGEPAGES_TOTAL_NL) +vmon_omit_literal("HugePages_Free:", SYS_VM_HUGEPAGES_FREE_LABEL) +vmon_omit_run(' ', SYS_VM_HUGEPAGES_FREE_WHITESPACE) +vmon_datum_ulong( hugepages_free, SYS_VM_HUGEPAGES_FREE, "HugePages_Free", "HugePages free") +vmon_omit_literal("\n", SYS_VM_HUGEPAGES_FREE_NL) +vmon_omit_literal("HugePages_Rsvd:", SYS_VM_HUGEPAGES_RESERVED_LABEL) +vmon_omit_run(' ', SYS_VM_HUGEPAGES_RESERVED_WHITESPACE) +vmon_datum_ulong( hugepages_reserved, SYS_VM_HUGEPAGES_RESERVED, "HugePages_Rsvd", "HugePages reserved") +vmon_omit_literal("\n", SYS_VM_HUGEPAGES_RESERVED_UNIT_NL) +vmon_omit_literal("HugePages_Surp:", SYS_VM_HUGEPAGES_SURPLUS_LABEL) +vmon_omit_run(' ', SYS_VM_HUGEPAGES_SURPLUS_WHITESPACE) +vmon_datum_ulong( hugepages_surplus, SYS_VM_HUGEPAGES_SURPLUS, "HugePages_Surp", "HugePages surplus") +vmon_omit_literal("\n", SYS_VM_HUGEPAGES_SURPLUS_NL) +vmon_omit_literal("Hugepagesize:", SYS_VM_HUGEPAGE_SIZE_KB_LABEL) +vmon_omit_run(' ', SYS_VM_HUGEPAGE_SIZE_KB_WHITESPACE) +vmon_datum_ulong( hugepage_size_kb, SYS_VM_HUGEPAGE_SIZE_KB, "HugePage_Size", "HugePage page size") +vmon_omit_literal(" kB\n", SYS_VM_HUGEPAGE_SIZE_KB_UNIT_NL) +vmon_omit_literal("DirectMap4k:", SYS_VM_DIRECTMAP_4K_KB_LABEL) +vmon_omit_run(' ', SYS_VM_DIRECTMAP_4K_KB_WHITESPACE) +vmon_datum_ulong( directmap4k_kb, SYS_VM_DIRECTMAP_4K_KB, "DirectMap4k", "DirectMap 4K") +vmon_omit_literal(" kB\n", SYS_VM_DIRECTMAP_4K_KB_UNIT_NL) +vmon_omit_literal("DirectMap4M:", SYS_VM_DIRECTMAP_4M_KB_LABEL) +vmon_omit_run(' ', SYS_VM_DIRECTMAP_4M_KB_WHITESPACE) +vmon_datum_ulong( directmap2m_kb, SYS_VM_DIRECTMAP_4M_KB, "DirectMap4M", "DirectMap 4M") +vmon_omit_literal(" kB\n", SYS_VM_DIRECTMAP_4M_KB_UNIT_NL) + +/* TODO: /proc/vmstat */ + +#include "_end.def" diff --git a/src/libvmon/defs/sys_wants.def b/src/libvmon/defs/sys_wants.def new file mode 100644 index 0000000..750d7bb --- /dev/null +++ b/src/libvmon/defs/sys_wants.def @@ -0,0 +1,7 @@ +#include "_begin.def" + +/* the available sys-wide wants */ +vmon_want(SYS_STAT, sys_stat, sys_sample_stat) +vmon_want(SYS_VM, sys_vm, sys_sample_vm) + +#include "_end.def" diff --git a/src/libvmon/vmon.c b/src/libvmon/vmon.c new file mode 100644 index 0000000..7d2b2a0 --- /dev/null +++ b/src/libvmon/vmon.c @@ -0,0 +1,1634 @@ +/* + * libvmon - a lightweight linux system/process monitoring library, + * intended for linking directly into gpl programs. + * + * This has been written specifically for use in vwm, my window manager, + * but includes some facilities for other uses. + * + * Copyright (c) 2012-2014 Vito Caputo - + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 3 as + * published by the Free Software Foundation. + * + * 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 . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "list.h" + +#include "vmon.h" + +#define VMON_INTERNAL_PROC_IS_THREAD (1L << 31) /* used to communicate to vmon_proc_monitor() that the pid is a tid */ + +/* valid return values for the sampler functions, these are private to the library */ +typedef enum _sample_ret_t { + SAMPLE_CHANGED, /* this sampler invocation has changes */ + SAMPLE_UNCHANGED, /* this sampler invocation has no changes */ + SAMPLE_ERROR, /* this sampler invocation encountered errors (XXX it may be interesting to support indicating changing & errors) */ + DTOR_FREE, /* this dtor(sampler) invocation wants the caller to free the store */ + DTOR_NOFREE /* this dtor(sampler) invocation does not want the caller to perform a free on the store */ +} sample_ret_t; + + +/* some private convenience functions */ +static void try_free(void **ptr) +{ + if((*ptr)) { + free((*ptr)); + (*ptr) = NULL; + } +} + + +static void try_close(int *fd) +{ + if((*fd) != -1) { + close((*fd)); + (*fd) = -1; + } +} + + +static void try_closedir(DIR **dir) +{ + if((*dir)) { + closedir((*dir)); + (*dir) = NULL; + } +} + + +/* these have been wrapped to suppress syscall overhead when we have a bad file descriptor without cluttering the samplers with checks */ +static off_t try_lseek(int fd, off_t offset, int whence) +{ + if(fd != -1) { + return lseek(fd, offset, whence); + } else { + errno = EBADF; + return fd; + } +} + + +static ssize_t try_read(int fd, void *buf, size_t count) +{ + if(fd != -1) { + return read(fd, buf, count); + } else { + errno = EBADF; + return fd; + } +} + + +/* this does a copy from src to dest + * sets the bit specified by changed_pos in the bitmap *changed if what was copied to src was different from what was already there */ +static void memcmpcpy(void *dest, const void *src, size_t n, char *changed, int changed_pos) +{ + size_t i = 0; + + /* if the changed bit is set on entry we don't execute the comparison-copy */ + if(!BITTEST(changed, changed_pos)) { + /* a simple slow compare and copy loop, break out if we've found a change */ + /* XXX TODO: an obvious optimization would be to compare and copy words at a time... */ + for(; i < n; i++) { + if(((char *)dest)[i] != ((char *)src)[i]) { + BITSET(changed, changed_pos); + break; + } + ((char *)dest)[i] = ((char *)src)[i]; + } + } + + /* memcpy whatever remains */ + if(n - i) { + memcpy(&((char *)dest)[i], &((char *)src)[i], n - i); + } +} + + +typedef enum _vmon_load_flags_t { + LOAD_FLAGS_NONE = 0, + LOAD_FLAGS_NOTRUNCATE = 1L +} vmon_load_flags_t; + +/* we enlarge *alloc if necessary, but never shrink it. changed[changed_pos] bit is set if a difference is detected, supply LOAD_FLAGS_NOTRUNCATE if we don't want empty contents to truncate last-known data */ +static char * load_contents_fd(vmon_t *vmon, vmon_char_array_t *array, int fd, vmon_load_flags_t flags, char *changed, int changed_pos) +{ + int total = 0, len, alloc_len = array->alloc_len; + char *alloc = array->array, *tmp; + + while((len = read(fd, vmon->buf, sizeof(vmon->buf))) > 0) { + if(total + len > alloc_len) { + /* realloc to accomodate the new total */ + tmp = realloc(alloc, total + len); + if(!tmp) { + return NULL; + } + + alloc_len = total + len; + alloc = tmp; + } + + memcmpcpy(&alloc[total], vmon->buf, len, changed, changed_pos); + + total += len; + } + + array->array = alloc; + array->alloc_len = alloc_len; + + /* if we read something or didn't encounter an error, store the new total */ + if(total || (len == 0 && !(flags & LOAD_FLAGS_NOTRUNCATE))) { + /* if the new length differs ensure the changed bit is set */ + if(array->len != total) { + BITSET(changed, changed_pos); + } + + array->len = total; + } + + return alloc; +} + + +/* convenience function for opening a path using a format string, path is temporarily assembled in vmon->buf */ +static int openf(vmon_t *vmon, int flags, DIR *dir, char *fmt, ...) +{ + int fd; + va_list va_arg; + + va_start(va_arg, fmt); + vsnprintf(vmon->buf, sizeof(vmon->buf), fmt, va_arg); /* XXX accepting the possibility of truncating the path */ + va_end(va_arg); + + fd = openat(dirfd(dir), vmon->buf, flags); + + return fd; +} + + +/* convenience function for opening a directory using a format string, path is temporarily assembled in vmon->buf */ +static DIR * opendirf(vmon_t *vmon, DIR *dir, char *fmt, ...) +{ + int fd; + va_list va_arg; + + va_start(va_arg, fmt); + vsnprintf(vmon->buf, sizeof(vmon->buf), fmt, va_arg); /* XXX accepting the possibility of truncating the path */ + va_end(va_arg); + + fd = openat(dirfd(dir), vmon->buf, O_RDONLY); + if(fd == -1) { + return NULL; + } + + return fdopendir(fd); +} + + +/* enlarge an array by the specified amount */ +static int grow_array(vmon_char_array_t *array, int amount) +{ + char *tmp; + + tmp = realloc(array->array, array->alloc_len + amount); + if(!tmp) { + return 0; + } + + array->alloc_len += amount; + array->array = tmp; + + return 1; +} + + +/* load the contents of a symlink, dir is not optional */ +#define READLINKF_GROWINIT 10 +#define READLINKF_GROWBY 2 +static char * readlinkf(vmon_t *vmon, vmon_char_array_t *array, DIR *dir, char *fmt, ...) +{ + va_list va_arg; + int len; + + va_start(va_arg, fmt); + vsnprintf(vmon->buf, sizeof(vmon->buf), fmt, va_arg); + va_end(va_arg); + + if(!array->array && !grow_array(array, READLINKF_GROWINIT)) { + goto _fail; + } + + do { + len = readlinkat(dirfd(dir), vmon->buf, array->array, (array->alloc_len - 1)); + } while(len != -1 && len == (array->alloc_len - 1) && (len = grow_array(array, READLINKF_GROWBY))); + + if(len <= 0) { + goto _fail; + } + + array->len = len; + array->array[array->len] = '\0'; + + return array->array; + +_fail: + return NULL; +} + + +/* here starts private per-process samplers and other things like following children implementation etc. */ + +/* sample stat process stats */ +typedef enum _vmon_proc_stat_fsm_t { +#define VMON_ENUM_PARSER_STATES +#include "defs/proc_stat.def" +} vmon_proc_stat_fsm_t; + +static sample_ret_t proc_sample_stat(vmon_t *vmon, vmon_proc_t *proc, vmon_proc_stat_t **store) +{ + int changes = 0; + int i, len; + char *arg; + int argn, prev_argc; + vmon_proc_stat_fsm_t state = VMON_PARSER_STATE_PROC_STAT_PID; +#define VMON_PREPARE_PARSER +#include "defs/proc_stat.def" + + if(!proc) { /* dtor */ + try_close(&(*store)->comm_fd); + try_free((void **)&(*store)->comm); + try_close(&(*store)->cmdline_fd); + try_free((void **)&(*store)->cmdline); + try_close(&(*store)->wchan_fd); + try_close(&(*store)->stat_fd); + try_free((void **)&(*store)->exe); + + return DTOR_FREE; + } + +_retry: + if(!(*store)) { /* ctor */ + + *store = calloc(1, sizeof(vmon_proc_stat_t)); + + if(proc->is_thread) { + (*store)->comm_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/task/%i/comm", proc->pid, proc->pid); + (*store)->cmdline_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/task/%i/cmdline", proc->pid, proc->pid); + (*store)->wchan_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/task/%i/wchan", proc->pid, proc->pid); + (*store)->stat_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/task/%i/stat", proc->pid, proc->pid); + } else { + (*store)->comm_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/comm", proc->pid); + (*store)->cmdline_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/cmdline", proc->pid); + (*store)->wchan_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/wchan", proc->pid); + (*store)->stat_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/stat", proc->pid); + } + + /* initially everything is considered changed */ + memset((*store)->changed, 0xff, sizeof((*store)->changed)); + } else { + try_lseek((*store)->comm_fd, 0, SEEK_SET); + try_lseek((*store)->cmdline_fd, 0, SEEK_SET); + try_lseek((*store)->wchan_fd, 0, SEEK_SET); + try_lseek((*store)->stat_fd, 0, SEEK_SET); + + /* clear the entire changed bitmap */ + memset((*store)->changed, 0, sizeof((*store)->changed)); + } + + /* XXX TODO: integrate load_contents_fd() calls into changes++ maintenance */ + /* /proc/$pid/comm */ + load_contents_fd(vmon, &(*store)->comm, (*store)->comm_fd, LOAD_FLAGS_NOTRUNCATE, (*store)->changed, VMON_PROC_STAT_COMM); + + /* /proc/$pid/cmdline */ + load_contents_fd(vmon, &(*store)->cmdline, (*store)->cmdline_fd, LOAD_FLAGS_NOTRUNCATE, (*store)->changed, VMON_PROC_STAT_CMDLINE); + for(prev_argc = (*store)->argc, (*store)->argc = 0, i = 0; i < (*store)->cmdline.len; i++) { + if(!(*store)->cmdline.array[i]) { + (*store)->argc++; + } + } + + /* if the cmdline has changed, allocate argv array and store ptrs to the fields within it */ + if(BITTEST((*store)->changed, VMON_PROC_STAT_CMDLINE)) { + if(prev_argc != (*store)->argc) { + try_free((void **)&(*store)->argv); /* XXX could realloc */ + (*store)->argv = malloc((*store)->argc * sizeof(char *)); + } + + for(argn = 0, arg = (*store)->cmdline.array, i = 0; i < (*store)->cmdline.len; i++) { + if(!(*store)->cmdline.array[i]) { + (*store)->argv[argn++] = arg; + arg = &(*store)->cmdline.array[i + 1]; + } + } + } + + /* /proc/$pid/wchan */ + load_contents_fd(vmon, &(*store)->wchan, (*store)->wchan_fd, LOAD_FLAGS_NOTRUNCATE, (*store)->changed, VMON_PROC_STAT_WCHAN); + + /* /proc/$pid/exe */ + if((*store)->cmdline.len) { /* kernel threads have no cmdline, and always fail readlinkf() on exe, skip readlinking the exe for them using this heuristic */ + readlinkf(vmon, &(*store)->exe, vmon->proc_dir, "%i/exe", proc->pid); + } + + /* XXX TODO: there's a race between discovering comm_len from /proc/$pid/comm and applying it in the parsing of /proc/$pid/stat, detect the race + * scenario and retry the sample when detected by goto _retry */ + + /* read in stat and parse it assigning the stat members accordingly */ + while((len = try_read((*store)->stat_fd, vmon->buf, sizeof(vmon->buf))) > 0) { + for(i = 0; i < len; i++) { + /* parse the fields from the file, stepping through... */ + input = vmon->buf[i]; + switch(state) { +#define VMON_PARSER_DELIM ' ' /* TODO XXX eliminate the need for this, I want the .def's to include all the data format knowledge */ +#define VMON_IMPLEMENT_PARSER +#include "defs/proc_stat.def" + default: + /* we're finished parsing once we've fallen off the end of the symbols */ + break; + } + } + } + + return changes ? SAMPLE_CHANGED : SAMPLE_UNCHANGED; +} + + +/* implements the children following */ +static int proc_follow_children(vmon_t *vmon, vmon_proc_t *proc, vmon_proc_follow_children_t **store) +{ + int changes = 0; + int len, i, child_pid = 0, found; + vmon_proc_t *tmp, *_tmp; + list_head_t *cur, *start; + + if(!proc) { /* dtor */ + try_close(&(*store)->children_fd); + + return DTOR_FREE; + } + + if(proc->is_thread) { /* don't follow children of threads */ + return SAMPLE_UNCHANGED; + } + + if(!(*store)) { /* implicit ctor on first sample */ + *store = calloc(1, sizeof(vmon_proc_follow_children_t)); + + (*store)->children_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/task/%i/children", proc->pid, proc->pid); + } else { + try_lseek((*store)->children_fd, 0, SEEK_SET); + } + + /* unmonitor stale children on entry, this concludes the two-phase removal of a process */ + list_for_each_entry_safe(tmp, _tmp, &proc->children, siblings) { + if(tmp->is_stale) { + vmon_proc_unmonitor(vmon, tmp, NULL, NULL); + } +#ifdef _MOVE_STALE_TO_FRONT + else { + break; + } +#endif + } + + /* if we have a parent, and our parent has become stale, ensure this, the child, becomes stale as well */ + if(proc->parent && proc->parent->is_stale) { + proc->is_stale = 1; + proc->parent->children_changed = 1; + return SAMPLE_CHANGED; + } + + /* maintain our awareness of children, if we detect a new child initiate monitoring for it, existing children get their generation number updated */ + start = &proc->children; + while((len = try_read((*store)->children_fd, vmon->buf, sizeof(vmon->buf))) > 0) { + for(i = 0; i < len; i++) { + switch(vmon->buf[i]) { + case '0' ... '9': + /* PID component, accumulate it */ + child_pid *= 10; + child_pid += (vmon->buf[i] - '0'); + break; + + case ' ': + /* separator, terminates a PID, search for it in the childrens list */ + found = 0; + list_for_each(cur, start) { + if(list_entry(cur, vmon_proc_t, siblings)->pid == child_pid) { + /* found the child already monitored, update its generation number and stop searching */ + tmp = list_entry(cur, vmon_proc_t, siblings); + tmp->generation = vmon->generation; + found = 1; + tmp->is_new = 0; + break; + } + } + + if(found || (tmp = vmon_proc_monitor(vmon, proc, child_pid, proc->wants, NULL, NULL))) { + /* position the process in the siblings list, and update the start */ + /* move to front breaks vwm, we rely on the stale processes maintaining their position! maybe make it an option to vmon_init() since it can be a useful optimization. */ +#ifdef _MOVE_STALE_TO_FRONT + list_move_tail(&tmp->siblings, start); +#endif + start = &tmp->siblings; + } /* else { vmon_proc_monitor failed just move on } */ + + child_pid = 0; + break; + } + } + } + + /* look for children which seem to no longer exist (found by stale generation numbers) and queue them for unmonitoring, flag this as a children change too */ + found = 0; + list_for_each_entry(tmp, &proc->children, siblings) { + if(tmp->generation != vmon->generation) { + /* set children not found to stale status so the caller can respond and on our next sample invocation we will unmonitor them */ + found = tmp->is_stale = 1; + } +#ifdef _MOVE_STALE_TO_FRONT + /* this depends on the moving of stale entries to the start of the list optimization which breaks vwm, disabled for now */ + else { + break; + } +#endif + } + + /* XXX TODO: does it makes sense for shit to happen here? */ + if(found) { + if(proc->parent) { + proc->parent->children_changed = 1; + } else { + vmon->processes_changed = 1; + } + } + + return changes ? SAMPLE_CHANGED : SAMPLE_UNCHANGED; +} + + +/* implements the thread following */ +static int proc_follow_threads(vmon_t *vmon, vmon_proc_t *proc, vmon_proc_follow_threads_t **store) +{ + int changes = 0; + struct dirent dentry, *dentry_res; + list_head_t *cur, *start; + vmon_proc_t *tmp, *_tmp; + int found; + + if(!proc) { /* dtor */ + try_closedir(&(*store)->task_dir); + + return DTOR_FREE; + } + + if(proc->is_thread) { /* bypass following the threads of threads */ + return SAMPLE_UNCHANGED; + } + + if(!proc->stores || !proc->stores[VMON_STORE_PROC_STAT] || (((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->num_threads <= 1 && list_empty(&proc->threads))) { + /* bypass following of threads if we either can't determine the number from the proc stat sample or if the sample says there's 1 or less (and an empty threads list, handling stale exited threads) */ + /* XXX I'm not sure if this is always the right thing to do, there may be some situations where one could play games with clone() directly + * and escape the monitoring library with a lone thread having had the main thread exit, leaving the count at 1 while having a process + * descriptor distinguished from the single thread XXX */ + return SAMPLE_UNCHANGED; + } + + if(!(*store)) { /* implicit ctor on first sample */ + *store = calloc(1, sizeof(vmon_proc_follow_threads_t)); + + (*store)->task_dir = opendirf(vmon, vmon->proc_dir, "%i/task", proc->pid); + } else if((*store)->task_dir) { + seekdir((*store)->task_dir, 0); + } + + if(!(*store)->task_dir) { + return SAMPLE_ERROR; + } + + /* unmonitor stale threads on entry, this concludes the two-phase removal of a thread (just like follow_children) */ + list_for_each_entry_safe(tmp, _tmp, &proc->threads, threads) { + if(tmp->is_stale) { + vmon_proc_unmonitor(vmon, tmp, NULL, NULL); + } +#ifdef _MOVE_STALE_TO_FRONT + else { + break; + } +#endif + } + + start = &proc->threads; + while(!readdir_r((*store)->task_dir, &dentry, &dentry_res) && dentry_res) { + int tid; + + if(dentry.d_name[0] == '.' && (dentry.d_name[1] == '\0' || (dentry.d_name[1] == '.' && dentry.d_name[2] == '\0'))) { + /* skip . and .. */ + continue; + } + + tid = atoi(dentry.d_name); + + found = 0; + list_for_each(cur, start) { + if(cur == &proc->threads) { /* take care to skip the head node */ + continue; + } + + if(list_entry(cur, vmon_proc_t, threads)->pid == tid) { + /* found the thread already monitored, update its generation number and stop searching */ + tmp = list_entry(cur, vmon_proc_t, threads); + tmp->generation = vmon->generation; + found = 1; + tmp->is_new = 0; + break; + } + } + + if(found || (tmp = vmon_proc_monitor(vmon, proc, tid, (proc->wants | VMON_INTERNAL_PROC_IS_THREAD), NULL, NULL))) { + /* position the thread in the threads list, and update the start */ +#ifdef _MOVE_STALE_TO_FRONT + list_move_tail(&tmp->threads, start); +#endif + start = &tmp->threads; + } /* else { vmon_proc_monitor failed just move on } */ + } + + list_for_each_entry_safe(tmp, _tmp, &proc->threads, threads) { + if(tmp->generation != vmon->generation) { + /* set children not found to stale status so the caller can respond and on our next sample invocation we will unmonitor them */ + tmp->is_stale = 1; + } +#ifdef _MOVE_STALE_TO_FRONT + else { + break; + } +#endif + } + + return changes ? SAMPLE_CHANGED : SAMPLE_UNCHANGED; +} + + +/* helper for maintaining reference counted global objects table */ +static vmon_fobject_t * fobject_lookup_hinted(vmon_t *vmon, const char *path, vmon_fobject_t *hint) +{ + vmon_fobject_t *fobject = NULL, *tmp = NULL; + uint64_t inum; + + /* TODO maintain the fobject hash tables, they should probably be isolated/scoped based on the string before the : */ + /* in reality there needs to be a list somewhere of the valid prefixes we wish to support, and that list should associate + * the prefixes with the kind of contextual information details we monitor for each of those types. Then when new + * fobject types are added to libvmon, the rest of the code automatically reflects the additions due to the mechanization. + */ + if(!path || strncmp(path, "pipe:", 5)) { + return NULL; /* XXX TODO: for now we're only dealing with pipes */ + } + + sscanf(&path[6], "%" SCNu64 "]", &inum); + + if(hint && hint->inum == inum) { + /* the hint matches, skip the search */ + return hint; + } + + /* search for the inode, if we can't find it, allocate a new fobject XXX this needs optimizing but silly until we have all object types handled... */ + list_for_each_entry(tmp, &vmon->fobjects, bucket) { + if(tmp->inum == inum) { + fobject = tmp; + break; + } + } + + if(!fobject) { + /* create a new fobject */ + fobject = malloc(sizeof(vmon_fobject_t)); + + fobject->type = VMON_FOBJECT_TYPE_PIPE; + fobject->inum = inum; + INIT_LIST_HEAD(&fobject->ref_fds); + INIT_LIST_HEAD(&fobject->bucket); + fobject->refcnt = 0; + fobject->foo = NULL; + list_add_tail(&fobject->bucket, &vmon->fobjects); + vmon->fobjects_nr++; + + if(vmon->fobject_ctor_cb) { + vmon->fobject_ctor_cb(vmon, fobject); + } + } + + return fobject; +} + + +/* add a reference to an fobject, fd_ref is optional (should be present if the reference is due to an open fd, which may not be the case) */ +static void fobject_ref(vmon_t *vmon, vmon_fobject_t *fobject, vmon_proc_fd_t *fd_ref) +{ + fobject->refcnt++; + + if(fd_ref) { + list_add_tail(&fd_ref->ref_fds, &fobject->ref_fds); + } +} + + +/* fobject is required and is the object being unrefereced, fd_ref is optional but represents the per-process fd reference being used to access this fobject via */ +static int fobject_unref(vmon_t *vmon, vmon_fobject_t *fobject, vmon_proc_fd_t *fd_ref) +{ + if(fd_ref) { + list_del(&fd_ref->ref_fds); + } + + fobject->refcnt--; + + if(!fobject->refcnt) { + /* after the refcnt drops to zero we discard the fobject */ + list_del(&fobject->bucket); + vmon->fobjects_nr--; + + if(vmon->fobject_dtor_cb) { + vmon->fobject_dtor_cb(vmon, fobject); + } + + free(fobject); + return 1; + } + + return 0; +} + + +/* helper for deleting an fd from the per-process fds list list */ +static void del_fd(vmon_t *vmon, vmon_proc_fd_t *fd) +{ + list_del(&fd->fds); + if(fd->object) { + fobject_unref(vmon, fd->object, fd); /* note we supply both the fobject ptr and proc_fd ptr (fd) */ + } + try_free((void **)&fd->object_path); + free(fd); +} + + +/* implements the open file descriptors (/proc/$pid/fd/...) sampling */ +static sample_ret_t proc_sample_files(vmon_t *vmon, vmon_proc_t *proc, vmon_proc_files_t **store) +{ + int changes = 0; + struct dirent dentry, *dentry_res; + int fdnum; + list_head_t *cur, *start; + vmon_proc_fd_t *fd, *_fd; + vmon_fobject_t *cur_object = NULL; + + if(!proc) { + /* dtor implementation */ + if(--((*store)->refcnt)) { /* suppress dtor while references exist, the store is shared */ + return DTOR_NOFREE; + } + + try_closedir(&(*store)->fd_dir); + + list_for_each_entry_safe(fd, _fd, &(*store)->fds, fds) { + del_fd(vmon, fd); + } + + return DTOR_FREE; + } + + if(proc->is_thread) { + /* don't monitor the open files of threads, instead, share the files store of the parent process by adding a reference to it */ + /* XXX TODO: use kcmp CMP_FILES in the future instead of assuming all threads share open files */ + if(!(*store) && ((*store) = proc->parent->stores[VMON_STORE_PROC_FILES])) { + (*store)->refcnt++; + } + return SAMPLE_UNCHANGED; /* XXX TODO: we actually want to reflect/copy the activity state of the parent */ + } + + if(!(*store)) { /* implicit ctor on first sample */ + *store = calloc(1, sizeof(vmon_proc_files_t)); + + (*store)->refcnt = 1; + (*store)->fd_dir = opendirf(vmon, vmon->proc_dir, "%i/fd", proc->pid); + + INIT_LIST_HEAD(&(*store)->fds); + } else if((*store)->fd_dir) { + /* we have a directory handle, and we're reentering the function with the directory positioned at the end */ + seekdir((*store)->fd_dir, 0); + } + + if(!(*store)->fd_dir) { + /* we have no directory handle on reentry */ + /* XXX TODO: this happens when we don't have permission, this hsould be handled more elegantly/cleanly, and we don't + * make any attempt to ever reopen the directory because the ctor has already run. */ + goto _fail; + } + + start = &(*store)->fds; + while(!readdir_r((*store)->fd_dir, &dentry, &dentry_res) && dentry_res) { + if(dentry.d_name[0] == '.' && (dentry.d_name[1] == '\0' || (dentry.d_name[1] == '.' && dentry.d_name[2] == '\0'))) { + /* skip . and .. */ + continue; + } + + fdnum = atoi(dentry.d_name); + + /* search the process' files list for this fdnum */ + fd = NULL; + list_for_each(cur, start) { + if(cur == &(*store)->fds) { + continue; /* skip the head node as it's not boxed */ + } + if(list_entry(cur, vmon_proc_fd_t, fds)->fdnum == fdnum) { + fd = list_entry(cur, vmon_proc_fd_t, fds); + break; + } + } + + if(!fd) { + fd = calloc(1, sizeof(vmon_proc_fd_t)); + if(!fd) { + /* TODO: errors */ + goto _fail; + } + fd->fdnum = fdnum; + fd->process = proc; + INIT_LIST_HEAD(&fd->ref_fds); + list_add_tail(&fd->fds, start); + } else { + list_move_tail(&fd->fds, start); + } + + fd->generation = vmon->generation; + + /* Always readlink the fd path, since we have no way of knowing if it's a repurposed fdnum even when we've found a match. + * It would be nice if say.. the mtime of the /proc/$pid/fd directory changed if there's been any fd activity so we could skip the entire + * readdir+readlink loop in idle times, worth investigating. */ + readlinkf(vmon, &fd->object_path, vmon->proc_dir, "%i/fd/%s", proc->pid, dentry.d_name); + + cur_object = fd->object; /* stow the current object reference before we potentially replace it so we may unreference it if needed */ + fd->object = fobject_lookup_hinted(vmon, fd->object_path.array, cur_object); + if(cur_object != fd->object) { + if(cur_object) { + fobject_unref(vmon, cur_object, fd); + } + + if(fd->object) { + fobject_ref(vmon, fd->object, fd); + } + } /* else { lookup returned the same object as before (or NULL), is there anything to do? } */ + + start = &fd->fds; /* update the search start to this fd */ + } + + /* search for stale (closed) fds, remove references for any we find */ + list_for_each_entry_safe(fd, _fd, &(*store)->fds, fds) { + if(fd->generation != vmon->generation) { + del_fd(vmon, fd); + } else { + break; + } + } + + return changes ? SAMPLE_CHANGED : SAMPLE_UNCHANGED; + +_fail: + return SAMPLE_ERROR; +} + + +/* implements the vm utilization sampling */ +typedef enum _vmon_proc_vm_fsm_t { +#define VMON_ENUM_PARSER_STATES +#include "defs/proc_vm.def" +} vmon_proc_vm_fsm_t; + +static sample_ret_t proc_sample_vm(vmon_t *vmon, vmon_proc_t *proc, vmon_proc_vm_t **store) +{ + int i, len; + int changes = 0; + vmon_proc_vm_fsm_t state = VMON_PARSER_STATE_PROC_VM_SIZE_PAGES; +#define VMON_PREPARE_PARSER +#include "defs/proc_vm.def" + + if(!proc) { /* dtor */ + try_close(&(*store)->statm_fd); + + return DTOR_FREE; + } + + if(!(*store)) { /* ctor */ + (*store) = calloc(1, sizeof(vmon_proc_vm_t)); + if(proc->is_thread) { + (*store)->statm_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/task/%i/statm", proc->pid, proc->pid); + } else { + (*store)->statm_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/statm", proc->pid); + } + + /* initially everything is considered changed */ + memset((*store)->changed, 0xff, sizeof((*store)->changed)); + } else { + try_lseek((*store)->statm_fd, 0, SEEK_SET); + + /* clear the entire changed bitmap */ + memset((*store)->changed, 0, sizeof((*store)->changed)); + } + + /* read in statm and parse it assigning the vm members accordingly */ + while((len = try_read((*store)->statm_fd, vmon->buf, sizeof(vmon->buf))) > 0) { + for(i = 0; i < len; i++) { + /* parse the fields from the file, stepping through... */ + input = vmon->buf[i]; + switch(state) { +#define VMON_IMPLEMENT_PARSER +#include "defs/proc_vm.def" + default: + /* we're finished parsing once we've fallen off the end of the symbols */ + break; + } + } + } + + return changes ? SAMPLE_CHANGED : SAMPLE_UNCHANGED; +} + + +/* implements the io utilization sampling */ +typedef enum _vmon_proc_io_fsm_t { +#define VMON_ENUM_PARSER_STATES +#include "defs/proc_io.def" +} vmon_proc_io_fsm_t; + +static sample_ret_t proc_sample_io(vmon_t *vmon, vmon_proc_t *proc, vmon_proc_io_t **store) +{ + int i, len; + int changes = 0; + vmon_proc_io_fsm_t state = VMON_PARSER_STATE_PROC_IO_RCHAR_LABEL; +#define VMON_PREPARE_PARSER +#include "defs/proc_io.def" + + if(!proc) { /* dtor */ + try_close(&(*store)->io_fd); + + return DTOR_FREE; + } + + if(!(*store)) { /* ctor */ + (*store) = calloc(1, sizeof(vmon_proc_io_t)); + if(proc->is_thread) { + (*store)->io_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/task/%i/io", proc->pid, proc->pid); + } else { + (*store)->io_fd = openf(vmon, O_RDONLY, vmon->proc_dir, "%i/io", proc->pid); + } + + /* initially everything is considered changed */ + memset((*store)->changed, 0xff, sizeof((*store)->changed)); + } else { + try_lseek((*store)->io_fd, 0, SEEK_SET); + + /* clear the entire changed bitmap */ + memset((*store)->changed, 0, sizeof((*store)->changed)); + } + + /* read in io and parse it assigning the io members accordingly */ + while((len = try_read((*store)->io_fd, vmon->buf, sizeof(vmon->buf))) > 0) { + for(i = 0; i < len; i++) { + /* parse the fields from the file, stepping through... */ + input = vmon->buf[i]; + switch(state) { +#define VMON_IMPLEMENT_PARSER +#include "defs/proc_io.def" + default: + /* we're finished parsing once we've fallen off the end of the symbols */ + break; + } + } + } + + return changes ? SAMPLE_CHANGED : SAMPLE_UNCHANGED; +} + + +/* here starts the private system-wide samplers */ + +typedef enum _vmon_sys_stat_fsm_t { +#define VMON_ENUM_PARSER_STATES +#include "defs/sys_stat.def" +} vmon_sys_stat_fsm_t; + +/* system-wide stat sampling, things like CPU usages, stuff in /proc/stat */ +static sample_ret_t sys_sample_stat(vmon_t *vmon, vmon_sys_stat_t **store) +{ + int i, len; + int changes = 0; + vmon_sys_stat_fsm_t state = VMON_PARSER_STATE_SYS_STAT_CPU_PREFIX; /* this could be defined as the "VMON_PARSER_INITIAL_STATE" */ +#define VMON_PREPARE_PARSER +#include "defs/sys_stat.def" + + if(!vmon) { /* dtor */ + try_close(&(*store)->stat_fd); + return DTOR_FREE; + } + + if(!(*store)) { /* ctor */ + (*store) = calloc(1, sizeof(vmon_sys_stat_t)); + (*store)->stat_fd = openat(dirfd(vmon->proc_dir), "stat", O_RDONLY); + } else { + try_lseek((*store)->stat_fd, 0, SEEK_SET); + } + + while((len = try_read((*store)->stat_fd, vmon->buf, sizeof(vmon->buf))) > 0) { + for(i = 0; i < len; i++) { + input = vmon->buf[i]; + switch(state) { +#define VMON_PARSER_DELIM ' ' /* TODO XXX eliminate the need for this, I want the .def's to include all the data format knowledge */ +#define VMON_IMPLEMENT_PARSER +#include "defs/sys_stat.def" + default: + /* we're finished parsing once we've fallen off the end of the symbols */ + break; + } + } + } + + return changes ? SAMPLE_CHANGED : SAMPLE_UNCHANGED; +} + + +/* system-wide vm sampling, /proc/meminfo & /proc/vmstat */ +typedef enum _vmon_sys_vm_fsm_t { +#define VMON_ENUM_PARSER_STATES +#include "defs/sys_vm.def" +} vmon_sys_vm_fsm_t; + +static sample_ret_t sys_sample_vm(vmon_t *vmon, vmon_sys_vm_t **store) +{ + int i, len; + int changes = 0; + vmon_sys_vm_fsm_t state = VMON_PARSER_STATE_SYS_VM_TOTAL_KB_LABEL; /* this could be defined as the "VMON_PARSER_INITIAL_STATE" */ +#define VMON_PREPARE_PARSER +#include "defs/sys_vm.def" + + if(!vmon) { /* dtor */ + try_close(&(*store)->meminfo_fd); + return DTOR_FREE; + } + + if(!(*store)) { /* ctor */ + (*store) = calloc(1, sizeof(vmon_sys_vm_t)); + (*store)->meminfo_fd = openat(dirfd(vmon->proc_dir), "meminfo", O_RDONLY); + + /* initially everything is considered changed */ + memset((*store)->changed, 0xff, sizeof((*store)->changed)); + } else { + try_lseek((*store)->meminfo_fd, 0, SEEK_SET); + memset((*store)->changed, 0, sizeof((*store)->changed)); + } + + while((len = try_read((*store)->meminfo_fd, vmon->buf, sizeof(vmon->buf))) > 0) { + for(i = 0; i < len; i++) { + input = vmon->buf[i]; + switch(state) { +#define VMON_PARSER_DELIM ' ' /* TODO XXX eliminate the need for this, I want the .def's to include all the data format knowledge */ +#define VMON_IMPLEMENT_PARSER +#include "defs/sys_vm.def" + default: + /* we're finished parsing once we've fallen off the end of the symbols */ + break; + } + } + } + + return changes ? SAMPLE_CHANGED : SAMPLE_UNCHANGED; +} + + +/* here begins the public interface */ + +/* initialize a vmon instance, proc_wants is a default wants mask, optionally inherited vmon_proc_monitor() calls */ +int vmon_init(vmon_t *vmon, vmon_flags_t flags, vmon_sys_wants_t sys_wants, vmon_proc_wants_t proc_wants) +{ + int i; + + if((flags & VMON_FLAG_PROC_ALL) && (proc_wants & VMON_WANT_PROC_FOLLOW_CHILDREN)) { + return 0; + } + + if(!(vmon->proc_dir = opendir("/proc"))) { + return 0; + } + + INIT_LIST_HEAD(&vmon->processes); + INIT_LIST_HEAD(&vmon->orphans); + + for(i = 0; i < VMON_HTAB_SIZE; i++) { + INIT_LIST_HEAD(&vmon->htab[i]); + } + + memset(vmon->stores, 0, sizeof(vmon->stores)); + + /* TODO XXX: rename to something processes-specific! see vmon.h */ + vmon->array = NULL; + vmon->array_allocated_nr = vmon->array_active_nr = vmon->array_hint_free = 0; + + /* TODO XXX: this is temporary, see vmon.h */ + INIT_LIST_HEAD(&vmon->fobjects); + vmon->fobjects_nr = 0; + + vmon->flags = flags; + vmon->sys_wants = sys_wants; + vmon->proc_wants = proc_wants; + + /* here we populate the sys and proc function tables */ +#define vmon_want(_sym, _name, _func) \ + vmon->sys_funcs[VMON_STORE_ ## _sym] = (int(*)(vmon_t *, void **))_func; +#include "defs/sys_wants.def" + +#define vmon_want(_sym, _name, _func) \ + vmon->proc_funcs[VMON_STORE_ ## _sym] = (int(*)(vmon_t *, vmon_proc_t *, void **))_func; +#include "defs/proc_wants.def" + + vmon->sample_cb = NULL; + vmon->proc_ctor_cb = NULL; + vmon->proc_dtor_cb = NULL; + vmon->fobject_ctor_cb = NULL; + vmon->fobject_dtor_cb = NULL; + + return 1; +} + + +/* destroy vmon instance */ +void vmon_destroy(vmon_t *vmon) +{ + /* TODO: do we want to forcibly unmonitor everything being monitored still, or require the caller to have done that beforehand? */ + /* TODO: cleanup other shit, like closedir(vmon->proc_dir), etc */ +} + + +/* helper for searching for the process in the process array, specify NULL to find a free slot */ +static int find_proc_in_array(vmon_t *vmon, vmon_proc_t *proc, int hint) +{ + int ret = -1; + + if(hint >= 0 && hint < vmon->array_allocated_nr && vmon->array[hint] == proc) { + /* the hint was accurate, bypass the search */ + ret = hint; + } else { + int i; + + /* search for the entry in the array */ + for(i = 0; i < vmon->array_allocated_nr; i++) { + if(vmon->array[i] == proc) { + ret = i; + break; + } + } + } + + if(!proc && ret == -1) { + vmon_proc_t **tmp; + + /* enlarge the array */ + tmp = realloc(vmon->array, (vmon->array_allocated_nr + VMON_ARRAY_GROWBY) * sizeof(vmon_proc_t *)); + if(tmp) { + memset(&tmp[vmon->array_allocated_nr], 0, VMON_ARRAY_GROWBY * sizeof(vmon_proc_t *)); + ret = vmon->array_hint_free = vmon->array_allocated_nr; + vmon->array_allocated_nr += VMON_ARRAY_GROWBY; + vmon->array = tmp; + } /* XXX TODO: handle realloc failure */ + } + + return ret; +} + + +/* simple helper for installing callbacks on the callback lists, currently only used for the per-process sample callbacks */ +/* will not install the same callback function & arg combination more than once, and will not install NULL-functioned callbacks at all! */ +static int maybe_install_proc_callback(vmon_t *vmon, list_head_t *callbacks, void (*func)(vmon_t *, vmon_proc_t *, void *), void *arg) +{ + if(func) { + vmon_proc_callback_t *cb; + + list_for_each_entry(cb, callbacks, callbacks) { + if(cb->func == func && cb->arg == arg) { + break; + } + } + + if(&cb->callbacks == callbacks) { + cb = malloc(sizeof(vmon_proc_callback_t)); + if(!cb) { + return 0; + } + cb->func = func; + cb->arg = arg; + list_add_tail(&cb->callbacks, callbacks); + } + } + + return 1; +} + + +/* monitor a process under a given vmon instance, the public interface. + * XXX note it's impossible to say "none" for wants per-process, just "inherit", if vmon_init() was told a proc_wants of "inherit" then it's like having "none" + * proc_wants for all proceses, perhaps improve this if there's a pressure to support this use case */ +vmon_proc_t * vmon_proc_monitor(vmon_t *vmon, vmon_proc_t *parent, int pid, vmon_proc_wants_t wants, void (*sample_cb)(vmon_t *, vmon_proc_t *, void *), void *sample_cb_data) +{ + vmon_proc_t *proc; + int hash = (pid % VMON_HTAB_SIZE), i; + int is_thread = (wants & VMON_INTERNAL_PROC_IS_THREAD) ? 1 : 0; + + wants &= ~VMON_INTERNAL_PROC_IS_THREAD; + + if(pid < 0) return NULL; + + list_for_each_entry(proc, &vmon->htab[hash], bucket) { + /* search for the process to see if it's already monitored, we allow threads to exist with the same pid hence the additional is_thread comparison */ + if(proc->pid == pid && proc->is_thread == is_thread) { + if(!maybe_install_proc_callback(vmon, &proc->sample_callbacks, sample_cb, sample_cb_data)) { + return NULL; + } + + proc->wants = wants; /* we can alter wants this way, though it clearly needs more consideration XXX */ + proc->refcnt++; + /* This is a predicament. If the top-level (externally-established) process monitor wins the race, the process has no parent and is on the vmon->processes list. + * Then the follow_children-established monitor comes along and wants to assign a parent, this isn't such a big deal, and we should be able to permit it, however, + * we're in the process of iterating the top-level processes list when we run the follow_children() sampler of a descendant which happens to also be the parent. + * We can't simply remove the process from the top-level processes list mid-iteration and stick it on the children list of the parent, the iterator could wind up + * following the new pointer into the parents children. + * + * What I'm doing for now is allowing the assignment of a parent when there is no parent, but we don't perform the vmon->processes to parent->children migration + * until the top-level sample_siblings() function sees the node with the parent. At that point, the node will migrate to the parent's children list. + */ + if(parent && !proc->parent) { + /* if a parent was supplied, and there is no current parent, the process is a top-level currently by external callers, but now appears to be a child of something as well, + * so in this scenario, we'll remove it from the top-level siblings list, and make it a child of the new parent. I don't think there needs to be concern about its being a thread here. */ + /* Note we can't simply move the process from its current processes list and add it to the supplied parent's children list, as that would break the iterator above us at the top-level, so + * we must defer the migration until the processes iterator context can do it for us - but this is tricky because we're in the middle of traversing our heirarchy and this process may + * be in a critical is_new state which must be realized this sample at its location in the heirarchy for correctness, there will be no reappearance of that critical state in the correct + * tree position for users like vwm. */ + /* the VMON_FLAG_2PASS flag has been introduced for users like vwm */ + proc->parent = parent; + } /* else if(parent && proc->parent) { XXX TODO: it shouldn't be possible to have conflicting parents, but may want to log an error if it happens. */ + + return proc; + } + } + + proc = (vmon_proc_t *)malloc(sizeof(vmon_proc_t)); + if(proc == NULL) { + /* TODO: report an error */ + return NULL; + } + + proc->pid = pid; + proc->wants = wants; + proc->generation = vmon->generation; + proc->refcnt = 1; + proc->is_new = 1; /* newly created process */ + proc->is_stale = 0; /* implicitly not stale, since it is new */ + proc->is_thread = is_thread; + memset(proc->stores, 0, sizeof(proc->stores)); + proc->parent = parent; + INIT_LIST_HEAD(&proc->sample_callbacks); + INIT_LIST_HEAD(&proc->children); + INIT_LIST_HEAD(&proc->siblings); + INIT_LIST_HEAD(&proc->threads); + + if(!maybe_install_proc_callback(vmon, &proc->sample_callbacks, sample_cb, sample_cb_data)) { + free(proc); + return NULL; + } + + if(parent) { + /* if a parent is specified, attach this process to the parent's children or threads with its siblings */ + if(is_thread) { + list_add_tail(&proc->threads, &parent->threads); + parent->threads_changed = 1; + } else { + list_add_tail(&proc->siblings, &parent->children); + parent->children_changed = 1; + } + } else { + /* if no parent is specified, this is a toplevel process, attach it to the vmon->processes list with its siblings */ + /* XXX ignoring is_thread if no parent is specified, it shouldn't occur, unless I want to support external callers monitoring specific threads explicitly, maybe... */ + list_add_tail(&proc->siblings, &vmon->processes); + vmon->processes_changed = 1; + } + + /* add this process to the hash table */ + list_add_tail(&proc->bucket, &vmon->htab[hash]); + + /* if process table maintenance is enabled acquire a free slot for this process */ + if((vmon->flags & VMON_FLAG_PROC_ARRAY) && (i = find_proc_in_array(vmon, NULL, vmon->array_hint_free)) != -1) { + vmon->array[i] = proc; + + /* cache where we get inserted into the array */ + proc->array_hint_pos = i; + } + + /* invoke ctor callback if set, note it's only called when a new vmon_proc_t has been instantiated */ + if(vmon->proc_ctor_cb) { + vmon->proc_ctor_cb(vmon, proc); + } + + return proc; +} + + +/* stop monitoring a process under a given vmon instance, a caller who supplied a sample_cb & sample_cb_data pair @ monitor() must also supply it @ unmonitor! */ +void vmon_proc_unmonitor(vmon_t *vmon, vmon_proc_t *proc, void (*sample_cb)(vmon_t *, vmon_proc_t *, void *), void *sample_cb_data) +{ + vmon_proc_t *child, *_child; + int i; + + if(sample_cb) { /* uninstall callback */ + vmon_proc_callback_t *cb, *_cb; + + list_for_each_entry_safe(cb, _cb, &proc->sample_callbacks, callbacks) { + if(cb->func == sample_cb && cb->arg == sample_cb_data) { + list_del(&cb->callbacks); + free(cb); + break; + } + } + } + + if(--(proc->refcnt)) { /* if the process still has references, don't free it */ + return; + } + + /* recursively unmonitor any children processes being monitored */ + list_for_each_entry_safe(child, _child, &proc->children, siblings) { + if(child->parent == proc) { + child->parent = NULL; /* children we're currently a parent of, we're going bye bye, so make them orphans */ + list_add_tail(&child->siblings, &vmon->orphans); /* if the child becomes actually dtor'd in the nxt step it immediately will be discarded from the orphans list ... */ + } + vmon_proc_unmonitor(vmon, child, NULL, NULL); + } + + /* unmonitor all threads being monitored, suppressed if this process is a thread itself, as threads don't have children */ + if(!proc->is_thread) { + list_for_each_entry_safe(child, _child, &proc->threads, threads) { + vmon_proc_unmonitor(vmon, child, NULL, NULL); + } + } + + /* if maintaining a process array NULL out the entry */ + if((vmon->flags & VMON_FLAG_PROC_ARRAY) && (i = find_proc_in_array(vmon, proc, proc->array_hint_pos)) != -1) { + vmon->array[i] = NULL; + /* store its index if the current free hint isn't free, or it's lower than the current free hint, making the hint useful */ + if(vmon->array[vmon->array_hint_free] || i < vmon->array_hint_free) { + vmon->array_hint_free = i; + } + } + + list_del(&proc->siblings); + if(proc->is_thread) { + list_del(&proc->threads); + } + list_del(&proc->bucket); + + if(proc->parent) { /* XXX TODO: verify this works ok for unmonitored orphans */ + /* set the children changed flag in the parent */ + if(proc->is_thread) { + proc->parent->threads_changed = 1; + } else { + proc->parent->children_changed = 1; /* XXX TODO: for now I modify children_changed for both when the child dtor occurs and is_stale gets set */ + } + } else { + /* or the toplevel processes changed flag if parentless/toplevel */ + vmon->processes_changed = 1; + } + + for(i = 0; i < sizeof(vmon->proc_funcs) / sizeof(vmon->proc_funcs[VMON_STORE_PROC_STAT]); i++) { + if(proc->stores[i] != NULL) { /* any non-NULL stores must have a function installed and must have been sampled, invoke the dtor branch */ + if(vmon->proc_funcs[i](vmon, NULL, &proc->stores[i]) == DTOR_FREE) { + free(proc->stores[i]); + } + proc->stores[i] = NULL; + } + } + + /* invoke the dtor if set, note it only happens when the vmon_proc_t instance is about to be freed, not when it transitions to proc.is_stale=1 */ + if(vmon->proc_dtor_cb) { + vmon->proc_dtor_cb(vmon, proc); + } + + free(proc); +} + + +/* internal sampling helper, perform sampling for a given process */ +static void sample(vmon_t *vmon, vmon_proc_t *proc) +{ + int i, wants, cur; + + /* load this process monitors wants, or inherit the default */ + wants = proc->wants ? proc->wants : vmon->proc_wants; + + proc->activity = 0; + for(i = 0, cur = 1; wants; cur <<= 1, i++) { + if(wants & cur) { + if(vmon->proc_funcs[i](vmon, proc, &proc->stores[i]) == SAMPLE_CHANGED) { + proc->activity |= cur; + } + wants &= ~cur; + } + } +} + + +/* internal sampling helper, perform sampling for all sibling processes in the provided siblings list */ +static int sample_threads(vmon_t *vmon, list_head_t *threads) +{ + vmon_proc_t *proc; + + list_for_each_entry(proc, threads, threads) { + sample(vmon, proc); + +#if 0 + /* callbacks can't be installed currently on threads */ + vmon_proc_callback_t *cb; + + list_for_each_entry(cb, &proc->sample_callbacks, callbacks) { + cb->func(vmon, proc, cb->arg); + } +#endif + } + + return 1; +} + + +/* internal single-pass sampling helper, recursively perform sampling and callbacks for all sibling processes in the provided siblings list */ +static int sample_siblings(vmon_t *vmon, list_head_t *siblings) +{ + vmon_proc_t *proc, *_proc; + + list_for_each_entry_safe(proc, _proc, siblings, siblings) { + vmon_proc_callback_t *cb; + int entered_new = 0; + + /* prepare to transition top-level processes out of the is_new state, there's no sampler acting on behalf of top-level processes */ + if(proc->is_new) { + entered_new = 1; + } + + sample(vmon, proc); /* invoke samplers for this node */ + sample_threads(vmon, &proc->threads); /* invoke samplers for this node's threads */ + sample_siblings(vmon, &proc->children); /* invoke samplers for this node's children, and their callbacks, by recursing into this function */ + /* XXX TODO: error returns */ + + /* if this is the top-level processes list, and proc has found a parent through the above sampling, migrate it to the parent's children list */ + if(siblings == &vmon->processes && proc->parent) { + list_del(&proc->siblings); + list_add_tail(&proc->siblings, &proc->parent->children); + continue; + } + + /* XXX note that sample_callbacks are called only after all the descendants have had their sampling performed (and their potential callbacks invoked) + * this enables the installation of a callback at a specific node in the process heirarchy which can also perform duties on behalf of the children + * being monitored, handy when automatically following children, an immediately relevant use case (vwm) + */ + list_for_each_entry(cb, &proc->sample_callbacks, callbacks) { + cb->func(vmon, proc, cb->arg); + } + + /* transition new to non-new processes where we're responsible, this is a slight problem */ + if(!proc->parent && entered_new) { + proc->is_new = 0; + } + } + + /* if we've just finished the top-level processes, and we have some orphans, we want to make the orphans top-level processes and sample them as such */ + if(siblings == &vmon->processes && !list_empty(&vmon->orphans)) { + /* XXX TODO: do I need to get these orphans sampled immediately for this sample? Are they getting skipped this sample? + * TODO: instrument the samplers to see if generation is > 1 behind to detect drops... */ + list_splice_init(&vmon->orphans, vmon->processes.prev); + } + + return 1; +} + + +/* 2pass version of the internal heirarchical sampling helper */ +static int sample_siblings_pass1(vmon_t *vmon, list_head_t *siblings) +{ + vmon_proc_t *proc, *_proc; + + /* invoke samplers */ + list_for_each_entry_safe(proc, _proc, siblings, siblings) { + sample(vmon, proc); /* invoke samplers for this node */ + sample_threads(vmon, &proc->threads); /* invoke samplers for this node's threads */ + sample_siblings_pass1(vmon, &proc->children); /* invoke samplers for this node's children, by recursing into this function */ + /* XXX TODO: error returns */ + + /* if this is the top-level processes list, and proc has found a parent through the above sampling, migrate it to the parent's children list */ + /* XXX: clarification; a process may have been monitored explicitly by an external caller which then becomes monitored as the followed child of + * another process, here we detect that and move the process out of the top-level processes list and down to the children list it belongs to. */ + if(siblings == &vmon->processes) { + /* XXX: nobody maintains the generation numbers for the top-level processes, so it's done here... + * TODO: detect exited top-level processes and do something useful? */ + proc->generation = vmon->generation; + + if(proc->parent) { + list_del(&proc->siblings); + list_add_tail(&proc->siblings, &proc->parent->children); + } + } + } + + if(siblings == &vmon->processes && !list_empty(&vmon->orphans)) { + /* XXX TODO: do I need to get these orphans sampled immediately for this sample? Are they getting skipped this sample? + * TODO: instrument the samplers to see if generation is > 1 behind to detect drops and log as bugs... */ + list_splice_init(&vmon->orphans, vmon->processes.prev); + } + + return 1; +} + + +static int sample_siblings_pass2(vmon_t *vmon, list_head_t *siblings) +{ + vmon_proc_t *proc; + + /* invoke callbacks */ + list_for_each_entry(proc, siblings, siblings) { + vmon_proc_callback_t *cb; + + sample_siblings_pass2(vmon, &proc->children); /* recurse into children, we invoke callbacks as encountered on nodes from the leaves up */ + + list_for_each_entry(cb, &proc->sample_callbacks, callbacks) { + cb->func(vmon, proc, cb->arg); + } + + if(!proc->parent && proc->is_new) { /* top-level processes aren't managed by a follower/sampler, so we need to clear their is_new flag, this approach is slightly deviant from the managed case, + * as the managed case will actually allow the process to retain its is_new flag across a vmon_sample() cycle, where we're clearing it @ exit. It makes + * no difference to the callbacks, but if someone walks the tree after vmon_sample() relying on is_new, they'll be confused. XXX TODO FIXME + * May be able to leverage the generation number and turn the top-level sampler into more of a follower analog??? + */ + proc->is_new = 0; + } + } + + return 1; +} + + +/* collect information for all monitored processes, this is the interesting part, call it periodically at a regular interval */ +int vmon_sample(vmon_t *vmon) +{ + int i, wants, cur, ret = 1; + + vmon->generation++; + + /* first manage the "all processes monitored" use case, this doesn't do any sampling, it just maintains the top-level list of processes being monitored */ + /* note this doesn't cover threads, as linux doesn't expose threads in the readdir of /proc, even though you can directly look them up at /proc/$tid */ + if((vmon->flags & VMON_FLAG_PROC_ALL)) { + struct dirent dentry, *dentry_res; + list_head_t *tmp, *_tmp = &vmon->processes; + + /* if VMON_FLAG_PROC_ALL flag is set, quite a different code path is used which simply readdir()'s /proc, treating every numeric directory found + * as a process to monitor. The list of toplevel processes being monitored is kept in sync with these, automatically monitoring + * new processes found, and unmonitoring processes now absent, in a fashion very similar to the proc_sample_files() code. */ + seekdir(vmon->proc_dir, 0); + while(!readdir_r(vmon->proc_dir, &dentry, &dentry_res) && dentry_res) { + int pid, found; + + if(dentry.d_type != DT_DIR || dentry.d_name[0] < '0' || dentry.d_name[0] > '9') { + /* skip non-directories and non-numeric directories */ + continue; + } + + pid = atoi(dentry.d_name); + + found = 0; + list_for_each(tmp, _tmp) { /* note how we use _tmp as the head for the processes iteration, resuming from the last process' node */ + if(tmp == &vmon->processes) { + continue; /* must take care to skip the processes list_head_t, as it's not a vmon_proc_t */ + } + + if(list_entry(tmp, vmon_proc_t, siblings)->pid == pid) { + found = 1; + break; + } + } + + if(!found) { + /* monitor the process */ + vmon_proc_t *proc = vmon_proc_monitor(vmon, NULL, pid, vmon->proc_wants, NULL, NULL); + + if(!proc) { + /* TODO error */ + continue; + } + + tmp = &proc->siblings; + } + + list_move_tail(tmp, _tmp); /* place this process next to the current start (XXX there are cases where it's already there) */ + + list_entry(tmp, vmon_proc_t, siblings)->generation = vmon->generation; /* for identifying stale nodes */ + + _tmp = tmp; /* set this node as the head to start the next search from */ + } + + list_for_each_safe(tmp, _tmp, &vmon->processes) { /* XXX safe version needed since vmon_proc_unmonitor() deletes from the processes list */ + if(list_entry(tmp, vmon_proc_t, siblings)->generation != vmon->generation) { + vmon_proc_unmonitor(vmon, list_entry(tmp, vmon_proc_t, siblings), NULL, NULL); + } else { + /* we can stop looking for stale processes upon finding a non-stale one, since they've been sorted by the above algorithm */ + break; + } + } + } + + /* now for actual sampling */ + + /* first the sys-wide samplers */ + wants = vmon->sys_wants; /* the caller-requested sys-wide wants */ + vmon->activity = 0; + for(i = 0, cur = 1; wants; cur <<= 1, i++) { + if(wants & cur) { + if(vmon->sys_funcs[i](vmon, &vmon->stores[i]) == SAMPLE_CHANGED) { + vmon->activity |= cur; + } + wants &= ~cur; + } + } + + if(vmon->sample_cb) { + vmon->sample_cb(vmon); + } + + /* then the per-process samplers */ + if((vmon->flags & VMON_FLAG_PROC_ARRAY)) { + int j; + /* TODO: determine if this really makes sense, if we always maintain a heirarchy even in array mode, then we + * should probably always sample in the heirarchical order, or maybe make it caller-specified. + * There is a benefit to invoking the callbacks in heirarchical order, the callbacks can make assumptions about the children + * having the callbacks invoked prior to the current node, if done in depth-first order.... + * XXX this is a problem, figure out what to do with this, for now we don't even maintain the heirarchy in VMON_FLAG_PROC_ALL + * mode, only FOLLOW_CHILDREN mode, and it's likely PROC_ARRAY will generally be used together with PROC_ALL, so no heirarchy + * is available to traverse even if we wanted to. + */ + + /* flat process-array ordered sampling, in this mode threads and processes are all placed flatly in the array, + * so this does the sampling for all monitored in no particular order */ + for(j = 0; j < vmon->array_allocated_nr; j++) { + vmon_proc_t *proc; + + if((proc = vmon->array[j])) { + vmon_proc_callback_t *cb; + + sample(vmon, proc); + + list_for_each_entry(cb, &proc->sample_callbacks, callbacks) { + cb->func(vmon, proc, cb->arg); + } + + /* age process, we use the presence of a parent as a flag indicating if the process is managed ala follow children/threads + * XXX TODO: should probably change the public _monitor() api to not contain a parent param then */ + if(!proc->parent && proc->is_new) { + proc->is_new = 0; + } + } + } + } else if((vmon->flags & VMON_FLAG_2PASS)) { + /* recursive heirarchical depth-first processes tree sampling, at each node threads come before children, done in two passes: + * Pass 1. samplers + * Pass 2. callbacks + * XXX this is the path vwm utilizes, everything else is for other uses, like implementing top-like programs. + */ + ret = sample_siblings_pass1(vmon, &vmon->processes); /* XXX TODO: errors */ + ret = sample_siblings_pass2(vmon, &vmon->processes); + } else { + /* recursive heirarchical depth-first processes tree sampling, at each node threads come before children, done in a single pass: + * Pass 1. samplers; callbacks (for every node) + */ + ret = sample_siblings(vmon, &vmon->processes); + } + + return ret; +} diff --git a/src/libvmon/vmon.h b/src/libvmon/vmon.h new file mode 100644 index 0000000..06a062b --- /dev/null +++ b/src/libvmon/vmon.h @@ -0,0 +1,308 @@ +#ifndef _VMON_H +#define _VMON_H + +#include +#include +#include +#include /* I use strcmp() in the type comparator definitions */ + +#include "bitmap.h" +#include "list.h" + +#define VMON_HTAB_SIZE 128 /* number of buckets in the processes hash table */ +#define VMON_ARRAY_GROWBY 5 /* number of elements to grow the processes array */ + +typedef enum _vmon_flags_t { + VMON_FLAG_NONE = 0, + VMON_FLAG_PROC_ARRAY = 1L, /* maintain a process array (useful if you need to do things like implement top(1) */ + VMON_FLAG_PROC_ALL = 1L << 1, /* monitor all the processes in the system (XXX this has some follow_children implications...) */ + VMON_FLAG_2PASS = 1L << 2, /* perform all sampling/wants in a first pass, then invoke all callbacks in second in vmon_sample(), important if your callbacks are layout-sensitive (vwm) */ +} vmon_flags_t; + +/* store ids, used as indices into the stores array, and shift offsets for the wants mask */ +typedef enum _vmon_sys_store_t { +#define vmon_want(_sym, _name, _func) VMON_STORE_ ## _sym, +#include "defs/sys_wants.def" + VMON_STORE_SYS_NR +} vmon_sys_store_t; + +typedef enum _vmon_sys_wants_t { + VMON_WANT_SYS_NONE = 0, +#define vmon_want(_sym, _name, _func) VMON_WANT_ ## _sym = 1L << VMON_STORE_ ## _sym, +#include "defs/sys_wants.def" +} vmon_sys_wants_t; + +typedef enum _vmon_proc_store_t { +#define vmon_want(_sym, _name, _func) VMON_STORE_ ## _sym, +#include "defs/proc_wants.def" + VMON_STORE_PROC_NR +} vmon_proc_store_t; + +typedef enum _vmon_proc_wants_t { + VMON_WANT_PROC_INHERIT = 0, +#define vmon_want(_sym, _name, _func) VMON_WANT_ ## _sym = 1L << VMON_STORE_ ## _sym, +#include "defs/proc_wants.def" + /* XXX: note proc_wants is internally overloaded in libvmon to communicate when a process is a thread-child of a process, so not all bits are available. */ +} vmon_proc_wants_t; + + +/* we add some new complex types */ +typedef struct _vmon_char_array_t { + char *array; + int len; + int alloc_len; +} vmon_char_array_t; + +typedef struct _vmon_str_array_t { + char **array; + int len; + int alloc_len; +} vmon_str_array_t; + + +/* system stat stuff (/proc/stat...) */ +typedef enum _vmon_sys_stat_sym_t { +#define VMON_ENUM_SYMBOLS +#include "defs/sys_stat.def" + VMON_SYS_STAT_NR /* append this symbol to the end so we have a count */ +} vmon_sys_stat_sym_t; + +typedef struct _vmon_sys_stat_t { + int stat_fd; + + char changed[BITNSLOTS(VMON_SYS_STAT_NR)]; /* bitmap for indicating changed fields */ + +#define VMON_DECLARE_MEMBERS +#include "defs/sys_stat.def" +} vmon_sys_stat_t; + + +/* system vm/mem stuff (/proc/meminfo, /proc/vmstat...) */ +typedef enum _vmon_sys_vm_sym_t { +#define VMON_ENUM_SYMBOLS +#include "defs/sys_vm.def" + VMON_SYS_VM_NR /* append this symbol to the end so we have a count */ +} vmon_sys_vm_sym_t; + +typedef struct _vmon_sys_vm_t { + int meminfo_fd; + + char changed[BITNSLOTS(VMON_SYS_VM_NR)]; /* bitmap for indicating changed fields */ + +#define VMON_DECLARE_MEMBERS +#include "defs/sys_vm.def" +} vmon_sys_vm_t; + + +/* stat things we always monitor for a process, regardless of the caller's wants */ +typedef enum _vmon_proc_stat_sym_t { +#define VMON_ENUM_SYMBOLS +#include "defs/proc_stat.def" + VMON_PROC_STAT_NR /* append this symbol to the end so we have a count */ +} vmon_proc_stat_sym_t; + +typedef struct _vmon_proc_stat_t { + int cmdline_fd, comm_fd, wchan_fd, stat_fd; /* per-process stat monitoring /proc/$pid/{wchan,stat} file handles */ + + char changed[BITNSLOTS(VMON_PROC_STAT_NR)]; /* bitmap for indicating changed fields */ + +#define VMON_DECLARE_MEMBERS +#include "defs/proc_stat.def" +} vmon_proc_stat_t; + + +/* vm-related per-process things we can monitor */ +typedef enum _vmon_proc_vm_sym_t { +#define VMON_ENUM_SYMBOLS +#include "defs/proc_vm.def" + VMON_PROC_VM_NR /* append this symbol to the end so we have a count */ +} vmon_proc_vm_sym_t; + +typedef struct _vmon_proc_vm_t { + int statm_fd; /* per-process vm monitoring /proc/$pid/statm file handle */ + + char changed[BITNSLOTS(VMON_PROC_VM_NR)]; /* bitmap for indicating changed fields */ + +#define VMON_DECLARE_MEMBERS +#include "defs/proc_vm.def" +} vmon_proc_vm_t; + + +/* io-related per-process things we can monitor */ +typedef enum _vmon_proc_io_sym_t { +#define VMON_ENUM_SYMBOLS +#include "defs/proc_io.def" + VMON_PROC_IO_NR /* append this symbol to the end so we have a count */ +} vmon_proc_io_sym_t; + +typedef struct _vmon_proc_io_t { + int io_fd; /* per-process io monitoring /proc/$pid/io file handle */ + + char changed[BITNSLOTS(VMON_PROC_IO_NR)]; /* bitmap for indicating changed fields */ + +#define VMON_DECLARE_MEMBERS +#include "defs/proc_io.def" +} vmon_proc_io_t; + + +/* follow children want context */ +typedef struct _vmon_proc_follow_children_t { + int children_fd; /* per-process children following /proc/$pid/task/$pid/children file handle */ +} vmon_proc_follow_children_t; + + +/* follow threads want context */ +typedef struct _vmon_proc_follow_threads_t { + DIR *task_dir; /* per-process threads monitoring /proc/$pid/task handle */ +} vmon_proc_follow_threads_t; + + +/* open files monitoring */ +typedef enum _vmon_proc_files_sym_t { +#define VMON_ENUM_SYMBOLS +#include "defs/proc_files.def" +} vmon_proc_files_sym_t; + +typedef enum _vmon_fobject_type_t { + VMON_FOBJECT_TYPE_UNRECOGNIZED = 0, + /* TODO, enumerate the possible opened fobject types, this should come out of a .def */ + VMON_FOBJECT_TYPE_PIPE, + VMON_FOBJECT_TYPE_SOCKET, + VMON_FOBJECT_TYPE_ANON, + VMON_FOBJECT_TYPE_NR +} vmon_fobject_type_t; + +typedef struct _vmon_fobject_t { + list_head_t bucket; /* fobjects hash table bucket this fobject belongs to */ + uint64_t inum; /* inode number */ + list_head_t ref_fds; /* referring fds list, this is a list of proc_fd_t's which appear to have this object open */ + int refcnt; /* reference count, this may be greater than the # of nodes in ref_fds, for instance the + monitoring of /proc/net/unix will maintain references to fobjects for every row, without + maintaing nodes on ref_fds. But there are certain fobjects which simply emerge due to + processes having them open (pipes) which are not explicitly monitored elsewhere, in those + cases the refcnt and number of nodes in ref_fds shall match. */ + vmon_fobject_type_t type; /* type for this fobject */ + + + /* TODO: possibly hook into the object-type-specific information here, if so, it should come out of .defs */ + /* XXX the question is do I want to introduce that resource allocation here as part of the fobject, or do I want + * it elsewhere and potentially optional? I think it makes sense to make it optional and triggered by asking for + * fobject detail monitoring, so instead of a union here we should have a pointer, and that pointer becomes useful + * when fobject-type monitors become active */ + void *foo; /* hook for caller's data, if needed (expected to be used together with fobject_[cd]tor_cb) */ +} vmon_fobject_t; + +typedef struct _vmon_proc_fd_t { + list_head_t fds; /* per-process files list node */ + int generation; /* generation number, for convenient detection of closed files */ + struct _vmon_proc_t *process; /* process this fd belongs to (annoying, but enables linking processes with fobject refs) */ + list_head_t ref_fds; /* ref_fds list node */ + vmon_fobject_t *object; /* the object instance this fd refers to (this object also contains the head for the refs list) */ + +#define VMON_DECLARE_MEMBERS +#include "defs/proc_files.def" +} vmon_proc_fd_t; + +typedef struct _vmon_proc_files_t { + int refcnt; /* reference count for dealing with sharing of open files (like threads...) */ + DIR *fd_dir; /* per-process files /proc/$pid/fd handle */ + list_head_t fds; /* per-process files linked list head */ +} vmon_proc_files_t; + + +/* TODO per-process VM stats monitoring */ + +struct _vmon_t; + + +/* list of callbacks is maintained for the per-process callbacks, it's convenient to do things like update multiple dynamic contexts associated with a given process monitor (think multiple windows) */ +typedef struct _vmon_proc_callback_t { + void (*func)(struct _vmon_t *, struct _vmon_proc_t *, void *); + void *arg; + list_head_t callbacks; +} vmon_proc_callback_t; + +typedef struct _vmon_proc_t { + list_head_t bucket; /* processes hash table bucket this process belongs to */ + + list_head_t children; /* head of the children of this process, empty when no children */ + list_head_t siblings; /* node in siblings list */ + list_head_t threads; /* head or node for the threads list, empty when process has no threads */ + + struct _vmon_proc_t *parent; /* reference to the parent */ + + int array_hint_pos; /* hint for the process's position in the array (when array maintenance has been requested) */ + + int pid; /* the PID of the process being monitored */ + + int generation; /* generation number, for convenient detection of exited processes */ + int refcnt; /* reference count on this node */ + vmon_proc_wants_t wants; /* wants @ this node */ + + vmon_proc_wants_t activity; /* bits updated when there's activity on the respective wants (stores have changes) */ + void *stores[VMON_STORE_PROC_NR]; /* pointers to the per-want per-monitored-process storage space */ + + /* callbacks invoked after sampling wants at and below this node */ + list_head_t sample_callbacks; /* list of callbacks to invoke sample_cb on behalf of (and supply as parameteres to) */ + void *foo; /* another per-process hook for whatever per-process uses the caller may have, but not managed by the api */ + + int children_changed:1; /* gets set when any of my immediate children have had is_new or is_stale set in the last sample */ + int threads_changed:1; /* gets set when any of my threads have had is_new or is_stale set in the last sample */ + int is_new:1; /* process is new in the most recent sample, automatically cleared on subsequent sample */ + int is_stale:1; /* process became stale in the most recent sample, automatically cleared on subsequent sample (process will be discarded) */ + int is_thread:1; /* process is a thread belonging to parent */ +} vmon_proc_t; + + +typedef struct _vmon_t { + DIR *proc_dir; /* /proc is opened @ vmon_init() */ + + /* TODO: rename this to something more contextually processes-specific */ + /* these array members are only relevant when array maintenance has been requested via VMON_FLAG_PROC_ARRAY @ vmon_init() */ + vmon_proc_t **array; /* array of processes being monitored (flat) */ + int array_allocated_nr; /* number of entries in the table */ + int array_active_nr; /* number of processes present in the table (including stale) */ + int array_hint_free; /* hint for a free element in the list */ + + list_head_t htab[VMON_HTAB_SIZE]; /* hash table for quickly finding processes being monitored */ + list_head_t processes; /* top of the processes heirarchy */ + list_head_t orphans; /* ephemeral list of processes orphaned this sample, orphans wind up becoming top-level processes */ + int processes_changed:1; /* flag set when the toplevel processes list changes */ + + list_head_t fobjects; /* XXX TODO: temporary single fobjects table, in the future this will be an array of type-indexed + * fobject hash tables */ + int fobjects_nr; /* XXX TODO: temporary simple counter of number of fobjects, this will change into something + * more like we have for the proceses array */ + vmon_flags_t flags; /* instance flags */ + vmon_sys_wants_t sys_wants; /* system-wide wants mask */ + vmon_proc_wants_t proc_wants; /* inherited per-process wants mask */ + + /* function tables for mapping of wants bits to functions (sys-wide and per-process) */ + int (*sys_funcs[VMON_STORE_SYS_NR])(struct _vmon_t *, void **); + int (*proc_funcs[VMON_STORE_PROC_NR])(struct _vmon_t *, vmon_proc_t *, void **); + + vmon_sys_wants_t activity; /* bits updated when there's activity on the respective wants (stores have changes) */ + void *stores[VMON_STORE_SYS_NR]; /* stores for the sys-wide wants */ + void (*sample_cb)(struct _vmon_t *); /* callback invoked after executing the selected sys wants (once per vmon_sample() call)) */ + + char buf[8192]; /* scratch buffer for private use XXX: it may make sense to dynamically size these... */ + char buf_bis[8192]; /* secondary scratch buffer for private use */ + int generation; /* generation counter for whatever might need it, increments with vmon_sample() calls */ + + /* callbacks we'll invoke in response to processes becoming instantiated and destroyed, when set */ + void (*proc_ctor_cb)(struct _vmon_t *, vmon_proc_t *); + void (*proc_dtor_cb)(struct _vmon_t *, vmon_proc_t *); + + /* callbacks we'll invoke in response to fobjects becoming instantiated and destroyed, when set */ + void (*fobject_ctor_cb)(struct _vmon_t *, vmon_fobject_t *); + void (*fobject_dtor_cb)(struct _vmon_t *, vmon_fobject_t *); +} vmon_t; + + +int vmon_init(vmon_t *, vmon_flags_t, vmon_sys_wants_t, vmon_proc_wants_t); +void vmon_destroy(vmon_t *); +vmon_proc_t * vmon_proc_monitor(vmon_t *, vmon_proc_t *, int, vmon_proc_wants_t, void (*)(vmon_t *, vmon_proc_t *, void *), void *); +void vmon_proc_unmonitor(vmon_t *, vmon_proc_t *, void (*)(vmon_t *, vmon_proc_t *, void *), void *); +int vmon_sample(vmon_t *); + +#endif diff --git a/src/list.h b/src/list.h new file mode 100644 index 0000000..48bca36 --- /dev/null +++ b/src/list.h @@ -0,0 +1,252 @@ +#ifndef __LIST_H +#define __LIST_H + +/* linux kernel linked list interface */ + +/* + * Simple doubly linked list implementation. + * + * Some of the internal functions ("__xxx") are useful when + * manipulating whole lists rather than single entries, as + * sometimes we already know the next/prev entries and we can + * generate better code by using them directly rather than + * using the generic single-entry routines. + */ + +typedef struct list_head { + struct list_head *next, *prev; +} list_head_t; + +#define LIST_HEAD_INIT(name) { &(name), &(name) } + +#define LIST_HEAD(name) \ + struct list_head name = LIST_HEAD_INIT(name) + +#define INIT_LIST_HEAD(ptr) do { \ + (ptr)->next = (ptr); (ptr)->prev = (ptr); \ +} while (0) + +/* + * Insert a new entry between two known consecutive entries. + * + * This is only for internal list manipulation where we know + * the prev/next entries already! + */ +static inline void __list_add(struct list_head *new, + struct list_head *prev, + struct list_head *next) +{ + next->prev = new; + new->next = next; + new->prev = prev; + prev->next = new; +} + +/** + * list_add - add a new entry + * @new: new entry to be added + * @head: list head to add it after + * + * Insert a new entry after the specified head. + * This is good for implementing stacks. + */ +static inline void list_add(struct list_head *new, struct list_head *head) +{ + __list_add(new, head, head->next); +} + +/** + * list_add_tail - add a new entry + * @new: new entry to be added + * @head: list head to add it before + * + * Insert a new entry before the specified head. + * This is useful for implementing queues. + */ +static inline void list_add_tail(struct list_head *new, struct list_head *head) +{ + __list_add(new, head->prev, head); +} + +/* + * Delete a list entry by making the prev/next entries + * point to each other. + * + * This is only for internal list manipulation where we know + * the prev/next entries already! + */ +static inline void __list_del(struct list_head *prev, struct list_head *next) +{ + next->prev = prev; + prev->next = next; +} + +/** + * list_del - deletes entry from list. + * @entry: the element to delete from the list. + * Note: list_empty on entry does not return true after this, the entry is in an undefined state. + */ +static inline void list_del(struct list_head *entry) +{ + __list_del(entry->prev, entry->next); + entry->next = (void *) 0; + entry->prev = (void *) 0; +} + +/** + * list_del_init - deletes entry from list and reinitialize it. + * @entry: the element to delete from the list. + */ +static inline void list_del_init(struct list_head *entry) +{ + __list_del(entry->prev, entry->next); + INIT_LIST_HEAD(entry); +} + +/** + * list_move - delete from one list and add as another's head + * @list: the entry to move + * @head: the head that will precede our entry + */ +static inline void list_move(struct list_head *list, struct list_head *head) +{ + __list_del(list->prev, list->next); + list_add(list, head); +} + +/** + * list_move_tail - delete from one list and add as another's tail + * @list: the entry to move + * @head: the head that will follow our entry + */ +static inline void list_move_tail(struct list_head *list, + struct list_head *head) +{ + __list_del(list->prev, list->next); + list_add_tail(list, head); +} + +/** + * list_empty - tests whether a list is empty + * @head: the list to test. + */ +static inline int list_empty(struct list_head *head) +{ + return head->next == head; +} + +static inline void __list_splice(struct list_head *list, + struct list_head *head) +{ + struct list_head *first = list->next; + struct list_head *last = list->prev; + struct list_head *at = head->next; + + first->prev = head; + head->next = first; + + last->next = at; + at->prev = last; +} + +/** + * list_splice - join two lists + * @list: the new list to add. + * @head: the place to add it in the first list. + */ +static inline void list_splice(struct list_head *list, struct list_head *head) +{ + if (!list_empty(list)) + __list_splice(list, head); +} + +/** + * list_splice_init - join two lists and reinitialise the emptied list. + * @list: the new list to add. + * @head: the place to add it in the first list. + * + * The list at @list is reinitialised + */ +static inline void list_splice_init(struct list_head *list, + struct list_head *head) +{ + if (!list_empty(list)) { + __list_splice(list, head); + INIT_LIST_HEAD(list); + } +} + +/** + * list_entry - get the struct for this entry + * @ptr: the &struct list_head pointer. + * @type: the type of the struct this is embedded in. + * @member: the name of the list_struct within the struct. + */ +#define list_entry(ptr, type, member) \ + ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member))) + +/** + * list_for_each - iterate over a list + * @pos: the &struct list_head to use as a loop counter. + * @head: the head for your list. + */ +#define list_for_each(pos, head) \ + for (pos = (head)->next; pos != (head); \ + pos = pos->next) +/** + * list_for_each_prev - iterate over a list backwards + * @pos: the &struct list_head to use as a loop counter. + * @head: the head for your list. + */ +#define list_for_each_prev(pos, head) \ + for (pos = (head)->prev; pos != (head); \ + pos = pos->prev) + +/** + * list_for_each_safe - iterate over a list safe against removal of list entry + * @pos: the &struct list_head to use as a loop counter. + * @n: another &struct list_head to use as temporary storage + * @head: the head for your list. + */ +#define list_for_each_safe(pos, n, head) \ + for (pos = (head)->next, n = pos->next; pos != (head); \ + pos = n, n = pos->next) + +/** + * list_for_each_entry - iterate over list of given type + * @pos: the type * to use as a loop counter. + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + */ +#define list_for_each_entry(pos, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member); \ + &pos->member != (head); \ + pos = list_entry(pos->member.next, typeof(*pos), member)) + +/** + * list_for_each_entry_prev - iterate over list of given type backwards + * @pos: the type * to use as a loop counter. + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + */ +#define list_for_each_entry_prev(pos, head, member) \ + for (pos = list_entry((head)->prev, typeof(*pos), member); \ + &pos->member != (head); \ + pos = list_entry(pos->member.prev, typeof(*pos), member)) + + +/** + * list_for_each_entry_safe - iterate over list of given type safe against removal of list entry + * @pos: the type * to use as a loop counter. + * @n: another type * to use as temporary storage + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + */ +#define list_for_each_entry_safe(pos, n, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member), \ + n = list_entry(pos->member.next, typeof(*pos), member); \ + &pos->member != (head); \ + pos = n, n = list_entry(n->member.next, typeof(*n), member)) + + +#endif diff --git a/src/logo.c b/src/logo.c new file mode 100644 index 0000000..8fe7291 --- /dev/null +++ b/src/logo.c @@ -0,0 +1,66 @@ +/* + * \/\/\ + * + * Copyright (C) 2012-2016 Vito Caputo - + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3 as published + * by the Free Software Foundation. + * + * 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 . + */ + +#include +#include + +#include "screen.h" +#include "vwm.h" + + /* startup logo */ + +/* animated \/\/\ logo done with simple XOR'd lines, a display of the WM being started and ready */ +#define VWM_LOGO_POINTS 6 +void vwm_draw_logo(vwm_t *vwm) +{ + int i; + unsigned int width, height, yoff, xoff; + XPoint points[VWM_LOGO_POINTS]; + const vwm_screen_t *scr = vwm_screen_find(vwm, VWM_SCREEN_REL_POINTER); + + XGrabServer(vwm->display); + + /* use the dimensions of the pointer-containing screen */ + width = scr->width; + height = scr->height; + xoff = scr->x_org; + yoff = scr->y_org + ((float)height * .333); + height /= 3; + + /* the logo gets shrunken vertically until it's essentially a flat line */ + while (height -= 2) { + /* scale and center the points to the screen size */ + for (i = 0; i < VWM_LOGO_POINTS; i++) { + points[i].x = xoff + (i * .2 * (float)width); + points[i].y = (i % 2 * (float)height) + yoff; + } + + XDrawLines(vwm->display, VWM_XROOT(vwm), vwm->gc, points, sizeof(points) / sizeof(XPoint), CoordModeOrigin); + XFlush(vwm->display); + usleep(3333); + XDrawLines(vwm->display, VWM_XROOT(vwm), vwm->gc, points, sizeof(points) / sizeof(XPoint), CoordModeOrigin); + XFlush(vwm->display); + + /* the width is shrunken as well, but only by as much as it is tall */ + yoff++; + width -= 4; + xoff += 2; + } + + XUngrabServer(vwm->display); +} diff --git a/src/logo.h b/src/logo.h new file mode 100644 index 0000000..51995c9 --- /dev/null +++ b/src/logo.h @@ -0,0 +1,8 @@ +#ifndef _LOGO_H +#define _LOGO_H + +typedef struct _vwm_t vwm_t; + +void vwm_draw_logo(vwm_t *vwm); + +#endif diff --git a/src/overlay.c b/src/overlay.c new file mode 100644 index 0000000..aeffd8e --- /dev/null +++ b/src/overlay.c @@ -0,0 +1,960 @@ +/* + * \/\/\ + * + * Copyright (C) 2012-2016 Vito Caputo - + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3 as published + * by the Free Software Foundation. + * + * 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 . + */ + +/* libvmon integration, warning: this gets a little crazy especially in the rendering. */ + +#include +#include +#include +#include +#include +#include + +#include "composite.h" +#include "libvmon/vmon.h" +#include "list.h" +#include "overlay.h" +#include "vwm.h" +#include "xwindow.h" + +/* TODO: move to overlay.h */ +#define OVERLAY_MASK_DEPTH 8 /* XXX: 1 would save memory, but Xorg isn't good at it */ +#define OVERLAY_MASK_FORMAT PictStandardA8 +#define OVERLAY_FIXED_FONT "-misc-fixed-medium-r-semicondensed--13-120-75-75-c-60-iso10646-1" +#define OVERLAY_ROW_HEIGHT 15 /* this should always be larger than the font height */ +#define OVERLAY_GRAPH_MIN_WIDTH 200 /* always create graphs at least this large */ +#define OVERLAY_GRAPH_MIN_HEIGHT (4 * OVERLAY_ROW_HEIGHT) +#define OVERLAY_ISTHREAD_ARGV "~" /* use this string to mark threads in the argv field */ +#define OVERLAY_NOCOMM_ARGV "#missed it!" /* use this string to substitute the command when missing in argv field */ + + +/* libvmon */ +static struct timeval maybe_sample, last_sample, this_sample = {0,0}; +static typeof(((vmon_sys_stat_t *)0)->user) last_user_cpu; +static typeof(((vmon_sys_stat_t *)0)->system) last_system_cpu; +static unsigned long long last_total, this_total, total_delta; +static unsigned long long last_idle, last_iowait, idle_delta, iowait_delta; +static vmon_t vmon; + +static float sampling_intervals[] = { + 1, /* ~1Hz */ + .1, /* ~10Hz */ + .05, /* ~20Hz */ + .025, /* ~40Hz */ + .01666}; /* ~60Hz */ +static int prev_sampling_interval = 1, sampling_interval = 1; + +/* space we need for every process being monitored */ +typedef struct _vwm_perproc_ctxt_t { + typeof(vmon.generation) generation; + typeof(((vmon_proc_stat_t *)0)->utime) last_utime; + typeof(((vmon_proc_stat_t *)0)->stime) last_stime; + typeof(((vmon_proc_stat_t *)0)->utime) utime_delta; + typeof(((vmon_proc_stat_t *)0)->stime) stime_delta; +} vwm_perproc_ctxt_t; + +/* Compositing / Overlays */ +static XFontStruct *overlay_font; +static GC text_gc; +static XRenderPictureAttributes pa_repeat = { .repeat = 1 }; +static XRenderPictureAttributes pa_no_repeat = { .repeat = 0 }; +static Picture overlay_shadow_fill, /* TODO: the repetition here smells like an XMacro waiting to happen */ + overlay_text_fill, + overlay_bg_fill, + overlay_snowflakes_text_fill, + overlay_grapha_fill, + overlay_graphb_fill, + overlay_finish_fill; +static XRenderColor overlay_visible_color = { 0xffff, 0xffff, 0xffff, 0xffff }, + overlay_shadow_color = { 0x0000, 0x0000, 0x0000, 0x8800}, + overlay_bg_color = { 0x0, 0x1000, 0x0, 0x9000}, + overlay_div_color = { 0x2000, 0x3000, 0x2000, 0x9000}, + overlay_snowflakes_visible_color = { 0xd000, 0xd000, 0xd000, 0x8000 }, + overlay_trans_color = {0x00, 0x00, 0x00, 0x00}, + overlay_grapha_color = { 0xff00, 0x0000, 0x0000, 0x3000 }, /* ~red */ + overlay_graphb_color = { 0x0000, 0xffff, 0xffff, 0x3000 }; /* ~cyan */ + + +/* we need a copy of this pointer for the vmon callback :( */ +static vwm_t *vwm_ptr; + +/* moves what's below a given row up above it if specified, the row becoming discarded */ +static void snowflake_row(vwm_t *vwm, vwm_xwindow_t *xwin, Picture pic, int copy, int row) +{ + VWM_TRACE("pid=%i xwin=%p row=%i copy=%i heirarhcy_end=%i", xwin->monitor->pid, xwin, row, copy, xwin->overlay.heirarchy_end); + + if (copy) { + /* copy row to tmp */ + XRenderComposite(vwm->display, PictOpSrc, pic, None, xwin->overlay.tmp_picture, + 0, row * OVERLAY_ROW_HEIGHT, /* src */ + 0, 0, /* mask */ + 0, 0, /* dest */ + xwin->overlay.width, OVERLAY_ROW_HEIGHT); /* dimensions */ + } + + /* shift up */ + XRenderChangePicture(vwm->display, pic, CPRepeat, &pa_no_repeat); + XRenderComposite(vwm->display, PictOpSrc, pic, None, pic, + 0, (1 + row) * OVERLAY_ROW_HEIGHT, /* src */ + 0, 0, /* mask */ + 0, row * OVERLAY_ROW_HEIGHT, /* dest */ + xwin->overlay.width, (1 + xwin->overlay.heirarchy_end) * OVERLAY_ROW_HEIGHT - (1 + row) * OVERLAY_ROW_HEIGHT); /* dimensions */ + XRenderChangePicture(vwm->display, pic, CPRepeat, &pa_repeat); + + if (copy) { + /* copy tmp to top of snowflakes */ + XRenderComposite(vwm->display, PictOpSrc, xwin->overlay.tmp_picture, None, pic, + 0, 0, /* src */ + 0, 0, /* mask */ + 0, (xwin->overlay.heirarchy_end) * OVERLAY_ROW_HEIGHT, /* dest */ + xwin->overlay.width, OVERLAY_ROW_HEIGHT); /* dimensions */ + } else { + /* clear the snowflake row */ + XRenderFillRectangle(vwm->display, PictOpSrc, pic, &overlay_trans_color, + 0, (xwin->overlay.heirarchy_end) * OVERLAY_ROW_HEIGHT, /* dest */ + xwin->overlay.width, OVERLAY_ROW_HEIGHT); /* dimensions */ + } +} + +/* XXX TODO libvmon automagic children following races with explicit X client pid monitoring with different outcomes, it should be irrelevant which wins, + * currently the only visible difference is the snowflakes gap (heirarchy_end) varies, which is why I haven't bothered to fix it, I barely even notice. + */ + +/* shifts what's below a given row down a row, and clears the row, preparing it for populating */ +static void allocate_row(vwm_t *vwm, vwm_xwindow_t *xwin, Picture pic, int row) +{ + VWM_TRACE("pid=%i xwin=%p row=%i", xwin->monitor->pid, xwin, row); + + /* shift everything below the row down */ + XRenderComposite(vwm->display, PictOpSrc, pic, None, pic, + 0, row * OVERLAY_ROW_HEIGHT, /* src */ + 0, 0, /* mask */ + 0, (1 + row) * OVERLAY_ROW_HEIGHT, /* dest */ + xwin->overlay.width, xwin->overlay.height - (1 + row) * OVERLAY_ROW_HEIGHT); /* dimensions */ + /* fill the space created with transparent pixels */ + XRenderFillRectangle(vwm->display, PictOpSrc, pic, &overlay_trans_color, + 0, row * OVERLAY_ROW_HEIGHT, /* dest */ + xwin->overlay.width, OVERLAY_ROW_HEIGHT); /* dimensions */ +} + + +/* shadow a row from the text layer in the shadow layer */ +static void shadow_row(vwm_t *vwm, vwm_xwindow_t *xwin, int row) +{ + /* the current technique for creating the shadow is to simply render the text at +1/-1 pixel offsets on both axis in translucent black */ + XRenderComposite(vwm->display, PictOpSrc, overlay_shadow_fill, xwin->overlay.text_picture, xwin->overlay.shadow_picture, + 0, 0, + -1, row * OVERLAY_ROW_HEIGHT, + 0, row * OVERLAY_ROW_HEIGHT, + xwin->attrs.width, OVERLAY_ROW_HEIGHT); + + XRenderComposite(vwm->display, PictOpOver, overlay_shadow_fill, xwin->overlay.text_picture, xwin->overlay.shadow_picture, + 0, 0, + 0, -1 + row * OVERLAY_ROW_HEIGHT, + 0, row * OVERLAY_ROW_HEIGHT, + xwin->attrs.width, OVERLAY_ROW_HEIGHT); + + XRenderComposite(vwm->display, PictOpOver, overlay_shadow_fill, xwin->overlay.text_picture, xwin->overlay.shadow_picture, + 0, 0, + 1, row * OVERLAY_ROW_HEIGHT, + 0, row * OVERLAY_ROW_HEIGHT, + xwin->attrs.width, OVERLAY_ROW_HEIGHT); + + XRenderComposite(vwm->display, PictOpOver, overlay_shadow_fill, xwin->overlay.text_picture, xwin->overlay.shadow_picture, + 0, 0, + 0, 1 + row * OVERLAY_ROW_HEIGHT, + 0, row * OVERLAY_ROW_HEIGHT, + xwin->attrs.width, OVERLAY_ROW_HEIGHT); +} + + +/* simple helper to map the vmon per-proc argv array into an XTextItem array, deals with threads vs. processes and the possibility of the comm field not getting read in before the process exited... */ +static void argv2xtext(vmon_proc_t *proc, XTextItem *items, int *nr_items) /* XXX TODO: reallocate items when too small... */ +{ + int i; + int nr = 0; + + if (proc->is_thread) { /* stick the thread marker at the start of threads */ + items[0].nchars = sizeof(OVERLAY_ISTHREAD_ARGV) - 1; + items[0].chars = OVERLAY_ISTHREAD_ARGV; + items[0].delta = 4; + items[0].font = None; + nr++; + } + + if (((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->comm.len) { + items[nr].nchars = ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->comm.len - 1; + items[nr].chars = ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->comm.array; + } else { + /* sometimes a process is so ephemeral we don't manage to sample its comm, XXX TODO: we always have a pid, stringify it? */ + items[nr].nchars = sizeof(OVERLAY_NOCOMM_ARGV) - 1; + items[nr].chars = OVERLAY_NOCOMM_ARGV; + } + items[nr].delta = 4; + items[nr].font = None; + nr++; + + for (i = 1; i < ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->argc; nr++, i++) { + items[nr].chars = ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->argv[i]; + items[nr].nchars = strlen(((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->argv[i]); /* TODO: libvmon should inform us of the length */ + items[nr].delta = 4; + items[nr].font = None; + } + + (*nr_items) = nr; +} + + +/* helper for counting number of existing descendants subtrees */ +static int count_rows(vmon_proc_t *proc) { + int count = 1; /* XXX maybe suppress proc->is_new? */ + vmon_proc_t *child; + + if (!proc->is_thread) { + list_for_each_entry(child, &proc->threads, threads) { + count += count_rows(child); + } + } + + list_for_each_entry(child, &proc->children, siblings) { + count += count_rows(child); + } + + return count; +} + + +/* recursive draw function for the consolidated version of the overlay rendering which also implements snowflakes */ +static void draw_overlay(vwm_t *vwm, vwm_xwindow_t *xwin, vmon_proc_t *proc, int *depth, int *row) +{ + vmon_proc_t *child; + vwm_perproc_ctxt_t *proc_ctxt = proc->foo; + vmon_proc_stat_t *proc_stat = proc->stores[VMON_STORE_PROC_STAT]; + + /* graph variables */ + int a_height, b_height; + double utime_delta, stime_delta; + + /* text variables */ + char str[256]; + int str_len; + XTextItem items[1024]; /* XXX TODO: dynamically allocate this and just keep it at the high water mark.. create a struct to encapsulate this, nr_items, and alloc_items... */ + int nr_items; + int direction, ascent, descent; + XCharStruct charstruct; + + if ((*row)) { /* except row 0 (Idle/IOWait graph), handle any stale and new processes/threads */ + if (proc->is_stale) { + /* what to do when a process (subtree) has gone away */ + static int in_stale = 0; + int in_stale_entrypoint = 0; + + /* I snowflake the stale processes from the leaves up for a more intuitive snowflake order... + * (I expect the command at the root of the subtree to appear at the top of the snowflakes...) */ + /* This does require that I do a separate forward recursion to determine the number of rows + * so I can correctly snowflake in reverse */ + if (!in_stale) { + VWM_TRACE("entered stale at xwin=%p depth=%i row=%i", xwin, *depth, *row); + in_stale_entrypoint = in_stale = 1; + (*row) += count_rows(proc) - 1; + } + + (*depth)++; + list_for_each_entry_prev(child, &proc->children, siblings) { + draw_overlay(vwm, xwin, child, depth, row); + (*row)--; + } + + if (!proc->is_thread) { + list_for_each_entry_prev(child, &proc->threads, threads) { + draw_overlay(vwm, xwin, child, depth, row); + (*row)--; + } + } + (*depth)--; + + VWM_TRACE("%i (%.*s) is stale @ depth %i row %i is_thread=%i", proc->pid, + ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->comm.len - 1, + ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->comm.array, + (*depth), (*row), proc->is_thread); + + /* stamp the graphs with the finish line */ + XRenderComposite(vwm->display, PictOpSrc, overlay_finish_fill, None, xwin->overlay.grapha_picture, + 0, 0, /* src x, y */ + 0, 0, /* mask x, y */ + xwin->overlay.phase, (*row) * OVERLAY_ROW_HEIGHT, /* dst x, y */ + 1, OVERLAY_ROW_HEIGHT - 1); + XRenderComposite(vwm->display, PictOpSrc, overlay_finish_fill, None, xwin->overlay.graphb_picture, + 0, 0, /* src x, y */ + 0, 0, /* mask x, y */ + xwin->overlay.phase, (*row) * OVERLAY_ROW_HEIGHT, /* dst x, y */ + 1, OVERLAY_ROW_HEIGHT - 1); + + /* extract the row from the various layers */ + snowflake_row(vwm, xwin, xwin->overlay.grapha_picture, 1, (*row)); + snowflake_row(vwm, xwin, xwin->overlay.graphb_picture, 1, (*row)); + snowflake_row(vwm, xwin, xwin->overlay.text_picture, 0, (*row)); + snowflake_row(vwm, xwin, xwin->overlay.shadow_picture, 0, (*row)); + xwin->overlay.snowflakes_cnt++; + + /* stamp the name (and whatever else we include) into overlay.text_picture */ + argv2xtext(proc, items, &nr_items); + XDrawText(vwm->display, xwin->overlay.text_pixmap, text_gc, + 5, (xwin->overlay.heirarchy_end + 1) * OVERLAY_ROW_HEIGHT - 3,/* dst x, y */ + items, nr_items); + shadow_row(vwm, xwin, xwin->overlay.heirarchy_end); + + xwin->overlay.heirarchy_end--; + + if (in_stale_entrypoint) { + VWM_TRACE("exited stale at xwin=%p depth=%i row=%i", xwin, *depth, *row); + in_stale = 0; + } + + return; + } else if (proc->is_new) { + /* what to do when a process has been introduced */ + VWM_TRACE("%i is new", proc->pid); + + allocate_row(vwm, xwin, xwin->overlay.grapha_picture, (*row)); + allocate_row(vwm, xwin, xwin->overlay.graphb_picture, (*row)); + allocate_row(vwm, xwin, xwin->overlay.text_picture, (*row)); + allocate_row(vwm, xwin, xwin->overlay.shadow_picture, (*row)); + + xwin->overlay.heirarchy_end++; + } + } + +/* CPU utilization graphs */ + if (!(*row)) { + /* XXX: sortof kludged in IOWait and Idle % @ row 0 */ + stime_delta = iowait_delta; + utime_delta = idle_delta; + } else { + /* use the generation number to avoid recomputing this stuff for callbacks recurring on the same process in the same sample */ + if (proc_ctxt->generation != vmon.generation) { + proc_ctxt->stime_delta = proc_stat->stime - proc_ctxt->last_stime; + proc_ctxt->utime_delta = proc_stat->utime - proc_ctxt->last_utime; + proc_ctxt->last_utime = proc_stat->utime; + proc_ctxt->last_stime = proc_stat->stime; + + proc_ctxt->generation = vmon.generation; + } + + if (proc->is_new) { + /* we need a minimum of two samples before we can compute a delta to plot, + * so we suppress that and instead mark the start of monitoring with an impossible 100% of both graph contexts, a starting line. */ + stime_delta = utime_delta = total_delta; + } else { + stime_delta = proc_ctxt->stime_delta; + utime_delta = proc_ctxt->utime_delta; + } + } + + /* compute the bar heights for this sample */ + a_height = (stime_delta / total_delta * (double)(OVERLAY_ROW_HEIGHT - 1)); /* give up 1 pixel for the div */ + b_height = (utime_delta / total_delta * (double)(OVERLAY_ROW_HEIGHT - 1)); + + /* round up to 1 pixel when the scaled result is a fraction less than 1, + * I want to at least see 1 pixel blips for the slightest cpu utilization */ + if (stime_delta && !a_height) a_height = 1; + if (utime_delta && !b_height) b_height = 1; + + /* draw the two bars for this sample at the current phase in the graphs, note the first is ceiling-based, second floor-based */ + XRenderFillRectangle(vwm->display, PictOpSrc, xwin->overlay.grapha_picture, &overlay_visible_color, + xwin->overlay.phase, (*row) * OVERLAY_ROW_HEIGHT, /* dst x, y */ + 1, a_height); /* dst w, h */ + XRenderFillRectangle(vwm->display, PictOpSrc, xwin->overlay.graphb_picture, &overlay_visible_color, + xwin->overlay.phase, (*row) * OVERLAY_ROW_HEIGHT + (OVERLAY_ROW_HEIGHT - b_height) - 1, /* dst x, y */ + 1, b_height); /* dst w, h */ + + if (!(*row)) { + /* here's where the Idle/IOWait row drawing concludes */ + if (1 /* FIXME TODO compositing_mode*/) { + snprintf(str, sizeof(str), "\\/\\/\\ %2iHz %n", (int)(sampling_interval < 0 ? 0 : 1 / sampling_intervals[sampling_interval]), &str_len); + /* TODO: I clear and redraw this row every time, which is unnecessary, small optimization would be to only do so when: + * - overlay resized, and then constrain the clear to the affected width + * - Hz changed + */ + XRenderFillRectangle(vwm->display, PictOpSrc, xwin->overlay.text_picture, &overlay_trans_color, + 0, 0, /* dst x, y */ + xwin->attrs.width, OVERLAY_ROW_HEIGHT); /* dst w, h */ + XTextExtents(overlay_font, str, str_len, &direction, &ascent, &descent, &charstruct); + XDrawString(vwm->display, xwin->overlay.text_pixmap, text_gc, + xwin->attrs.width - charstruct.width, OVERLAY_ROW_HEIGHT - 3, /* dst x, y */ + str, str_len); + shadow_row(vwm, xwin, 0); + } + (*row)++; + draw_overlay(vwm, xwin, proc, depth, row); + return; + } + +/* process heirarchy text and accompanying per-process details like wchan/pid/state... */ + if (1 /* FIXME TODO compositing_mode */) { /* this stuff can be skipped when monitors aren't visible */ + /* TODO: make the columns interactively configurable @ runtime */ + if (!proc->is_new) { + /* XXX for now always clear the row, this should be capable of being optimized in the future (if the datums driving the text haven't changed...) */ + XRenderFillRectangle(vwm->display, PictOpSrc, xwin->overlay.text_picture, &overlay_trans_color, + 0, (*row) * OVERLAY_ROW_HEIGHT, /* dst x, y */ + xwin->overlay.width, OVERLAY_ROW_HEIGHT); /* dst w, h */ + } + + /* put the process' wchan, state, and PID columns @ the far right */ + if (proc->is_thread || list_empty(&proc->threads)) { /* only threads or non-threaded processes include the wchan and state */ + snprintf(str, sizeof(str), " %.*s %5i %c %n", + proc_stat->wchan.len, + proc_stat->wchan.len == 1 && proc_stat->wchan.array[0] == '0' ? "-" : proc_stat->wchan.array, + proc->pid, + proc_stat->state, + &str_len); + } else { /* we're a process having threads, suppress the wchan and state, as they will be displayed for the thread of same pid */ + snprintf(str, sizeof(str), " %5i %n", proc->pid, &str_len); + } + + XTextExtents(overlay_font, str, str_len, &direction, &ascent, &descent, &charstruct); + + /* the process' comm label indented according to depth, followed with their respective argv's */ + argv2xtext(proc, items, &nr_items); + XDrawText(vwm->display, xwin->overlay.text_pixmap, text_gc, + (*depth) * (OVERLAY_ROW_HEIGHT / 2), ((*row) + 1) * OVERLAY_ROW_HEIGHT - 3, /* dst x, y */ + items, nr_items); + + /* ensure the area for the rest of the stuff is cleared, we don't put much text into thread rows so skip it for those. */ + if (!proc->is_thread) { + XRenderFillRectangle(vwm->display, PictOpSrc, xwin->overlay.text_picture, &overlay_trans_color, + xwin->attrs.width - charstruct.width, (*row) * OVERLAY_ROW_HEIGHT, /* dst x,y */ + xwin->overlay.width - (xwin->attrs.width - charstruct.width), OVERLAY_ROW_HEIGHT); /* dst w,h */ + } + + XDrawString(vwm->display, xwin->overlay.text_pixmap, text_gc, + xwin->attrs.width - charstruct.width, ((*row) + 1) * OVERLAY_ROW_HEIGHT - 3, /* dst x, y */ + str, str_len); + + /* only if this process isn't the root process @ the window shall we consider all relational drawing conditions */ + if (proc != xwin->monitor) { + vmon_proc_t *ancestor, *sibling, *last_sibling = NULL; + struct list_head *rem; + int needs_tee = 0; + int bar_x = 0, bar_y = 0; + int sub; + + /* XXX: everything done in this code block only dirties _this_ process' row in the rendered overlay output */ + + /* walk up the ancestors until reaching xwin->monitor, any ancestors we encounter which have more siblings we draw a vertical bar for */ + /* this draws the |'s in something like: | | | | comm */ + for (sub = 1, ancestor = proc->parent; ancestor && ancestor != xwin->monitor; ancestor = ancestor->parent) { + sub++; + bar_x = ((*depth) - sub) * (OVERLAY_ROW_HEIGHT / 2) + 4; + bar_y = ((*row) + 1) * OVERLAY_ROW_HEIGHT; + + /* determine if the ancestor has remaining siblings which are not stale, if so, draw a connecting bar at its depth */ + for (rem = ancestor->siblings.next; rem != &ancestor->parent->children; rem = rem->next) { + if (!(list_entry(rem, vmon_proc_t, siblings)->is_stale)) { + XDrawLine(vwm->display, xwin->overlay.text_pixmap, text_gc, + bar_x, bar_y - OVERLAY_ROW_HEIGHT, /* dst x1, y1 */ + bar_x, bar_y); /* dst x2, y2 (vertical line) */ + break; /* stop looking for more siblings at this ancestor when we find one that isn't stale */ + } + } + } + + /* determine if _any_ of our siblings have children requiring us to draw a tee immediately before our comm string. + * The only sibling which doesn't cause this to happen is the last one in the children list, if it has children it has no impact on its remaining + * siblings, as there are none. + * + * This draws the + in something like: | | | | +comm + */ + + /* find the last sibling (this has to be done due to the potential for stale siblings at the tail, and we'd rather not repeatedly check for it) */ + list_for_each_entry(sibling, &proc->parent->children, siblings) { + if (!sibling->is_stale) last_sibling = sibling; + } + + /* now look for siblings with non-stale children to determine if a tee is needed, ignoring the last sibling */ + list_for_each_entry(sibling, &proc->parent->children, siblings) { + /* skip stale siblings, they aren't interesting as they're invisible, and the last sibling has no bearing on wether we tee or not. */ + if (sibling->is_stale || sibling == last_sibling) continue; + + /* if any of the other siblings have children which are not stale, put a tee in front of our name, but ignore stale children */ + list_for_each_entry(child, &sibling->children, siblings) { + if (!child->is_stale) { + needs_tee = 1; + break; + } + } + + /* if we still don't think we need a tee, check if there are threads */ + if (!needs_tee) { + list_for_each_entry(child, &sibling->threads, threads) { + if (!child->is_stale) { + needs_tee = 1; + break; + } + } + } + + /* found a tee is necessary, all that's left is to determine if the tee is a corner and draw it accordingly, stopping the search. */ + if (needs_tee) { + bar_x = ((*depth) - 1) * (OVERLAY_ROW_HEIGHT / 2) + 4; + + /* if we're the last sibling, corner the tee by shortening the vbar */ + if (proc == last_sibling) { + XDrawLine(vwm->display, xwin->overlay.text_pixmap, text_gc, + bar_x, bar_y - OVERLAY_ROW_HEIGHT, /* dst x1, y1 */ + bar_x, bar_y - 4); /* dst x2, y2 (vertical bar) */ + } else { + XDrawLine(vwm->display, xwin->overlay.text_pixmap, text_gc, + bar_x, bar_y - OVERLAY_ROW_HEIGHT, /* dst x1, y1 */ + bar_x, bar_y); /* dst x2, y2 (vertical bar) */ + } + + XDrawLine(vwm->display, xwin->overlay.text_pixmap, text_gc, + bar_x, bar_y - 4, /* dst x1, y1 */ + bar_x + 2, bar_y - 4); /* dst x2, y2 (horizontal bar) */ + + /* terminate the outer sibling loop upon drawing the tee... */ + break; + } + } + } + shadow_row(vwm, xwin, (*row)); + } + + (*row)++; + + /* recur any threads first, then any children processes */ + (*depth)++; + if (!proc->is_thread) { /* XXX: the threads member serves as the list head only when not a thread */ + list_for_each_entry(child, &proc->threads, threads) { + draw_overlay(vwm, xwin, child, depth, row); + } + } + + list_for_each_entry(child, &proc->children, siblings) { + draw_overlay(vwm, xwin, child, depth, row); + } + (*depth)--; +} + + +/* consolidated version of overlay text and graph rendering, makes snowflakes integration cleaner, this always gets called regadless of the overlays mode */ +static void maintain_overlay(vwm_t *vwm, vwm_xwindow_t *xwin) +{ + int row = 0, depth = 0; + + if (!xwin->monitor || !xwin->monitor->stores[VMON_STORE_PROC_STAT]) return; + + /* TODO: + * I side effect of responding to window resizes in this function is there's a latency proportional to the current sample_interval. + * Something to fix is to resize the overlays when the window resizes. + * However, simply resizing the overlays is insufficient. Their contents need to be redrawn in the new dimensions, this is where it + * gets annoying. The current maintain/draw_overlay makes assumptions about being run from the periodic vmon per-process callback. + * There needs to be a redraw mode added where draw_overlay is just reconstructing the current state, which requires that we suppress + * the phase advance and in maintain_overlay() and just enter draw_overlay() to redraw everything for the same generation. + * So this probably requires some tweaking of draw_overlay() as well as maintain_overlay(). I want to be able tocall mainta_overlays() + * from anywhere, and have it detect if it's being called on the same generation or if the generation has advanced. + * For now, the monitors will just be a little latent in window resizes which is pretty harmless artifact. + */ + + /* if the window is larger than the overlays currently are, enlarge them */ + if (xwin->attrs.width > xwin->overlay.width || xwin->attrs.height > xwin->overlay.height) { + vwm_overlay_t existing; + Pixmap pixmap; + + existing = xwin->overlay; + + xwin->overlay.width = MAX(xwin->overlay.width, MAX(xwin->attrs.width, OVERLAY_GRAPH_MIN_WIDTH)); + xwin->overlay.height = MAX(xwin->overlay.height, MAX(xwin->attrs.height, OVERLAY_GRAPH_MIN_HEIGHT)); + + pixmap = XCreatePixmap(vwm->display, VWM_XROOT(vwm), xwin->overlay.width, xwin->overlay.height, OVERLAY_MASK_DEPTH); + xwin->overlay.grapha_picture = XRenderCreatePicture(vwm->display, pixmap, XRenderFindStandardFormat(vwm->display, OVERLAY_MASK_FORMAT), CPRepeat, &pa_repeat); + XFreePixmap(vwm->display, pixmap); + XRenderFillRectangle(vwm->display, PictOpSrc, xwin->overlay.grapha_picture, &overlay_trans_color, 0, 0, xwin->overlay.width, xwin->overlay.height); + + pixmap = XCreatePixmap(vwm->display, VWM_XROOT(vwm), xwin->overlay.width, xwin->overlay.height, OVERLAY_MASK_DEPTH); + xwin->overlay.graphb_picture = XRenderCreatePicture(vwm->display, pixmap, XRenderFindStandardFormat(vwm->display, OVERLAY_MASK_FORMAT), CPRepeat, &pa_repeat); + XFreePixmap(vwm->display, pixmap); + XRenderFillRectangle(vwm->display, PictOpSrc, xwin->overlay.graphb_picture, &overlay_trans_color, 0, 0, xwin->overlay.width, xwin->overlay.height); + + pixmap = XCreatePixmap(vwm->display, VWM_XROOT(vwm), xwin->overlay.width, OVERLAY_ROW_HEIGHT, OVERLAY_MASK_DEPTH); + xwin->overlay.tmp_picture = XRenderCreatePicture(vwm->display, pixmap, XRenderFindStandardFormat(vwm->display, OVERLAY_MASK_FORMAT), 0, NULL); + XFreePixmap(vwm->display, pixmap); + + /* keep the text_pixmap reference around for XDrawText usage */ + xwin->overlay.text_pixmap = XCreatePixmap(vwm->display, VWM_XROOT(vwm), xwin->overlay.width, xwin->overlay.height, OVERLAY_MASK_DEPTH); + xwin->overlay.text_picture = XRenderCreatePicture(vwm->display, xwin->overlay.text_pixmap, XRenderFindStandardFormat(vwm->display, OVERLAY_MASK_FORMAT), 0, NULL); + XRenderFillRectangle(vwm->display, PictOpSrc, xwin->overlay.text_picture, &overlay_trans_color, 0, 0, xwin->overlay.width, xwin->overlay.height); + + pixmap = XCreatePixmap(vwm->display, VWM_XROOT(vwm), xwin->overlay.width, xwin->overlay.height, OVERLAY_MASK_DEPTH); + xwin->overlay.shadow_picture = XRenderCreatePicture(vwm->display, pixmap, XRenderFindStandardFormat(vwm->display, OVERLAY_MASK_FORMAT), 0, NULL); + XFreePixmap(vwm->display, pixmap); + XRenderFillRectangle(vwm->display, PictOpSrc, xwin->overlay.shadow_picture, &overlay_trans_color, 0, 0, xwin->overlay.width, xwin->overlay.height); + + pixmap = XCreatePixmap(vwm->display, VWM_XROOT(vwm), xwin->overlay.width, xwin->overlay.height, 32); + xwin->overlay.picture = XRenderCreatePicture(vwm->display, pixmap, XRenderFindStandardFormat(vwm->display, PictStandardARGB32), 0, NULL); + XFreePixmap(vwm->display, pixmap); + + if (existing.width) { + /* XXX: note the graph pictures are copied from their current phase in the x dimension */ + XRenderComposite(vwm->display, PictOpSrc, existing.grapha_picture, None, xwin->overlay.grapha_picture, + existing.phase, 0, /* src x, y */ + 0, 0, /* mask x, y */ + 0, 0, /* dest x, y */ + existing.width, existing.height); + XRenderComposite(vwm->display, PictOpSrc, existing.graphb_picture, None, xwin->overlay.graphb_picture, + existing.phase, 0, /* src x, y */ + 0, 0, /* mask x, y */ + 0, 0, /* dest x, y */ + existing.width, existing.height); + XRenderComposite(vwm->display, PictOpSrc, existing.text_picture, None, xwin->overlay.text_picture, + 0, 0, /* src x, y */ + 0, 0, /* mask x, y */ + 0, 0, /* dest x, y */ + existing.width, existing.height); + XRenderComposite(vwm->display, PictOpSrc, existing.shadow_picture, None, xwin->overlay.shadow_picture, + 0, 0, /* src x, y */ + 0, 0, /* mask x, y */ + 0, 0, /* dest x, y */ + existing.width, existing.height); + XRenderComposite(vwm->display, PictOpSrc, existing.picture, None, xwin->overlay.picture, + 0, 0, /* src x, y */ + 0, 0, /* mask x, y */ + 0, 0, /* dest x, y */ + existing.width, existing.height); + xwin->overlay.phase = 0; /* having unrolled the existing graph[ab] pictures into the larger ones, phase is reset to 0 */ + XRenderFreePicture(vwm->display, existing.grapha_picture); + XRenderFreePicture(vwm->display, existing.graphb_picture); + XRenderFreePicture(vwm->display, existing.tmp_picture); + XRenderFreePicture(vwm->display, existing.text_picture); + XFreePixmap(vwm->display, existing.text_pixmap); + XRenderFreePicture(vwm->display, existing.shadow_picture); + XRenderFreePicture(vwm->display, existing.picture); + } + } + + xwin->overlay.phase += (xwin->overlay.width - 1); /* simply change this to .phase++ to scroll the other direction */ + xwin->overlay.phase %= xwin->overlay.width; + XRenderFillRectangle(vwm->display, PictOpSrc, xwin->overlay.grapha_picture, &overlay_trans_color, xwin->overlay.phase, 0, 1, xwin->overlay.height); + XRenderFillRectangle(vwm->display, PictOpSrc, xwin->overlay.graphb_picture, &overlay_trans_color, xwin->overlay.phase, 0, 1, xwin->overlay.height); + + /* recursively draw the monitored processes to the overlay */ + draw_overlay(vwm, xwin, xwin->monitor, &depth, &row); +} + + +/* this callback gets invoked at sample time for every process we've explicitly monitored (not autofollowed children/threads) + * It's where we update the cumulative data for all windows, including the graph masks, regardless of their visibility + * It's also where we compose the graphs and text for visible windows into a picture ready for compositing with the window contents */ +static void proc_sample_callback(vmon_t *vmon, vmon_proc_t *proc, vwm_xwindow_t *xwin) +{ + //VWM_TRACE("proc=%p xwin=%p", proc, xwin); + /* render the various always-updated overlays, this is the component we do regardless of the overlays mode and window visibility, + * essentially the incrementally rendered/historic components */ + maintain_overlay(vwm_ptr, xwin); + + /* if we've updated overlays for a mapped window, kick the compositor to do the costly parts of overlay drawing and compositing. */ + if (vwm_xwin_is_mapped(vwm_ptr, xwin)) vwm_composite_repaint_needed(vwm_ptr); +} + + +/* this callback gets invoked at sample time once "per sys" */ +static void sample_callback(vmon_t *_vmon) +{ + vmon_sys_stat_t *sys_stat = vmon.stores[VMON_STORE_SYS_STAT]; + this_total = sys_stat->user + sys_stat->nice + sys_stat->system + + sys_stat->idle + sys_stat->iowait + sys_stat->irq + + sys_stat->softirq + sys_stat->steal + sys_stat->guest; + + total_delta = this_total - last_total; + idle_delta = sys_stat->idle - last_idle; + iowait_delta = sys_stat->iowait - last_iowait; +} + + +/* these callbacks are invoked by the vmon library when process instances become monitored/unmonitored */ +static void vmon_ctor_cb(vmon_t *vmon, vmon_proc_t *proc) +{ + VWM_TRACE("proc->pid=%i", proc->pid); + proc->foo = calloc(1, sizeof(vwm_perproc_ctxt_t)); +} + + +static void vmon_dtor_cb(vmon_t *vmon, vmon_proc_t *proc) +{ + VWM_TRACE("proc->pid=%i", proc->pid); + if (proc->foo) { + free(proc->foo); + proc->foo = NULL; + } +} + + +/* return the composed height of the overlay */ +int vwm_overlay_xwin_composed_height(vwm_t *vwm, vwm_xwindow_t *xwin) +{ + int snowflakes = xwin->overlay.snowflakes_cnt ? 1 + xwin->overlay.snowflakes_cnt : 0; /* don't include the separator row if there are no snowflakes */ + + return MIN((xwin->overlay.heirarchy_end + snowflakes) * OVERLAY_ROW_HEIGHT, xwin->attrs.height); +} + +/* reset snowflakes on the specified window */ +void vwm_overlay_xwin_reset_snowflakes(vwm_t *vwm, vwm_xwindow_t *xwin) { + if (xwin->overlay.snowflakes_cnt) { + xwin->overlay.snowflakes_cnt = 0; + vwm_composite_damage_win(vwm, xwin); + } +} + +static void init_overlay(vwm_t *vwm) { + static int initialized; + Window bitmask; + + if (initialized) return; + initialized = 1; + + /* we stow the vwm pointer so the vmon callback can access it, rather than allocating something + * to encapsulate the xwin and vwm pointers just for the callback... */ + vwm_ptr = vwm; + + /* initialize libvmon */ + vmon_init(&vmon, VMON_FLAG_2PASS, VMON_WANT_SYS_STAT, (VMON_WANT_PROC_STAT | VMON_WANT_PROC_FOLLOW_CHILDREN | VMON_WANT_PROC_FOLLOW_THREADS)); + vmon.proc_ctor_cb = vmon_ctor_cb; + vmon.proc_dtor_cb = vmon_dtor_cb; + vmon.sample_cb = sample_callback; + gettimeofday(&this_sample, NULL); + + /* get all the text and graphics stuff setup for overlays */ + overlay_font = XLoadQueryFont(vwm->display, OVERLAY_FIXED_FONT); + + /* create a GC for rendering the text using Xlib into the text overlay stencils */ + bitmask = XCreatePixmap(vwm->display, VWM_XROOT(vwm), 1, 1, OVERLAY_MASK_DEPTH); + text_gc = XCreateGC(vwm->display, bitmask, 0, NULL); + XSetForeground(vwm->display, text_gc, WhitePixel(vwm->display, vwm->screen_num)); + XFreePixmap(vwm->display, bitmask); + + /* create some repeating source fill pictures for drawing through the text and graph stencils */ + bitmask = XCreatePixmap(vwm->display, VWM_XROOT(vwm), 1, 1, 32); + overlay_text_fill = XRenderCreatePicture(vwm->display, bitmask, XRenderFindStandardFormat(vwm->display, PictStandardARGB32), CPRepeat, &pa_repeat); + XRenderFillRectangle(vwm->display, PictOpSrc, overlay_text_fill, &overlay_visible_color, 0, 0, 1, 1); + + bitmask = XCreatePixmap(vwm->display, VWM_XROOT(vwm), 1, 1, 32); + overlay_shadow_fill = XRenderCreatePicture(vwm->display, bitmask, XRenderFindStandardFormat(vwm->display, PictStandardARGB32), CPRepeat, &pa_repeat); + XRenderFillRectangle(vwm->display, PictOpSrc, overlay_shadow_fill, &overlay_shadow_color, 0, 0, 1, 1); + + bitmask = XCreatePixmap(vwm->display, VWM_XROOT(vwm), 1, OVERLAY_ROW_HEIGHT, 32); + overlay_bg_fill = XRenderCreatePicture(vwm->display, bitmask, XRenderFindStandardFormat(vwm->display, PictStandardARGB32), CPRepeat, &pa_repeat); + XRenderFillRectangle(vwm->display, PictOpSrc, overlay_bg_fill, &overlay_bg_color, 0, 0, 1, OVERLAY_ROW_HEIGHT); + XRenderFillRectangle(vwm->display, PictOpSrc, overlay_bg_fill, &overlay_div_color, 0, OVERLAY_ROW_HEIGHT - 1, 1, 1); + + bitmask = XCreatePixmap(vwm->display, VWM_XROOT(vwm), 1, 1, 32); + overlay_snowflakes_text_fill = XRenderCreatePicture(vwm->display, bitmask, XRenderFindStandardFormat(vwm->display, PictStandardARGB32), CPRepeat, &pa_repeat); + XRenderFillRectangle(vwm->display, PictOpSrc, overlay_snowflakes_text_fill, &overlay_snowflakes_visible_color, 0, 0, 1, 1); + + bitmask = XCreatePixmap(vwm->display, VWM_XROOT(vwm), 1, 1, 32); + overlay_grapha_fill = XRenderCreatePicture(vwm->display, bitmask, XRenderFindStandardFormat(vwm->display, PictStandardARGB32), CPRepeat, &pa_repeat); + XRenderFillRectangle(vwm->display, PictOpSrc, overlay_grapha_fill, &overlay_grapha_color, 0, 0, 1, 1); + + bitmask = XCreatePixmap(vwm->display, VWM_XROOT(vwm), 1, 1, 32); + overlay_graphb_fill = XRenderCreatePicture(vwm->display, bitmask, XRenderFindStandardFormat(vwm->display, PictStandardARGB32), CPRepeat, &pa_repeat); + XRenderFillRectangle(vwm->display, PictOpSrc, overlay_graphb_fill, &overlay_graphb_color, 0, 0, 1, 1); + + bitmask = XCreatePixmap(vwm->display, VWM_XROOT(vwm), 1, 2, 32); + overlay_finish_fill = XRenderCreatePicture(vwm->display, bitmask, XRenderFindStandardFormat(vwm->display, PictStandardARGB32), CPRepeat, &pa_repeat); + XRenderFillRectangle(vwm->display, PictOpSrc, overlay_finish_fill, &overlay_visible_color, 0, 0, 1, 1); + XRenderFillRectangle(vwm->display, PictOpSrc, overlay_finish_fill, &overlay_trans_color, 0, 1, 1, 1); +} + + +/* install a monitor on the window if it doesn't already have one and has _NET_WM_PID set */ +void vwm_overlay_xwin_create(vwm_t *vwm, vwm_xwindow_t *xwin) +{ + Atom type; + int fmt; + unsigned long nitems; + unsigned long nbytes; + long *foo = NULL; + int pid = -1; + + init_overlay(vwm); + + if (xwin->monitor) return; + + if (XGetWindowProperty(vwm->display, xwin->id, vwm->wm_pid_atom, 0, 1, False, XA_CARDINAL, + &type, &fmt, &nitems, &nbytes, (unsigned char **)&foo) != Success || !foo) return; + + pid = *foo; + XFree(foo); + + /* add the client process to the monitoring heirarchy */ + /* XXX note libvmon here maintains a unique callback for each unique callback+xwin pair, so multi-window processes work */ + xwin->monitor = vmon_proc_monitor(&vmon, NULL, pid, VMON_WANT_PROC_INHERIT, (void (*)(vmon_t *, vmon_proc_t *, void *))proc_sample_callback, xwin); + /* FIXME: count_rows() isn't returning the right count sometimes (off by ~1), it seems to be related to racing with the automatic child monitoring */ + /* the result is an extra row sometimes appearing below the process heirarchy */ + xwin->overlay.heirarchy_end = 1 + count_rows(xwin->monitor); + xwin->overlay.snowflakes_cnt = 0; +} + + +/* remove monitoring on the window if installed */ +void vwm_overlay_xwin_destroy(vwm_t *vwm, vwm_xwindow_t *xwin) +{ + if (xwin->monitor) vmon_proc_unmonitor(&vmon, xwin->monitor, (void (*)(vmon_t *, vmon_proc_t *, void *))proc_sample_callback, xwin); +} + + +/* this composes the maintained overlay into the window's overlay picture, this gets called from paint_all() on every repaint of xwin */ +/* we noop the call if the gen_last_composed and monitor->proc.generation numbers match, indicating there's nothing new to compose. */ +void vwm_overlay_xwin_compose(vwm_t *vwm, vwm_xwindow_t *xwin) +{ + XserverRegion region; + XRectangle damage; + int height; + + if (!xwin->overlay.width) return; /* prevent winning race with maintain_overlay() and using an unready overlay... */ + + if (xwin->overlay.gen_last_composed == xwin->monitor->generation) return; /* noop if no sampling occurred since last compose */ + xwin->overlay.gen_last_composed = xwin->monitor->generation; /* remember this generation */ + + //VWM_TRACE("composing %p", xwin); + + height = vwm_overlay_xwin_composed_height(vwm, xwin); + + /* fill the overlay picture with the background */ + XRenderComposite(vwm->display, PictOpSrc, overlay_bg_fill, None, xwin->overlay.picture, + 0, 0, + 0, 0, + 0, 0, + xwin->attrs.width, height); + + /* draw the graphs into the overlay through the stencils being maintained by the sample callbacks */ + XRenderComposite(vwm->display, PictOpOver, overlay_grapha_fill, xwin->overlay.grapha_picture, xwin->overlay.picture, + 0, 0, + xwin->overlay.phase, 0, + 0, 0, + xwin->attrs.width, height); + XRenderComposite(vwm->display, PictOpOver, overlay_graphb_fill, xwin->overlay.graphb_picture, xwin->overlay.picture, + 0, 0, + xwin->overlay.phase, 0, + 0, 0, + xwin->attrs.width, height); + + /* draw the shadow into the overlay picture using a translucent black source drawn through the shadow mask */ + XRenderComposite(vwm->display, PictOpOver, overlay_shadow_fill, xwin->overlay.shadow_picture, xwin->overlay.picture, + 0, 0, + 0, 0, + 0, 0, + xwin->attrs.width, height); + + /* render overlay text into the overlay picture using a white source drawn through the overlay text as a mask, on top of everything */ + XRenderComposite(vwm->display, PictOpOver, overlay_text_fill, xwin->overlay.text_picture, xwin->overlay.picture, + 0, 0, + 0, 0, + 0, 0, + xwin->attrs.width, (xwin->overlay.heirarchy_end * OVERLAY_ROW_HEIGHT)); + + XRenderComposite(vwm->display, PictOpOver, overlay_snowflakes_text_fill, xwin->overlay.text_picture, xwin->overlay.picture, + 0, 0, + 0, xwin->overlay.heirarchy_end * OVERLAY_ROW_HEIGHT, + 0, xwin->overlay.heirarchy_end * OVERLAY_ROW_HEIGHT, + xwin->attrs.width, height - (xwin->overlay.heirarchy_end * OVERLAY_ROW_HEIGHT)); + + /* damage the window to ensure the updated overlay is drawn (TODO: this can be done more selectively/efficiently) */ + damage.x = xwin->attrs.x + xwin->attrs.border_width; + damage.y = xwin->attrs.y + xwin->attrs.border_width; + damage.width = xwin->attrs.width; + damage.height = height; + region = XFixesCreateRegion(vwm->display, &damage, 1); + vwm_composite_damage_add(vwm, region); +} + +void vwm_overlay_rate_increase(vwm_t *vwm) { + if (sampling_interval + 1 < sizeof(sampling_intervals) / sizeof(sampling_intervals[0])) sampling_interval++; +} + +void vwm_overlay_rate_decrease(vwm_t *vwm) { + if (sampling_interval >= 0) sampling_interval--; +} + + +/* comvenience function for returning the time delta as a seconds.fraction float */ +static float delta(struct timeval *cur, struct timeval *prev) +{ + struct timeval res; + float delta; + + /* determine the # of whole.fractional seconds between prev and cur */ + timersub(cur, prev, &res); + + delta = res.tv_sec; + delta += (float)((float)res.tv_usec) / 1000000.0; + + return delta; +} + + +void vwm_overlay_update(vwm_t *vwm, int *desired_delay) { + static int sampling_paused = 0; + static int contiguous_drops = 0; + float this_delta; + + init_overlay(vwm); + + gettimeofday(&maybe_sample, NULL); + if ((sampling_interval == -1 && !sampling_paused) || /* XXX this is kind of a kludge to get the 0 Hz indicator drawn before pausing */ + (sampling_interval != -1 && ((this_delta = delta(&maybe_sample, &this_sample)) >= sampling_intervals[sampling_interval]))) { + vmon_sys_stat_t *sys_stat; + + /* automatically lower the sample rate if we can't keep up with the current sample rate */ + if (sampling_interval != -1 && sampling_interval <= prev_sampling_interval && + this_delta >= (sampling_intervals[sampling_interval] * 1.5)) { + contiguous_drops++; + /* require > 1 contiguous drops before lowering the rate, tolerates spurious one-off stalls */ + if (contiguous_drops > 2) sampling_interval--; + } else contiguous_drops = 0; + + /* age the sys-wide sample data into "last" variables, before the new sample overwrites them. */ + last_sample = this_sample; + this_sample = maybe_sample; + if ((sys_stat = vmon.stores[VMON_STORE_SYS_STAT])) { + last_user_cpu = sys_stat->user; + last_system_cpu = sys_stat->system; + last_total = sys_stat->user + + sys_stat->nice + + sys_stat->system + + sys_stat->idle + + sys_stat->iowait + + sys_stat->irq + + sys_stat->softirq + + sys_stat->steal + + sys_stat->guest; + + last_idle = sys_stat->idle; + last_iowait = sys_stat->iowait; + } + + vmon_sample(&vmon); /* XXX: calls proc_sample_callback() for explicitly monitored processes after sampling their descendants */ + /* XXX: also calls sample_callback() per invocation after sampling the sys wants */ + sampling_paused = (sampling_interval == -1); + prev_sampling_interval = sampling_interval; + } + + + /* TODO: make some effort to compute how long to sleep, but this is perfectly fine for now. */ + *desired_delay = sampling_interval != -1 ? sampling_intervals[sampling_interval] * 300.0 : -1; +} diff --git a/src/overlay.h b/src/overlay.h new file mode 100644 index 0000000..94e2dca --- /dev/null +++ b/src/overlay.h @@ -0,0 +1,36 @@ +#ifndef _OVERLAY_H +#define _OVERLAY_H + +#include +#include + +typedef struct _vwm_t vwm_t; +typedef struct _vwm_xwindow_t vwm_xwindow_t; + +/* everything needed by the per-window overlay's context */ +typedef struct _vwm_overlay_t { + Pixmap text_pixmap; /* pixmap for overlayed text (kept around for XDrawText usage) */ + Picture text_picture; /* picture representation of text_pixmap */ + Picture shadow_picture; /* text shadow layer */ + Picture grapha_picture; /* graph A layer */ + Picture graphb_picture; /* graph B layer */ + Picture tmp_picture; /* 1 row worth of temporary picture space */ + Picture picture; /* overlay picture derived from the pixmap, for render compositing */ + int width; /* current width of the overlay */ + int height; /* current height of the overlay */ + int phase; /* current position within the (horizontally scrolling) graphs */ + int heirarchy_end; /* row where the process heirarchy currently ends */ + int snowflakes_cnt; /* count of snowflaked rows (reset to zero to truncate snowflakes display) */ + int gen_last_composed; /* the last composed vmon generation */ +} vwm_overlay_t; + +int vwm_overlay_xwin_composed_height(vwm_t *vwm, vwm_xwindow_t *xwin); +void vwm_overlay_xwin_reset_snowflakes(vwm_t *vwm, vwm_xwindow_t *xwin); +void vwm_overlay_xwin_create(vwm_t *vwm, vwm_xwindow_t *xwin); +void vwm_overlay_xwin_destroy(vwm_t *vwm, vwm_xwindow_t *xwin); +void vwm_overlay_xwin_compose(vwm_t *vwm, vwm_xwindow_t *xwin); +void vwm_overlay_rate_increase(vwm_t *vwm); +void vwm_overlay_rate_decrease(vwm_t *vwm); +void vwm_overlay_update(vwm_t *vwm, int *desired_delay); + +#endif diff --git a/src/screen.c b/src/screen.c new file mode 100644 index 0000000..8fb63a5 --- /dev/null +++ b/src/screen.c @@ -0,0 +1,152 @@ +/* + * \/\/\ + * + * Copyright (C) 2012-2016 Vito Caputo - + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3 as published + * by the Free Software Foundation. + * + * 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 . + */ +/* return the appropriate screen, don't use the return value across event loops because randr events reallocate the array. */ + +#include +#include +#include + +#include "list.h" +#include "screen.h" +#include "vwm.h" +#include "window.h" +#include "xwindow.h" + + /* Xinerama/multihead screen functions */ + +/* return what fraction (0.0-1.0) of vwin overlaps with scr */ +static float vwm_screen_overlaps_xwin(vwm_t *vwm, const vwm_screen_t *scr, vwm_xwindow_t *xwin) +{ + float pct = 0, xover = 0, yover = 0; + + if (scr->x_org + scr->width < xwin->attrs.x || scr->x_org > xwin->attrs.x + xwin->attrs.width || + scr->y_org + scr->height < xwin->attrs.y || scr->y_org > xwin->attrs.y + xwin->attrs.height) + goto _out; + + /* they overlap, by how much? */ + xover = MIN(scr->x_org + scr->width, xwin->attrs.x + xwin->attrs.width) - MAX(scr->x_org, xwin->attrs.x); + yover = MIN(scr->y_org + scr->height, xwin->attrs.y + xwin->attrs.height) - MAX(scr->y_org, xwin->attrs.y); + + pct = (xover * yover) / (xwin->attrs.width * xwin->attrs.height); +_out: + VWM_TRACE("xover=%f yover=%f width=%i height=%i pct=%.4f", xover, yover, xwin->attrs.width, xwin->attrs.height, pct); + return pct; +} + + +const vwm_screen_t * vwm_screen_find(vwm_t *vwm, vwm_screen_rel_t rel, ...) +{ + static vwm_screen_t faux; + vwm_screen_t *scr, *best = &faux; /* default to faux as best */ + int i; + + faux.screen_number = 0; + faux.x_org = 0; + faux.y_org = 0; + faux.width = WidthOfScreen(DefaultScreenOfDisplay(vwm->display)); + faux.height = HeightOfScreen(DefaultScreenOfDisplay(vwm->display)); + + if (!vwm->xinerama_screens) goto _out; + +#define for_each_screen(_tmp) \ + for (i = 0, _tmp = vwm->xinerama_screens; i < vwm->xinerama_screens_cnt; _tmp = &vwm->xinerama_screens[++i]) + + switch (rel) { + case VWM_SCREEN_REL_XWIN: { + va_list ap; + vwm_xwindow_t *xwin; + float best_pct = 0, this_pct; + + va_start(ap, rel); + xwin = va_arg(ap, vwm_xwindow_t *); + va_end(ap); + + for_each_screen(scr) { + this_pct = vwm_screen_overlaps_xwin(vwm, scr, xwin); + if (this_pct > best_pct) { + best = scr; + best_pct = this_pct; + } + } + break; + } + + case VWM_SCREEN_REL_POINTER: { + int root_x, root_y, win_x, win_y; + unsigned int mask; + Window root, child; + + /* get the pointer coordinates and find which screen it's in */ + XQueryPointer(vwm->display, VWM_XROOT(vwm), &root, &child, &root_x, &root_y, &win_x, &win_y, &mask); + + for_each_screen(scr) { + if (root_x >= scr->x_org && root_x < scr->x_org + scr->width && + root_y >= scr->y_org && root_y < scr->y_org + scr->height) { + best = scr; + break; + } + } + break; + } + + case VWM_SCREEN_REL_TOTAL: { + short x1 = MAXSHORT, y1 = MAXSHORT, x2 = MINSHORT, y2 = MINSHORT; + /* find the smallest x_org and y_org, the highest x_org + width and y_org + height, those are the two corners of the total rect */ + for_each_screen(scr) { + if (scr->x_org < x1) x1 = scr->x_org; + if (scr->y_org < y1) y1 = scr->y_org; + if (scr->x_org + scr->width > x2) x2 = scr->x_org + scr->width; + if (scr->y_org + scr->height > y2) y2 = scr->y_org + scr->height; + } + faux.x_org = x1; + faux.y_org = y1; + faux.width = x2 - x1; + faux.height = y2 - y1; + best = &faux; + break; + } + } +_out: + VWM_TRACE("Found Screen #%i: %hix%hi @ %hi,%hi", best->screen_number, best->width, best->height, best->x_org, best->y_org); + + return best; +} + + +/* check if a screen contains any windows (assuming the current desktop) */ +int vwm_screen_is_empty(vwm_t *vwm, const vwm_screen_t *scr) +{ + vwm_xwindow_t *xwin; + int is_empty = 1; + + list_for_each_entry(xwin, &vwm->xwindows, xwindows) { + if (!xwin->mapped) continue; + if (!xwin->managed || (xwin->managed->desktop == vwm->focused_desktop && !xwin->managed->shelved && !xwin->managed->configuring)) { + /* XXX: it may make more sense to see what %age of the screen is overlapped by windows, and consider it empty if < some % */ + /* This is just seeing if any window is predominantly within the specified screen, the rationale being if you had a focusable + * window on the screen you would have used the keyboard to make windows go there; this function is only used in determining + * wether a new window should go where the pointer is or not. */ + if (vwm_screen_overlaps_xwin(vwm, scr, xwin) >= 0.05) { + is_empty = 0; + break; + } + } + } + + return is_empty; +} diff --git a/src/screen.h b/src/screen.h new file mode 100644 index 0000000..c8b7531 --- /dev/null +++ b/src/screen.h @@ -0,0 +1,19 @@ +#ifndef _SCREEN_H +#define _SCREEN_H + +#include /* XINERAMA extension, facilitates easy multihead awareness */ + +typedef struct _vwm_t vwm_t; + +typedef XineramaScreenInfo vwm_screen_t; /* conveniently reuse the xinerama type for describing screens */ + +typedef enum _vwm_screen_rel_t { + VWM_SCREEN_REL_XWIN, /* return the screen the supplied window most resides in */ + VWM_SCREEN_REL_POINTER, /* return the screen the pointer resides in */ + VWM_SCREEN_REL_TOTAL, /* return the bounding rectangle of all screens as one */ +} vwm_screen_rel_t; + +const vwm_screen_t * vwm_screen_find(vwm_t *vwm, vwm_screen_rel_t rel, ...); +int vwm_screen_is_empty(vwm_t *vwm, const vwm_screen_t *scr); + +#endif diff --git a/src/vwm.c b/src/vwm.c new file mode 100644 index 0000000..c2e5126 --- /dev/null +++ b/src/vwm.c @@ -0,0 +1,291 @@ +/* + * \/\/\ + * + * Copyright (C) 2012-2016 Vito Caputo - + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3 as published + * by the Free Software Foundation. + * + * 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 . + */ + +#include +#include +#include +#include +#include /* SYNC extension, enables us to give vwm the highest X client priority, helps keep vwm responsive at all times */ +#include /* XINERAMA extension, facilitates easy multihead awareness */ +#include /* RANDR extension, facilitates display configuration change awareness */ +#include /* Damage extension, enables receipt of damage events, reports visible regions needing updating (compositing) */ +#include /* Render extension, enables use of alpha channels and accelerated rendering of surfaces having alpha (compositing) */ +#include /* Composite extension, enables off-screen redirection of window rendering (compositing) */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "composite.h" +#include "desktop.h" +#include "launch.h" +#include "logo.h" +#include "vwm.h" +#include "xevent.h" +#include "xwindow.h" + +static vwm_t vwm; + + /* Sync */ +static int sync_event, sync_error; + + /* Xinerama */ +static int xinerama_event, xinerama_error; +static int randr_event, randr_error; + + /* Compositing */ +static int composite_event, composite_error, composite_opcode; + +static int errhandler(Display *display, XErrorEvent *err) +{ + /* TODO */ + return 1; +} + +int main(int argc, char *argv[]) +{ + int err = 0; + int done = 0; + XEvent event; + Cursor pointer; + struct pollfd pfd; + char *console_args[] = {"xterm", "-class", CONSOLE_WM_CLASS, "-e", "/bin/sh", "-c", "screen -D -RR " CONSOLE_SESSION_STRING, NULL}; + +#define reterr_if(_cond, _fmt, _args...) \ + err++;\ + if (_cond) {\ + VWM_ERROR(_fmt, ##_args);\ + return err;\ + } + + INIT_LIST_HEAD(&vwm.desktops); + INIT_LIST_HEAD(&vwm.desktops_mru); + INIT_LIST_HEAD(&vwm.windows_mru); + INIT_LIST_HEAD(&vwm.xwindows); + + /* open connection with the server */ + reterr_if((vwm.display = XOpenDisplay(NULL)) == NULL, "Cannot open display"); + + /* prevent children from inheriting the X connection */ + reterr_if(fcntl(ConnectionNumber(vwm.display), F_SETFD, FD_CLOEXEC) < 0, "Cannot set FD_CLOEXEC on X connection"); + + /* get our scheduling priority, clients are launched with a priority LAUNCHED_RELATIVE_PRIORITY nicer than this */ + reterr_if((vwm.priority = getpriority(PRIO_PROCESS, getpid())) == -1, "Cannot get scheduling priority"); + + XSetErrorHandler(errhandler); + + vwm.screen_num = DefaultScreen(vwm.display); + + /* query the needed X extensions */ + reterr_if(!XQueryExtension (vwm.display, COMPOSITE_NAME, &composite_opcode, &composite_event, &composite_error), "No composite extension available"); + reterr_if(!XDamageQueryExtension(vwm.display, &vwm.damage_event, &vwm.damage_error), "No damage extension available"); + if (XSyncQueryExtension(vwm.display, &sync_event, &sync_error)) { + /* set the window manager to the maximum X client priority */ + XSyncSetPriority(vwm.display, VWM_XROOT(&vwm), 0x7fffffff); + } + + if (XineramaQueryExtension(vwm.display, &xinerama_event, &xinerama_error)) { + vwm.xinerama_screens = XineramaQueryScreens(vwm.display, &vwm.xinerama_screens_cnt); + } + + if (XRRQueryExtension(vwm.display, &randr_event, &randr_error)) { + XRRSelectInput(vwm.display, VWM_XROOT(&vwm), RRScreenChangeNotifyMask); + } + + /* allocate colors, I make assumptions about the X server's color capabilities since I'll only use this on modern-ish computers... */ + vwm.cmap = DefaultColormap(vwm.display, vwm.screen_num); + +#define color(_sym, _str) \ + XAllocNamedColor(vwm.display, vwm.cmap, _str, &vwm.colors._sym ## _color, &vwm.colors._sym ## _color); +#include "colors.def" +#undef color + + vwm.wm_delete_atom = XInternAtom(vwm.display, "WM_DELETE_WINDOW", False); + vwm.wm_protocols_atom = XInternAtom(vwm.display, "WM_PROTOCOLS", False); + vwm.wm_pid_atom = XInternAtom(vwm.display, "_NET_WM_PID", False); + + XSelectInput(vwm.display, VWM_XROOT(&vwm), + PropertyChangeMask | SubstructureNotifyMask | SubstructureRedirectMask | PointerMotionMask | ButtonPressMask | ButtonReleaseMask); + XGrabKey(vwm.display, AnyKey, WM_GRAB_MODIFIER, VWM_XROOT(&vwm), False, GrabModeAsync, GrabModeAsync); + + XFlush(vwm.display); + + XSetInputFocus(vwm.display, VWM_XROOT(&vwm), RevertToPointerRoot, CurrentTime); + + /* create initial virtual desktop */ + vwm_desktop_focus(&vwm, vwm_desktop_create(&vwm, NULL)); + vwm_desktop_mru(&vwm, vwm.focused_desktop); + + /* manage all preexisting windows */ + vwm_xwin_create_existing(&vwm); + + /* create GC for logo drawing and window rubber-banding */ + vwm.gc = XCreateGC(vwm.display, VWM_XROOT(&vwm), 0, NULL); + XSetSubwindowMode(vwm.display, vwm.gc, IncludeInferiors); + XSetFunction(vwm.display, vwm.gc, GXxor); + + /* launch the console here so it's likely ready by the time the logo animation finishes (there's no need to synchronize with it currently) */ + vwm_launch(&vwm, console_args, VWM_LAUNCH_MODE_BG); + + /* first the logo color is the foreground */ + XSetForeground(vwm.display, vwm.gc, vwm.colors.logo_color.pixel); + vwm_draw_logo(&vwm); + + /* change to the rubber-banding foreground color */ + XSetForeground(vwm.display, vwm.gc, vwm.colors.rubberband_color.pixel); + + XClearWindow(vwm.display, VWM_XROOT(&vwm)); + + /* set the pointer */ + pointer = XCreateFontCursor(vwm.display, XC_X_cursor); + XDefineCursor(vwm.display, VWM_XROOT(&vwm), pointer); + + pfd.events = POLLIN; + pfd.revents = 0; + pfd.fd = ConnectionNumber(vwm.display); + + while (!done) { + do { + int delay; + + vwm_overlay_update(&vwm, &delay); + XFlush(vwm.display); + + if (!XPending(vwm.display)) { + if (poll(&pfd, 1, delay) == 0) break; + } + + XNextEvent(vwm.display, &event); + switch (event.type) { + case KeyPress: + VWM_TRACE("keypress"); + vwm_xevent_handle_key_press(&vwm, &event.xkey); + break; + + case KeyRelease: + VWM_TRACE("keyrelease"); + vwm_xevent_handle_key_release(&vwm, &event.xkey); + break; + + case ButtonPress: + VWM_TRACE("buttonpresss"); + vwm_xevent_handle_button_press(&vwm, &event.xbutton); + break; + + case MotionNotify: + //VWM_TRACE("motionnotify"); + vwm_xevent_handle_motion_notify(&vwm, &event.xmotion); + break; + + case ButtonRelease: + VWM_TRACE("buttonrelease"); + vwm_xevent_handle_button_release(&vwm, &event.xbutton); + break; + + case CreateNotify: + VWM_TRACE("createnotify"); + vwm_xevent_handle_create_notify(&vwm, &event.xcreatewindow); + break; + + case DestroyNotify: + VWM_TRACE("destroynotify"); + vwm_xevent_handle_destroy_notify(&vwm, &event.xdestroywindow); + break; + + case ConfigureRequest: + VWM_TRACE("configurerequest"); + vwm_xevent_handle_configure_request(&vwm, &event.xconfigurerequest); + break; + + case ConfigureNotify: + VWM_TRACE("configurenotify"); + vwm_xevent_handle_configure_notify(&vwm, &event.xconfigure); + break; + + case UnmapNotify: + VWM_TRACE("unmapnotify"); + vwm_xevent_handle_unmap_notify(&vwm, &event.xunmap); + break; + + case MapNotify: + VWM_TRACE("mapnotify"); + vwm_xevent_handle_map_notify(&vwm, &event.xmap); + break; + + case MapRequest: + VWM_TRACE("maprequest"); + vwm_xevent_handle_map_request(&vwm, &event.xmaprequest); + break; + + case PropertyNotify: + VWM_TRACE("property notify"); + vwm_xevent_handle_property_notify(&vwm, &event.xproperty); + break; + + case MappingNotify: + VWM_TRACE("mapping notify"); + vwm_xevent_handle_mapping_notify(&vwm, &event.xmapping); + break; + + case Expose: + VWM_TRACE("expose"); + break; + + case GravityNotify: + VWM_TRACE("gravitynotify"); + break; + + case ReparentNotify: + VWM_TRACE("reparentnotify"); + break; + + default: + if (event.type == randr_event + RRScreenChangeNotify) { + VWM_TRACE("rrscreenchangenotify"); + if (vwm.xinerama_screens) XFree(vwm.xinerama_screens); + vwm.xinerama_screens = XineramaQueryScreens(vwm.display, &vwm.xinerama_screens_cnt); + + vwm_composite_invalidate_root(&vwm); + } else if (event.type == vwm.damage_event + XDamageNotify) { + //VWM_TRACE("damagenotify"); + vwm_composite_damage_event(&vwm, (XDamageNotifyEvent *)&event); + } else { + VWM_ERROR("Unhandled X op %i", event.type); + } + break; + } + } while (QLength(vwm.display)); + + vwm_composite_paint_all(&vwm); + } + + /* close connection to server */ + XFlush(vwm.display); + XCloseDisplay(vwm.display); + + return 0; +} diff --git a/src/vwm.h b/src/vwm.h new file mode 100644 index 0000000..8bc0f7a --- /dev/null +++ b/src/vwm.h @@ -0,0 +1,79 @@ +#ifndef _UTIL_H +#define _UTIL_H + +#include +// #include +// #include +#include +#include +#include + +#include "context.h" +#include "list.h" + +#define WINDOW_BORDER_WIDTH 1 +#define WM_GRAB_MODIFIER Mod1Mask /* the modifier for invoking vwm's controls */ + /* Mod4Mask would be the windows key instead of Alt, but there's an assumption + * in the code that grabs are being activated by Alt which complicates changing it, + * search for XGetModifierMapping to see where, feel free to fix it. Or you can + * just hack the code to expect the appropriate key instead of Alt, I didn't see the + * value of making it modifier mapping aware if it's always Alt for me. */ + +#define CONSOLE_WM_CLASS "VWMConsoleXTerm" /* the class we specify to the "console" xterm */ +#define CONSOLE_SESSION_STRING "_vwm_console.$DISPLAY" /* the unique console screen session identifier */ + + +#define VWM_ERROR(_fmt, _args...) fprintf(stderr, "%s:%i\t%s() "_fmt"\n", __FILE__, __LINE__, __FUNCTION__, ##_args) +#define VWM_PERROR(_fmt, _args...) fprintf(stderr, "%s:%i\t%s() "_fmt"; %s\n", __FILE__, __LINE__, __FUNCTION__, ##_args, strerror(errno)) +#define VWM_BUG(_fmt, _args...) fprintf(stderr, "BUG %s:%i\t%s() "_fmt"; %s\n", __FILE__, __LINE__, __FUNCTION__, ##_args, strerror(errno)) + +#ifdef TRACE +#define VWM_TRACE(_fmt, _args...) fprintf(stderr, "%s:%i\t%s() "_fmt"\n", __FILE__, __LINE__, __FUNCTION__, ##_args) +#else +#define VWM_TRACE(_fmt, _args...) do { } while(0) +#endif + +#define VWM_XROOT(_vwm) RootWindow((_vwm)->display, (_vwm)->screen_num) +#define VWM_XVISUAL(_vwm) DefaultVisual((_vwm)->display, (_vwm)->screen_num) +#define VWM_XDEPTH(_vwm) DefaultDepth((_vwm)->display, (_vwm)->screen_num) + +#define MIN(_a, _b) ((_a) < (_b) ? (_a) : (_b)) +#define MAX(_a, _b) ((_a) > (_b) ? (_a) : (_b)) + +typedef struct _vwm_window_t vwm_window_t; +typedef struct _vwm_desktop_t vwm_desktop_t; + +typedef struct _vwm_t { + Display *display; + Colormap cmap; + int screen_num; + GC gc; + Atom wm_delete_atom; + Atom wm_protocols_atom; + Atom wm_pid_atom; + int damage_event, damage_error; + + list_head_t desktops; /* global list of all (virtual) desktops in spatial created-in order */ + list_head_t desktops_mru; /* global list of all (virtual) desktops in MRU order */ + list_head_t windows_mru; /* global list of all managed windows kept in MRU order */ + list_head_t xwindows; /* global list of all xwindows kept in the X server stacking order */ + vwm_window_t *console; /* the console window */ + vwm_window_t *focused_origin; /* the originating window in a grabbed operation/transaction */ + vwm_desktop_t *focused_desktop; /* currently focused (virtual) desktop */ + vwm_window_t *focused_shelf; /* currently focused shelved window */ + vwm_context_t focused_context; /* currently focused context */ + int priority; /* scheduling priority of the vwm process, launcher nices relative to this */ + unsigned long fence_mask; /* global mask state for vwm_win_focus_next(... VWM_FENCE_MASKED_VIOLATE), + * if you use vwm on enough screens to overflow this, pics or it didn't happen. */ + struct colors { +#define color(_sym, _str) \ + XColor _sym ## _color; + #include "colors.def" +#undef color + } colors; + + XineramaScreenInfo *xinerama_screens; + int xinerama_screens_cnt; +} vwm_t; + +#endif diff --git a/src/window.c b/src/window.c new file mode 100644 index 0000000..e28330a --- /dev/null +++ b/src/window.c @@ -0,0 +1,468 @@ +/* + * \/\/\ + * + * Copyright (C) 2012-2016 Vito Caputo - + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3 as published + * by the Free Software Foundation. + * + * 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 . + */ + /* vwm "managed" windows (vwm_window_t) (which are built upon the "core" X windows (vwm_xwindow_t)) */ + +#include +#include +#include + +#include "desktop.h" +#include "list.h" +#include "vwm.h" +#include "window.h" +#include "xwindow.h" + +/* unmap the specified window and set the unmapping-in-progress flag so we can discard vwm-generated UnmapNotify events */ +void vwm_win_unmap(vwm_t *vwm, vwm_window_t *vwin) +{ + if (!vwin->xwindow->mapped) { + VWM_TRACE("inhibited unmap of \"%s\", not mapped by client", vwin->xwindow->name); + return; + } + VWM_TRACE("Unmapping \"%s\"", vwin->xwindow->name); + vwin->unmapping = 1; + XUnmapWindow(vwm->display, vwin->xwindow->id); +} + + +/* map the specified window and set the mapping-in-progress flag so we can discard vwm-generated MapNotify events */ +void vwm_win_map(vwm_t *vwm, vwm_window_t *vwin) +{ + if (!vwin->xwindow->mapped) { + VWM_TRACE("inhibited map of \"%s\", not mapped by client", vwin->xwindow->name); + return; + } + VWM_TRACE("Mapping \"%s\"", vwin->xwindow->name); + vwin->mapping = 1; + XMapWindow(vwm->display, vwin->xwindow->id); +} + + +/* make the specified window the most recently used one */ +void vwm_win_mru(vwm_t *vwm, vwm_window_t *vwin) +{ + list_move(&vwin->windows_mru, &vwm->windows_mru); +} + + +/* look up the X window in the global managed windows list */ +vwm_window_t * vwm_win_lookup(vwm_t *vwm, Window win) +{ + vwm_window_t *tmp, *vwin = NULL; + + list_for_each_entry(tmp, &vwm->windows_mru, windows_mru) { + if (tmp->xwindow->id == win) { + vwin = tmp; + break; + } + } + + return vwin; +} + + +/* return the currently focused window (considers current context...), may return NULL */ +vwm_window_t * vwm_win_focused(vwm_t *vwm) +{ + vwm_window_t *vwin = NULL; + + switch (vwm->focused_context) { + case VWM_CONTEXT_SHELF: + vwin = vwm->focused_shelf; + break; + + case VWM_CONTEXT_DESKTOP: + if (vwm->focused_desktop) vwin = vwm->focused_desktop->focused_window; + break; + + default: + VWM_BUG("Unsupported context"); + break; + } + + return vwin; +} + + +/* "autoconfigure" windows (configuration shortcuts like fullscreen/halfscreen/quarterscreen) and restoring the window */ +void vwm_win_autoconf(vwm_t *vwm, vwm_window_t *vwin, vwm_screen_rel_t rel, vwm_win_autoconf_t conf, ...) +{ + const vwm_screen_t *scr; + va_list ap; + XWindowChanges changes = { .border_width = WINDOW_BORDER_WIDTH }; + + /* remember the current configuration as the "client" configuration if it's not an autoconfigured one. */ + if (vwin->autoconfigured == VWM_WIN_AUTOCONF_NONE) vwin->client = vwin->xwindow->attrs; + + scr = vwm_screen_find(vwm, rel, vwin->xwindow); /* XXX FIXME: this becomes a bug when vwm_screen_find() uses non-xwin va_args */ + va_start(ap, conf); + switch (conf) { + case VWM_WIN_AUTOCONF_QUARTER: { + vwm_corner_t corner = va_arg(ap, vwm_corner_t); + changes.width = scr->width / 2 - (WINDOW_BORDER_WIDTH * 2); + changes.height = scr->height / 2 - (WINDOW_BORDER_WIDTH * 2); + switch (corner) { + case VWM_CORNER_TOP_LEFT: + changes.x = scr->x_org; + changes.y = scr->y_org; + break; + + case VWM_CORNER_TOP_RIGHT: + changes.x = scr->x_org + scr->width / 2; + changes.y = scr->y_org; + break; + + case VWM_CORNER_BOTTOM_RIGHT: + changes.x = scr->x_org + scr->width / 2; + changes.y = scr->y_org + scr->height / 2; + break; + + case VWM_CORNER_BOTTOM_LEFT: + changes.x = scr->x_org; + changes.y = scr->y_org + scr->height / 2; + break; + } + break; + } + + case VWM_WIN_AUTOCONF_HALF: { + vwm_side_t side = va_arg(ap, vwm_side_t); + switch (side) { + case VWM_SIDE_TOP: + changes.width = scr->width - (WINDOW_BORDER_WIDTH * 2); + changes.height = scr->height / 2 - (WINDOW_BORDER_WIDTH * 2); + changes.x = scr->x_org; + changes.y = scr->y_org; + break; + + case VWM_SIDE_BOTTOM: + changes.width = scr->width - (WINDOW_BORDER_WIDTH * 2); + changes.height = scr->height / 2 - (WINDOW_BORDER_WIDTH * 2); + changes.x = scr->x_org; + changes.y = scr->y_org + scr->height / 2; + break; + + case VWM_SIDE_LEFT: + changes.width = scr->width / 2 - (WINDOW_BORDER_WIDTH * 2); + changes.height = scr->height - (WINDOW_BORDER_WIDTH * 2); + changes.x = scr->x_org; + changes.y = scr->y_org; + break; + + case VWM_SIDE_RIGHT: + changes.width = scr->width / 2 - (WINDOW_BORDER_WIDTH * 2); + changes.height = scr->height - (WINDOW_BORDER_WIDTH * 2); + changes.x = scr->x_org + scr->width / 2; + changes.y = scr->y_org; + break; + } + break; + } + + case VWM_WIN_AUTOCONF_FULL: + changes.width = scr->width - WINDOW_BORDER_WIDTH * 2; + changes.height = scr->height - WINDOW_BORDER_WIDTH * 2; + changes.x = scr->x_org; + changes.y = scr->y_org; + break; + + case VWM_WIN_AUTOCONF_ALL: + changes.width = scr->width; + changes.height = scr->height; + changes.x = scr->x_org; + changes.y = scr->y_org; + changes.border_width = 0; + break; + + case VWM_WIN_AUTOCONF_NONE: /* restore window if autoconfigured */ + changes.width = vwin->client.width; + changes.height = vwin->client.height; + changes.x = vwin->client.x; + changes.y = vwin->client.y; + break; + } + va_end(ap); + + XConfigureWindow(vwm->display, vwin->xwindow->id, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &changes); + vwin->autoconfigured = conf; +} + + +/* focus a window */ +/* this updates window border color as needed and the X input focus if mapped */ +void vwm_win_focus(vwm_t *vwm, vwm_window_t *vwin) +{ + VWM_TRACE("focusing: %#x", (unsigned int)vwin->xwindow->id); + + if (vwm_xwin_is_mapped(vwm, vwin->xwindow)) { + /* if vwin is mapped give it the input focus */ + XSetInputFocus(vwm->display, vwin->xwindow->id, RevertToPointerRoot, CurrentTime); + } + + /* update the border color accordingly */ + if (vwin->shelved) { + /* set the border of the newly focused window to the shelved color */ + XSetWindowBorder(vwm->display, vwin->xwindow->id, vwin == vwm->console ? vwm->colors.shelved_console_border_color.pixel : vwm->colors.shelved_window_border_color.pixel); + /* fullscreen windows in the shelf when focused, since we don't intend to overlap there */ + vwm_win_autoconf(vwm, vwin, VWM_SCREEN_REL_POINTER, VWM_WIN_AUTOCONF_FULL); /* XXX TODO: for now the shelf follows the pointer, it's simple. */ + } else { + if (vwin->desktop->focused_window) { + /* set the border of the previously focused window on the same desktop to the unfocused color */ + XSetWindowBorder(vwm->display, vwin->desktop->focused_window->xwindow->id, vwm->colors.unfocused_window_border_color.pixel); + } + + /* set the border of the newly focused window to the focused color */ + XSetWindowBorder(vwm->display, vwin->xwindow->id, vwm->colors.focused_window_border_color.pixel); + + /* persist this on a per-desktop basis so it can be restored on desktop switches */ + vwin->desktop->focused_window = vwin; + } +} + + +/* focus the next window on a virtual desktop relative to the supplied window, in the specified context, respecting screen boundaries according to fence. */ +vwm_window_t * vwm_win_focus_next(vwm_t *vwm, vwm_window_t *vwin, vwm_fence_t fence) +{ + const vwm_screen_t *scr = vwm_screen_find(vwm, VWM_SCREEN_REL_XWIN, vwin->xwindow), *next_scr = NULL; + vwm_window_t *next; + unsigned long visited_mask; + +_retry: + visited_mask = 0; + list_for_each_entry(next, &vwin->windows_mru, windows_mru) { + /* searching for the next mapped window in this context, using vwin->windows as the head */ + if (&next->windows_mru == &vwm->windows_mru) continue; /* XXX: skip the containerless head, we're leveraging the circular list implementation */ + + if ((vwin->shelved && next->shelved) || + ((!vwin->shelved && !next->shelved && next->desktop == vwin->desktop) && + (fence == VWM_FENCE_IGNORE || + ((fence == VWM_FENCE_RESPECT || fence == VWM_FENCE_TRY_RESPECT) && vwm_screen_find(vwm, VWM_SCREEN_REL_XWIN, next->xwindow) == scr) || + (fence == VWM_FENCE_VIOLATE && vwm_screen_find(vwm, VWM_SCREEN_REL_XWIN, next->xwindow) != scr) || + (fence == VWM_FENCE_MASKED_VIOLATE && (next_scr = vwm_screen_find(vwm, VWM_SCREEN_REL_XWIN, next->xwindow)) != scr && + !((1UL << next_scr->screen_number) & vwm->fence_mask)) + ))) break; + + if (fence == VWM_FENCE_MASKED_VIOLATE && next_scr && next_scr != scr) visited_mask |= (1UL << next_scr->screen_number); + } + + if (fence == VWM_FENCE_TRY_RESPECT && next == vwin) { + /* if we tried to respect the fence and failed to find a next, fallback to ignoring the fence and try again */ + fence = VWM_FENCE_IGNORE; + goto _retry; + } else if (fence == VWM_FENCE_MASKED_VIOLATE && next_scr) { + /* if we did a masked violate update the mask with the potentially new screen number */ + if (next == vwin && visited_mask) { + /* if we failed to find a next window on a different screen but had candidates we've exhausted screens and need to reset the mask then retry */ + VWM_TRACE("all candidate screens masked @ 0x%lx, resetting mask", vwm->fence_mask); + vwm->fence_mask = 0; + goto _retry; + } + vwm->fence_mask |= (1UL << next_scr->screen_number); + VWM_TRACE("VWM_FENCE_MASKED_VIOLATE fence_mask now: 0x%lx\n", vwm->fence_mask); + } + + if (vwin->shelved) { + if (next != vwm->focused_shelf) { + /* shelf switch, unmap the focused shelf and take it over */ + /* TODO FIXME: this makes assumptions about the shelf being focused calling unmap/map directly.. */ + vwm_win_unmap(vwm, vwm->focused_shelf); + + XFlush(vwm->display); + + vwm_win_map(vwm, next); + vwm->focused_shelf = next; + vwm_win_focus(vwm, next); + } + } else { + if (next != next->desktop->focused_window) { + /* focus the changed window */ + vwm_win_focus(vwm, next); + XRaiseWindow(vwm->display, next->xwindow->id); + } + } + + VWM_TRACE("vwin=%p xwin=%p name=\"%s\"", next, next->xwindow, next->xwindow->name); + + return next; +} + + +/* shelves a window, if the window is focused we focus the next one (if possible) */ +void vwm_win_shelve(vwm_t *vwm, vwm_window_t *vwin) +{ + /* already shelved, NOOP */ + if (vwin->shelved) return; + + /* shelving focused window, focus the next window */ + if (vwin == vwin->desktop->focused_window) { + vwm_win_mru(vwm, vwm_win_focus_next(vwm, vwin, VWM_FENCE_RESPECT)); + } + + if (vwin == vwin->desktop->focused_window) { + /* TODO: we can probably put this into vwm_win_focus_next() and have it always handled there... */ + vwin->desktop->focused_window = NULL; + } + + vwin->shelved = 1; + vwm_win_mru(vwm, vwin); + + /* newly shelved windows always become the focused shelf */ + vwm->focused_shelf = vwin; + + vwm_win_unmap(vwm, vwin); +} + + +/* helper for (idempotently) unfocusing a window, deals with context switching etc... */ +void vwm_win_unfocus(vwm_t *vwm, vwm_window_t *vwin) +{ + /* if we're the focused shelved window, cycle the focus to the next shelved window if possible, if there's no more shelf, switch to the desktop */ + /* TODO: there's probably some icky behaviors for focused windows unmapping/destroying in unfocused contexts, we probably jump contexts suddenly. */ + if (vwin == vwm->focused_shelf) { + VWM_TRACE("unfocusing focused shelf"); + vwm_win_focus_next(vwm, vwin, VWM_FENCE_IGNORE); + + if (vwin == vwm->focused_shelf) { + VWM_TRACE("shelf empty, leaving"); + /* no other shelved windows, exit the shelf context */ + vwm_context_focus(vwm, VWM_CONTEXT_DESKTOP); + vwm->focused_shelf = NULL; + } + } + + /* if we're the focused window cycle the focus to the next window on the desktop if possible */ + if (vwin->desktop->focused_window == vwin) { + VWM_TRACE("unfocusing focused window"); + vwm_win_focus_next(vwm, vwin, VWM_FENCE_TRY_RESPECT); + } + + if (vwin->desktop->focused_window == vwin) { + VWM_TRACE("desktop empty"); + vwin->desktop->focused_window = NULL; + } +} + + +/* demote an managed window to an unmanaged one */ +vwm_xwindow_t * vwm_win_unmanage(vwm_t *vwm, vwm_window_t *vwin) +{ + vwm_win_mru(vwm, vwin); /* bump vwin to the mru head before unfocusing so we always move focus to the current head on unmanage of the focused window */ + vwm_win_unfocus(vwm, vwin); + list_del(&vwin->windows_mru); + + if (vwin == vwm->console) vwm->console = NULL; + if (vwin == vwm->focused_origin) vwm->focused_origin = NULL; + + vwin->xwindow->managed = NULL; + + return vwin->xwindow; +} + + +/* promote an unmanaged window to a managed one */ +vwm_window_t * vwm_win_manage_xwin(vwm_t *vwm, vwm_xwindow_t *xwin) +{ + vwm_window_t *focused, *vwin = NULL; + + if (xwin->managed) { + VWM_TRACE("suppressed re-management of xwin=%p", xwin); + goto _fail; + } + + if (!(vwin = (vwm_window_t *)malloc(sizeof(vwm_window_t)))) { + VWM_PERROR("Failed to allocate vwin"); + goto _fail; + } + + XUngrabButton(vwm->display, AnyButton, AnyModifier, xwin->id); + XGrabButton(vwm->display, AnyButton, WM_GRAB_MODIFIER, xwin->id, False, (PointerMotionMask | ButtonPressMask | ButtonReleaseMask), GrabModeAsync, GrabModeAsync, None, None); + XGrabKey(vwm->display, AnyKey, WM_GRAB_MODIFIER, xwin->id, False, GrabModeAsync, GrabModeAsync); + XSetWindowBorder(vwm->display, xwin->id, vwm->colors.unfocused_window_border_color.pixel); + + vwin->hints = XAllocSizeHints(); + if (!vwin->hints) { + VWM_PERROR("Failed to allocate WM hints"); + goto _fail; + } + XGetWMNormalHints(vwm->display, xwin->id, vwin->hints, &vwin->hints_supplied); + + xwin->managed = vwin; + vwin->xwindow = xwin; + + vwin->desktop = vwm->focused_desktop; + vwin->autoconfigured = VWM_WIN_AUTOCONF_NONE; + vwin->mapping = vwin->unmapping = vwin->configuring = 0; + vwin->shelved = (vwm->focused_context == VWM_CONTEXT_SHELF); /* if we're in the shelf when the window is created, the window is shelved */ + vwin->client = xwin->attrs; /* remember whatever the current attributes are */ + + VWM_TRACE("hints: flags=%lx x=%i y=%i w=%i h=%i minw=%i minh=%i maxw=%i maxh=%i winc=%i hinc=%i basew=%i baseh=%i grav=%x", + vwin->hints->flags, + vwin->hints->x, vwin->hints->y, + vwin->hints->width, vwin->hints->height, + vwin->hints->min_width, vwin->hints->min_height, + vwin->hints->max_width, vwin->hints->max_height, + vwin->hints->width_inc, vwin->hints->height_inc, + vwin->hints->base_width, vwin->hints->base_height, + vwin->hints->win_gravity); + + if ((vwin->hints_supplied & (USSize | PSize))) { + vwin->client.width = vwin->hints->base_width; + vwin->client.height = vwin->hints->base_height; + } + + /* put it on the global windows_mru list, if there's a focused window insert the new one after it */ + if (!list_empty(&vwm->windows_mru) && (focused = vwm_win_focused(vwm))) { + /* insert the vwin immediately after the focused window, so Mod1+Tab goes to the new window */ + list_add(&vwin->windows_mru, &focused->windows_mru); + } else { + list_add(&vwin->windows_mru, &vwm->windows_mru); + } + + /* always raise newly managed windows so we know about them. */ + XRaiseWindow(vwm->display, xwin->id); + + /* if the desktop has no focused window yet, automatically focus the newly managed one, provided we're on the desktop context */ + if (!vwm->focused_desktop->focused_window && vwm->focused_context == VWM_CONTEXT_DESKTOP) { + VWM_TRACE("Mapped new window \"%s\" is alone on desktop \"%s\", focusing", xwin->name, vwm->focused_desktop->name); + vwm_win_focus(vwm, vwin); + } + + return vwin; + +_fail: + if (vwin) { + if (vwin->hints) XFree(vwin->hints); + free(vwin); + } + return NULL; +} + + +/* migrate a window to a new desktop, focuses the destination desktop as well */ +void vwm_win_migrate(vwm_t *vwm, vwm_window_t *vwin, vwm_desktop_t *desktop) +{ + vwm_win_unfocus(vwm, vwin); /* go through the motions of unfocusing the window if it is focused */ + vwin->shelved = 0; /* ensure not shelved */ + vwin->desktop = desktop; /* assign the new desktop */ + vwm_desktop_focus(vwm, desktop); /* currently we always focus the new desktop in a migrate */ + + vwm_win_focus(vwm, vwin); /* focus the window so borders get updated */ + vwm_win_mru(vwm, vwin); /* TODO: is this right? shouldn't the Mod1 release be what's responsible for this? I migrate so infrequently it probably doesn't matter */ + + XRaiseWindow(vwm->display, vwin->xwindow->id); /* ensure the window is raised */ +} diff --git a/src/window.h b/src/window.h new file mode 100644 index 0000000..3b3c745 --- /dev/null +++ b/src/window.h @@ -0,0 +1,81 @@ +#ifndef _WINDOW_H +#define _WINDOW_H + +#include +#include + +#include "list.h" +#include "screen.h" + +typedef struct _vwm_t vwm_t; +typedef struct _vwm_xwindow_t vwm_xwindow_t; +typedef struct _vwm_desktop_t vwm_desktop_t; + +typedef enum _vwm_win_autoconf_t { + VWM_WIN_AUTOCONF_NONE, /* un-autoconfigured window (used to restore the configuration) */ + VWM_WIN_AUTOCONF_QUARTER, /* quarter-screened */ + VWM_WIN_AUTOCONF_HALF, /* half-screened */ + VWM_WIN_AUTOCONF_FULL, /* full-screened */ + VWM_WIN_AUTOCONF_ALL /* all-screened (borderless) */ +} vwm_win_autoconf_t; + +/* the managed window we create for every mapped window we actually manage */ +typedef struct _vwm_window_t { + list_head_t windows_mru; /* global list of managed windows kept in MRU order */ + + vwm_xwindow_t *xwindow; /* window being managed */ + vwm_desktop_t *desktop; /* desktop this window belongs to currently */ + + XWindowAttributes client; /* attrs of the client-configured window */ + + XSizeHints *hints; /* hints the client supplied */ + long hints_supplied; /* bitfield reflecting the hints the client supplied */ + + unsigned int autoconfigured:3; /* autoconfigured window states (none/quarter/half/full/all) */ + unsigned int mapping:1; /* is the window being mapped? (by vwm) */ + unsigned int unmapping:1; /* is the window being unmapped? (by vwm) */ + unsigned int configuring:1; /* is the window being configured/placed? (by vwm) */ + unsigned int shelved:1; /* is the window shelved? */ +} vwm_window_t; + + +void vwm_win_unmap(vwm_t *vwm, vwm_window_t *vwin); +void vwm_win_map(vwm_t *vwm, vwm_window_t *vwin); +void vwm_win_mru(vwm_t *vwm, vwm_window_t *vwin); +vwm_window_t * vwm_win_lookup(vwm_t *vwm, Window win); +vwm_window_t * vwm_win_focused(vwm_t *vwm); + +typedef enum _vwm_side_t { + VWM_SIDE_TOP, + VWM_SIDE_BOTTOM, + VWM_SIDE_LEFT, + VWM_SIDE_RIGHT +} vwm_side_t; + +typedef enum _vwm_corner_t { + VWM_CORNER_TOP_LEFT, + VWM_CORNER_TOP_RIGHT, + VWM_CORNER_BOTTOM_RIGHT, + VWM_CORNER_BOTTOM_LEFT +} vwm_corner_t; + +void vwm_win_autoconf(vwm_t *vwm, vwm_window_t *vwin, vwm_screen_rel_t rel, vwm_win_autoconf_t conf, ...); +void vwm_win_focus(vwm_t *vwm, vwm_window_t *vwin); + +typedef enum _vwm_fence_t { + VWM_FENCE_IGNORE = 0, /* behave as if screen boundaries don't exist (like the pre-Xinerama code) */ + VWM_FENCE_RESPECT, /* confine operation to within the screen */ + VWM_FENCE_TRY_RESPECT, /* confine operation to within the screen, unless no options exist. */ + VWM_FENCE_VIOLATE, /* leave the screen for any other */ + VWM_FENCE_MASKED_VIOLATE /* leave the screen for any other not masked */ +} vwm_fence_t; + +vwm_window_t * vwm_win_focus_next(vwm_t *vwm, vwm_window_t *vwin, vwm_fence_t fence); +void vwm_win_shelve(vwm_t *vwm, vwm_window_t *vwin); +void vwm_win_unfocus(vwm_t *vwm, vwm_window_t *vwin); +vwm_xwindow_t * vwm_win_unmanage(vwm_t *vwm, vwm_window_t *vwin); +vwm_window_t * vwm_win_manage_xwin(vwm_t *vwm, vwm_xwindow_t *xwin); +void vwm_win_migrate(vwm_t *vwm, vwm_window_t *vwin, vwm_desktop_t *desktop); + + +#endif diff --git a/src/xevent.c b/src/xevent.c new file mode 100644 index 0000000..1955ee3 --- /dev/null +++ b/src/xevent.c @@ -0,0 +1,269 @@ +/* + * \/\/\ + * + * Copyright (C) 2012-2016 Vito Caputo - + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3 as published + * by the Free Software Foundation. + * + * 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 . + */ + +#include "X11/Xlib.h" + +#include "key.h" +#include "clickety.h" +#include "composite.h" +#include "desktop.h" +#include "screen.h" +#include "vwm.h" +#include "window.h" +#include "xwindow.h" + +/* this forms the glue between the X event loop in vwm.c and the rest of the + * code making up vwm */ + +void vwm_xevent_handle_key_press(vwm_t *vwm, XKeyPressedEvent *ev) +{ + vwm_key_pressed(vwm, ev->window, ev); +} + + +void vwm_xevent_handle_key_release(vwm_t *vwm, XKeyReleasedEvent *ev) +{ + vwm_key_released(vwm, ev->window, ev); +} + + +void vwm_xevent_handle_button_press(vwm_t *vwm, XButtonPressedEvent *ev) +{ + vwm_clickety_pressed(vwm, ev->window, ev); +} + + +void vwm_xevent_handle_motion_notify(vwm_t *vwm, XMotionEvent *ev) +{ + vwm_clickety_motion(vwm, ev->window, ev); +} + + +void vwm_xevent_handle_button_release(vwm_t *vwm, XButtonReleasedEvent *ev) +{ + vwm_clickety_released(vwm, ev->window, ev); +} + + +void vwm_xevent_handle_create_notify(vwm_t *vwm, XCreateWindowEvent *ev) +{ + vwm_xwin_create(vwm, ev->window, VWM_NOT_GRABBED); +} + + +void vwm_xevent_handle_destroy_notify(vwm_t *vwm, XDestroyWindowEvent *ev) +{ + vwm_xwindow_t *xwin; + + if ((xwin = vwm_xwin_lookup(vwm, ev->window))) { + vwm_xwin_destroy(vwm, xwin); + } +} + + +void vwm_xevent_handle_configure_request(vwm_t *vwm, XConfigureRequestEvent *ev) +{ + XWindowChanges changes = { + .x = ev->x, /* TODO: for now I don't manipulate anything */ + .y = ev->y, + .width = ev->width, + .height = ev->height, + .border_width = WINDOW_BORDER_WIDTH /* except I do override whatever the border width may be */ + }; + unsigned long change_mask = (ev->value_mask & (CWX | CWY | CWWidth | CWHeight)) | CWBorderWidth; + vwm_xwindow_t *xwin; + + /* XXX: windows raising themselves is annoying, so discard CWSibling and CWStackMode. */ + + if ((xwin = vwm_xwin_lookup(vwm, ev->window)) && + xwin->managed && + xwin->managed->autoconfigured == VWM_WIN_AUTOCONF_ALL) { + /* this is to allow auto-allscreen to succeed in getting a borderless window configured */ + change_mask &= ~CWBorderWidth; + } + + XConfigureWindow(vwm->display, ev->window, change_mask, &changes); +} + + +void vwm_xevent_handle_configure_notify(vwm_t *vwm, XConfigureEvent *ev) +{ + vwm_xwindow_t *xwin; + + if ((xwin = vwm_xwin_lookup(vwm, ev->window))) { + XWindowAttributes attrs; + vwm_xwin_restack(vwm, xwin, ev->above); + XGetWindowAttributes(vwm->display, ev->window, &attrs); + vwm_composite_handle_configure(vwm, xwin, &attrs); + VWM_TRACE("pre x=%i y=%i w=%i h=%i\n", xwin->attrs.x, xwin->attrs.y, xwin->attrs.width, xwin->attrs.height); + xwin->attrs = attrs; + VWM_TRACE("post x=%i y=%i w=%i h=%i\n", xwin->attrs.x, xwin->attrs.y, xwin->attrs.width, xwin->attrs.height); + } +} + + +void vwm_xevent_handle_unmap_notify(vwm_t *vwm, XUnmapEvent *ev) +{ + vwm_xwindow_t *xwin; + + /* unlike MapRequest, we simply are notified when a window is unmapped. */ + if ((xwin = vwm_xwin_lookup(vwm, ev->window))) { + if (xwin->managed) { + if (xwin->managed->unmapping) { + VWM_TRACE("swallowed vwm-induced UnmapNotify"); + xwin->managed->unmapping = 0; + } else { + /* client requested unmap, demote the window and note the unmapped state */ + vwm_win_unmanage(vwm, xwin->managed); + xwin->mapped = 0; + } + } else { + /* if it's not managed, we can't have caused the map */ + xwin->mapped = 0; + } + + vwm_composite_damage_win(vwm, xwin); + } +} + + +void vwm_xevent_handle_map_notify(vwm_t *vwm, XMapEvent *ev) +{ + vwm_xwindow_t *xwin; + + if ((xwin = vwm_xwin_lookup(vwm, ev->window))) { + if (xwin->managed && xwin->managed->mapping) { + VWM_TRACE("swallowed vwm-induced MapNotify"); + xwin->managed->mapping = 0; + } else { + /* some windows like popup dialog boxes bypass MapRequest */ + xwin->mapped = 1; + } + + vwm_composite_handle_map(vwm, xwin); + } +} + + +void vwm_xevent_handle_map_request(vwm_t *vwm, XMapRequestEvent *ev) +{ + vwm_xwindow_t *xwin; + vwm_window_t *vwin = NULL; + int domap = 1; + + /* FIXME TODO: this is a fairly spuriously open-coded mess, this stuff + * needs to be factored and moved elsewhere */ + + if ((xwin = vwm_xwin_lookup(vwm, ev->window)) && + ((vwin = xwin->managed) || (vwin = vwm_win_manage_xwin(vwm, xwin)))) { + XWindowAttributes attrs; + XWindowChanges changes = {.x = 0, .y = 0}; + unsigned changes_mask = (CWX | CWY); + XClassHint *classhint; + const vwm_screen_t *scr = NULL; + + xwin->mapped = 1; /* note that the client mapped the window */ + + /* figure out if the window is the console */ + if ((classhint = XAllocClassHint())) { + if (XGetClassHint(vwm->display, ev->window, classhint) && !strcmp(classhint->res_class, CONSOLE_WM_CLASS)) { + vwm->console = vwin; + vwm_win_shelve(vwm, vwin); + vwm_win_autoconf(vwm, vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_FULL); + domap = 0; + } + + if (classhint->res_class) XFree(classhint->res_class); + if (classhint->res_name) XFree(classhint->res_name); + XFree(classhint); + } + + /* TODO: this is a good place to hook in a window placement algo */ + + /* on client-requested mapping we place the window */ + if (!vwin->shelved) { + /* we place the window on the screen containing the the pointer only if that screen is empty, + * otherwise we place windows on the screen containing the currently focused window */ + /* since we query the geometry of windows in determining where to place them, a configuring + * flag is used to exclude the window being configured from those queries */ + scr = vwm_screen_find(vwm, VWM_SCREEN_REL_POINTER); + vwin->configuring = 1; + if (vwm_screen_is_empty(vwm, scr)) { + /* focus the new window if it isn't already focused when it's going to an empty screen */ + VWM_TRACE("window \"%s\" is alone on screen \"%i\", focusing", vwin->xwindow->name, scr->screen_number); + vwm_win_focus(vwm, vwin); + } else { + scr = vwm_screen_find(vwm, VWM_SCREEN_REL_XWIN, vwm->focused_desktop->focused_window->xwindow); + } + vwin->configuring = 0; + + changes.x = scr->x_org; + changes.y = scr->y_org; + } else if (vwm->focused_context == VWM_CONTEXT_SHELF) { + scr = vwm_screen_find(vwm, VWM_SCREEN_REL_XWIN, vwm->focused_shelf->xwindow); + changes.x = scr->x_org; + changes.y = scr->y_org; + } + + /* XXX TODO: does this belong here? */ + XGetWMNormalHints(vwm->display, ev->window, vwin->hints, &vwin->hints_supplied); + XGetWindowAttributes(vwm->display, ev->window, &attrs); + + + /* if the window size is precisely the screen size then directly "allscreen" the window right here */ + if (!vwin->shelved && scr && + attrs.width == scr->width && + attrs.height == scr->height) { + VWM_TRACE("auto-allscreened window \"%s\"", vwin->xwindow->name); + changes.border_width = 0; + changes_mask |= CWBorderWidth; + vwin->autoconfigured = VWM_WIN_AUTOCONF_ALL; + } + + vwin->client.x = changes.x; + vwin->client.y = changes.y; + vwin->client.height = attrs.height; + vwin->client.width = attrs.width; + + XConfigureWindow(vwm->display, ev->window, changes_mask, &changes); + } + + if (domap) { + XMapWindow(vwm->display, ev->window); + if (vwin && vwin->desktop->focused_window == vwin) { + XSync(vwm->display, False); + XSetInputFocus(vwm->display, vwin->xwindow->id, RevertToPointerRoot, CurrentTime); + } + } +} + + +void vwm_xevent_handle_property_notify(vwm_t *vwm, XPropertyEvent *ev) +{ + vwm_xwindow_t *xwin; + + if ((xwin = vwm_xwin_lookup(vwm, ev->window)) && + ev->atom == vwm->wm_pid_atom && + ev->state == PropertyNewValue) vwm_overlay_xwin_create(vwm, xwin); +} + + +void vwm_xevent_handle_mapping_notify(vwm_t *vwm, XMappingEvent *ev) +{ + XRefreshKeyboardMapping(ev); +} diff --git a/src/xevent.h b/src/xevent.h new file mode 100644 index 0000000..dc710fd --- /dev/null +++ b/src/xevent.h @@ -0,0 +1,18 @@ +#include "X11/Xlib.h" + +typedef struct _vwm_t vwm_t; + +void vwm_xevent_handle_key_press(vwm_t *vwm, XKeyPressedEvent *ev); +void vwm_xevent_handle_key_release(vwm_t *vwm, XKeyReleasedEvent *ev); +void vwm_xevent_handle_button_press(vwm_t *vwm, XButtonPressedEvent *ev); +void vwm_xevent_handle_motion_notify(vwm_t *vwm, XMotionEvent *ev); +void vwm_xevent_handle_button_release(vwm_t *vwm, XButtonReleasedEvent *ev); +void vwm_xevent_handle_create_notify(vwm_t *vwm, XCreateWindowEvent *ev); +void vwm_xevent_handle_destroy_notify(vwm_t *vwm, XDestroyWindowEvent *ev); +void vwm_xevent_handle_configure_request(vwm_t *vwm, XConfigureRequestEvent *ev); +void vwm_xevent_handle_configure_notify(vwm_t *vwm, XConfigureEvent *ev); +void vwm_xevent_handle_unmap_notify(vwm_t *vwm, XUnmapEvent *ev); +void vwm_xevent_handle_map_notify(vwm_t *vwm, XMapEvent *ev); +void vwm_xevent_handle_map_request(vwm_t *vwm, XMapRequestEvent *ev); +void vwm_xevent_handle_property_notify(vwm_t *vwm, XPropertyEvent *ev); +void vwm_xevent_handle_mapping_notify(vwm_t *vwm, XMappingEvent *ev); diff --git a/src/xwindow.c b/src/xwindow.c new file mode 100644 index 0000000..f646aac --- /dev/null +++ b/src/xwindow.c @@ -0,0 +1,247 @@ +/* + * \/\/\ + * + * Copyright (C) 2012-2016 Vito Caputo - + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 3 as published + * by the Free Software Foundation. + * + * 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 . + */ + /* bare X windows stuff, there's a distinction between bare xwindows and the vwm managed windows */ +#include +#include +#include + +#include "composite.h" +#include "list.h" +#include "vwm.h" +#include "window.h" +#include "xwindow.h" + +#define HONOR_OVERRIDE_REDIRECT + +/* send a client message to a window (currently used for WM_DELETE) */ +void vwm_xwin_message(vwm_t *vwm, vwm_xwindow_t *xwin, Atom type, long foo) +{ + XEvent event; + + memset(&event, 0, sizeof(event)); + event.xclient.type = ClientMessage; + event.xclient.window = xwin->id; + event.xclient.message_type = type; + event.xclient.format = 32; + event.xclient.data.l[0] = foo; + event.xclient.data.l[1] = CurrentTime; /* XXX TODO: is CurrentTime actually correct to use for this purpose? */ + + XSendEvent(vwm->display, xwin->id, False, 0, &event); +} + + +/* look up the X window in the global xwindows list (includes unmanaged windows like override_redirect/popup menus) */ +vwm_xwindow_t * vwm_xwin_lookup(vwm_t *vwm, Window win) +{ + vwm_xwindow_t *tmp, *xwin = NULL; + + list_for_each_entry(tmp, &vwm->xwindows, xwindows) { + if (tmp->id == win) { + xwin = tmp; + break; + } + } + + return xwin; +} + + +/* determine if a window is mapped (vwm-mapped) according to the current context */ +int vwm_xwin_is_mapped(vwm_t *vwm, vwm_xwindow_t *xwin) +{ + int ret = 0; + + if (!xwin->mapped) return 0; + + if (xwin->managed) { + switch (vwm->focused_context) { + case VWM_CONTEXT_SHELF: + if (vwm->focused_shelf == xwin->managed) ret = xwin->mapped; + break; + + case VWM_CONTEXT_DESKTOP: + if (vwm->focused_desktop == xwin->managed->desktop && !xwin->managed->shelved) ret = xwin->mapped; + break; + + default: + VWM_BUG("Unsupported context"); + break; + } + } else { /* unmanaged xwins like popup dialogs when mapped are always visible */ + ret = 1; + } + + /* annoyingly, Xorg stops delivering VisibilityNotify events for redirected windows, so we don't conveniently know if a window is obscured or not :( */ + /* I could maintain my own data structure for answering this question, but that's pretty annoying when Xorg already has that knowledge. */ + + return ret; +} + + +/* creates and potentially manages a new window (called in response to CreateNotify events, and during startup for all existing windows) */ +/* if the window is already mapped and not an override_redirect window, it becomes managed here. */ +vwm_xwindow_t * vwm_xwin_create(vwm_t *vwm, Window win, vwm_grab_mode_t grabbed) +{ + XWindowAttributes attrs; + vwm_xwindow_t *xwin = NULL; + + VWM_TRACE("creating %#x", (unsigned int)win); + + /* prevent races */ + if (!grabbed) { + XGrabServer(vwm->display); + XSync(vwm->display, False); + } + + /* verify the window still exists */ + if (!XGetWindowAttributes(vwm->display, win, &attrs)) goto _out_grabbed; + + /* don't create InputOnly windows */ + if (attrs.class == InputOnly) goto _out_grabbed; + + if (!(xwin = (vwm_xwindow_t *)malloc(sizeof(vwm_xwindow_t)))) { + VWM_PERROR("Failed to allocate xwin"); + goto _out_grabbed; + } + + xwin->id = win; + xwin->attrs = attrs; + xwin->managed = NULL; + xwin->name = NULL; + XFetchName(vwm->display, win, &xwin->name); + + xwin->monitor = NULL; + xwin->overlay.width = xwin->overlay.height = xwin->overlay.phase = 0; + xwin->overlay.gen_last_composed = -1; + + /* This is so we get the PropertyNotify event and can get the pid when it's set post-create, + * with my _NET_WM_PID patch the property is immediately available */ + XSelectInput(vwm->display, win, PropertyChangeMask); + + /* we must track the mapped-by-client state of the window independent of managed vs. unmanaged because + * in the case of override_redirect windows they may be unmapped (invisible) or mapped (visible) like menus without being managed. + * otherwise we could just use !xwin.managed to indicate unmapped, which is more vwm2-like, but insufficient when compositing. */ + xwin->mapped = (attrs.map_state != IsUnmapped); + + vwm_overlay_xwin_create(vwm, xwin); + vwm_composite_xwin_create(vwm, xwin); + + list_add_tail(&xwin->xwindows, &vwm->xwindows); /* created windows are always placed on the top of the stacking order */ + +#ifdef HONOR_OVERRIDE_REDIRECT + if (!attrs.override_redirect && xwin->mapped) vwm_win_manage_xwin(vwm, xwin); +#else + if (xwin->mapped) vwm_win_manage_xwin(vwm, xwin); +#endif +_out_grabbed: + if (!grabbed) XUngrabServer(vwm->display); + + return xwin; +} + + +/* destroy a window, called in response to DestroyNotify events */ +/* if the window is also managed it will be unmanaged first */ +void vwm_xwin_destroy(vwm_t *vwm, vwm_xwindow_t *xwin) +{ + XGrabServer(vwm->display); + XSync(vwm->display, False); + + if (xwin->managed) vwm_win_unmanage(vwm, xwin->managed); + + list_del(&xwin->xwindows); + + if (xwin->name) XFree(xwin->name); + + vwm_overlay_xwin_destroy(vwm, xwin); + vwm_composite_xwin_destroy(vwm, xwin); + + free(xwin); + + XUngrabServer(vwm->display); +} + + +/* maintain the stack-ordered xwindows list, when new_above is != None xwin is to be placed above new_above, when == None xwin goes to the bottom. */ +void vwm_xwin_restack(vwm_t *vwm, vwm_xwindow_t *xwin, Window new_above) +{ + Window old_above; +#ifdef TRACE + vwm_xwindow_t *tmp; + fprintf(stderr, "restack of %#x new_above=%#x\n", (unsigned int)xwin->id, (unsigned int)new_above); + fprintf(stderr, "restack pre:"); + list_for_each_entry(tmp, &vwm->xwindows, xwindows) { + fprintf(stderr, " %#x", (unsigned int)tmp->id); + } + fprintf(stderr, "\n"); +#endif + if (xwin->xwindows.prev != &vwm->xwindows) { + old_above = list_entry(xwin->xwindows.prev, vwm_xwindow_t, xwindows)->id; + } else { + old_above = None; + } + + if (old_above != new_above) { + vwm_xwindow_t *new; + + if (new_above == None) { /* to the bottom of the stack, so just above the &xwindows head */ + list_move(&xwin->xwindows, &vwm->xwindows); + } else if ((new = vwm_xwin_lookup(vwm, new_above))) { /* to just above new_above */ + list_move(&xwin->xwindows, &new->xwindows); + } + } +#ifdef TRACE + fprintf(stderr, "restack post:"); + list_for_each_entry(tmp, &vwm->xwindows, xwindows) { + fprintf(stderr, " %#x", (unsigned int)tmp->id); + } + fprintf(stderr, "\n\n"); +#endif +} + +/* create xwindows for all existing windows (for startup) */ +int vwm_xwin_create_existing(vwm_t *vwm) +{ + Window root, parent; + Window *children = NULL; + unsigned int n_children, i; + + /* TODO FIXME I don't think this is right anymore, not since we went compositing and split managed vs. bare xwindows... */ + XGrabServer(vwm->display); + XSync(vwm->display, False); + XQueryTree(vwm->display, VWM_XROOT(vwm), &root, &parent, &children, &n_children); + + for (i = 0; i < n_children; i++) { + if (children[i] == None) continue; + + if ((vwm_xwin_create(vwm, children[i], VWM_GRABBED) == NULL)) goto _fail_grabbed; + } + + XUngrabServer(vwm->display); + + if (children) XFree(children); + + return 1; + +_fail_grabbed: + XUngrabServer(vwm->display); + + if (children) XFree(children); + + return 0; +} diff --git a/src/xwindow.h b/src/xwindow.h new file mode 100644 index 0000000..f3be681 --- /dev/null +++ b/src/xwindow.h @@ -0,0 +1,52 @@ +#ifndef _XWIN_H +#define _XWIN_H + +#include +#include +#include + +#include "libvmon/vmon.h" +#include "list.h" +#include "overlay.h" + +typedef struct _vwm_t vwm_t; +typedef struct _vwm_window_t vwm_window_t; + +/* every window gets this, even non-managed ones. For compositing vwm must track everything visible, even popup menus. */ +typedef struct _vwm_xwindow_t { + list_head_t xwindows; /* global list of all windows kept in X stacking order */ + + Window id; /* X Window backing this instance */ + XWindowAttributes attrs; /* X window's current attributes, kept up-to-date in handling of ConfigureNotify events */ + Damage damage; /* X damage object associated with the window (for compositing) */ + Picture picture; /* X picture object representing the window (for compositing) */ + Pixmap pixmap; /* X pixmap object representing the window (for compositing) */ + + vmon_proc_t *monitor; /* vmon process monitor handle, may be NULL if for example the X client doesn't supply a PID */ + vwm_overlay_t overlay; /* monitoring overlay state */ + + char *name; /* client name */ + unsigned int mapped:1; /* is the window currently mapped (by client) */ + unsigned int occluded:1; /* is the window occluded entirely by another window? (used and valid only during paint_all()) */ + /* if only Xorg could send VisibilityNotify events when requested for redirected windows :( */ + vwm_window_t *managed; /* is the window "managed"? NULL or this points to the managed context of the window */ +} vwm_xwindow_t; + +/* creates and potentially manages a new window (called in response to CreateNotify events, and during startup for all existing windows) */ +/* if the window is already mapped and not an override_redirect window, it becomes managed here. */ +typedef enum _vwm_grab_mode_t { + VWM_NOT_GRABBED = 0, + VWM_GRABBED +} vwm_grab_mode_t; + +void vwm_xwin_message(vwm_t *vwm, vwm_xwindow_t *xwin, Atom type, long foo); +vwm_xwindow_t * vwm_xwin_lookup(vwm_t *vwm, Window win); +int vwm_xwin_is_mapped(vwm_t *vwm, vwm_xwindow_t *xwin); +void vwm_xwin_monitor(vwm_t *vwm, vwm_xwindow_t *xwin); +vwm_xwindow_t * vwm_xwin_create(vwm_t *vwm, Window win, vwm_grab_mode_t grabbed); +void vwm_xwin_destroy(vwm_t *vwm, vwm_xwindow_t *xwin); +void vwm_xwin_restack(vwm_t *vwm, vwm_xwindow_t *xwin, Window new_above); +int vwm_xwin_create_existing(vwm_t *vwm); + + +#endif diff --git a/vwm.c b/vwm.c deleted file mode 100644 index f6aa4f7..0000000 --- a/vwm.c +++ /dev/null @@ -1,3285 +0,0 @@ -/* - * \/\/\ - * - * Copyright (C) 2012-2015 Vito Caputo - - * - * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 3 as published - * by the Free Software Foundation. - * - * 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 . - */ - -/* The compositing code is heavily influenced by Keith Packard's xcompmgr. - */ - -#include -#include -#include -#include -#include /* SYNC extension, enables us to give vwm the highest X client priority, helps keep vwm responsive at all times */ -#include /* XINERAMA extension, facilitates easy multihead awareness */ -#include /* RANDR extension, facilitates display configuration change awareness */ -#include /* Damage extension, enables receipt of damage events, reports visible regions needing updating (compositing) */ -#include /* Render extension, enables use of alpha channels and accelerated rendering of surfaces having alpha (compositing) */ -#include /* Composite extension, enables off-screen redirection of window rendering (compositing) */ -#include /* XFixes extension exposes things like regions (compositing) */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "libvmon/vmon.h" -#include "vwm.h" - -#define WINDOW_BORDER_WIDTH 1 -#define CONSOLE_WM_CLASS "VWMConsoleXTerm" /* the class we specify to the "console" xterm */ -#define CONSOLE_SESSION_STRING "_vwm_console.$DISPLAY" /* the unique console screen session identifier */ - -#define WM_GRAB_MODIFIER Mod1Mask /* the modifier for invoking vwm's controls */ - /* Mod4Mask would be the windows key instead of Alt, but there's an assumption - * in the code that grabs are being activated by Alt which complicates changing it, - * search for XGetModifierMapping to see where, feel free to fix it. Or you can - * just hack the code to expect the appropriate key instead of Alt, I didn't see the - * value of making it modifier mapping aware if it's always Alt for me. */ -#define LAUNCHED_RELATIVE_PRIORITY 10 /* the wm priority plus this is used as the priority of launched processes */ -#define HONOR_OVERRIDE_REDIRECT /* search for HONOR_OVERRIDE_REDIRECT for understanding */ - - -#define OVERLAY_MASK_DEPTH 8 /* XXX: 1 would save memory, but Xorg isn't good at it */ -#define OVERLAY_MASK_FORMAT PictStandardA8 -#define OVERLAY_FIXED_FONT "-misc-fixed-medium-r-semicondensed--13-120-75-75-c-60-iso10646-1" -#define OVERLAY_ROW_HEIGHT 15 /* this should always be larger than the font height */ -#define OVERLAY_GRAPH_MIN_WIDTH 200 /* always create graphs at least this large */ -#define OVERLAY_GRAPH_MIN_HEIGHT (4 * OVERLAY_ROW_HEIGHT) -#define OVERLAY_ISTHREAD_ARGV "~" /* use this string to mark threads in the argv field */ -#define OVERLAY_NOCOMM_ARGV "#missed it!" /* use this string to substitute the command when missing in argv field */ - - -typedef enum _vwm_context_focus_t { - VWM_CONTEXT_FOCUS_OTHER = 0, /* focus the other context relative to the current one */ - VWM_CONTEXT_FOCUS_DESKTOP, /* focus the desktop context */ - VWM_CONTEXT_FOCUS_SHELF /* focus the shelf context */ -} vwm_context_focus_t; - -typedef enum _vwm_compositing_mode_t { - VWM_COMPOSITING_OFF = 0, /* non-composited, no redirected windows, most efficient */ - VWM_COMPOSITING_MONITORS = 1 /* composited process monitoring overlays, slower but really useful. */ -} vwm_compositing_mode_t; - -typedef XineramaScreenInfo vwm_screen_t; /* conveniently reuse the xinerama type for describing screens */ - -static LIST_HEAD(desktops); /* global list of all (virtual) desktops in spatial created-in order */ -static LIST_HEAD(desktops_mru); /* global list of all (virtual) desktops in MRU order */ -static LIST_HEAD(windows_mru); /* global list of all managed windows kept in MRU order */ -static LIST_HEAD(xwindows); /* global list of all xwindows kept in the X server stacking order */ -static vwm_window_t *console = NULL; /* the console window */ -static vwm_window_t *focused_origin = NULL; /* the originating window in a grabbed operation/transaction */ -static vwm_desktop_t *focused_desktop = NULL; /* currently focused (virtual) desktop */ -static vwm_window_t *focused_shelf = NULL; /* currently focused shelved window */ -static vwm_context_focus_t focused_context = VWM_CONTEXT_FOCUS_DESKTOP; /* currently focused context */ -static vwm_compositing_mode_t compositing_mode = VWM_COMPOSITING_OFF; /* current compositing mode */ -static int key_is_grabbed = 0; /* flag for tracking keyboard grab state */ -static int priority; /* scheduling priority of the vwm process, launcher nices relative to this */ -static unsigned long fence_mask = 0; /* global mask state for vwm_win_focus_next(... VWM_FENCE_MASKED_VIOLATE), - * if you use vwm on enough screens to overflow this, pics or it didn't happen. */ - - /* Uninteresting stuff */ -static Display *display; -static Colormap cmap; - -#define color(_sym, _str) \ -static XColor _sym ## _color; -#include "colors.def" -#undef color - -static int screen_num; -static GC gc; -static Atom wm_delete_atom; -static Atom wm_protocols_atom; -static Atom wm_pid_atom; -static int sync_event, sync_error; - - /* Xinerama */ -static int xinerama_event, xinerama_error; -static XineramaScreenInfo *xinerama_screens = NULL; -static int xinerama_screens_cnt; -static int randr_event, randr_error; - - /* Compositing */ -static int composite_event, composite_error, composite_opcode; -static int damage_event, damage_error; -static XserverRegion combined_damage = None; -static Picture root_picture = None, root_buffer = None; /* compositing gets double buffered */ -static XWindowAttributes root_attrs; -static XRenderPictureAttributes pa_inferiors = { .subwindow_mode = IncludeInferiors }; - - /* Compositing / Overlays */ -static XFontStruct *overlay_font; -static GC text_gc; -static XRenderPictureAttributes pa_repeat = { .repeat = 1 }; -static XRenderPictureAttributes pa_no_repeat = { .repeat = 0 }; -static Picture overlay_shadow_fill, /* TODO: the repetition here smells like an XMacro waiting to happen */ - overlay_text_fill, - overlay_bg_fill, - overlay_snowflakes_text_fill, - overlay_grapha_fill, - overlay_graphb_fill, - overlay_finish_fill; -static XRenderColor overlay_visible_color = { 0xffff, 0xffff, 0xffff, 0xffff }, - overlay_shadow_color = { 0x0000, 0x0000, 0x0000, 0x8800}, - overlay_bg_color = { 0x0, 0x1000, 0x0, 0x9000}, - overlay_div_color = { 0x2000, 0x3000, 0x2000, 0x9000}, - overlay_snowflakes_visible_color = { 0xd000, 0xd000, 0xd000, 0x8000 }, - overlay_trans_color = {0x00, 0x00, 0x00, 0x00}, - overlay_grapha_color = { 0xff00, 0x0000, 0x0000, 0x3000 }, /* ~red */ - overlay_graphb_color = { 0x0000, 0xffff, 0xffff, 0x3000 }; /* ~cyan */ - - /* libvmon */ -static struct timeval maybe_sample, last_sample, this_sample = {0,0}; -static typeof(((vmon_sys_stat_t *)0)->user) last_user_cpu; -static typeof(((vmon_sys_stat_t *)0)->system) last_system_cpu; -static unsigned long long last_total, this_total, total_delta; -static unsigned long long last_idle, last_iowait, idle_delta, iowait_delta; -static vmon_t vmon; - -static float sampling_intervals[] = { - 1, /* ~1Hz */ - .1, /* ~10Hz */ - .05, /* ~20Hz */ - .025, /* ~40Hz */ - .01666}; /* ~60Hz */ -static int prev_sampling_interval = 1, sampling_interval = 1; - - /* some needed prototypes */ -static vwm_xwindow_t * vwm_xwin_lookup(Window win); -static inline int vwm_xwin_is_mapped(vwm_xwindow_t *xwin); -static void vwm_comp_damage_add(XserverRegion damage); -static vwm_xwindow_t * vwm_win_unmanage(vwm_window_t *vwin); -static vwm_window_t * vwm_win_manage_xwin(vwm_xwindow_t *xwin); -static void vwm_win_unmap(vwm_window_t *vwin); -static void vwm_win_map(vwm_window_t *vwin); -static void vwm_win_focus(vwm_window_t *vwin); -static void vwm_keypressed(Window win, XEvent *keypress); - -#define MIN(_a, _b) ((_a) < (_b) ? (_a) : (_b)) -#define MAX(_a, _b) ((_a) > (_b) ? (_a) : (_b)) - - - /* libvmon integration, warning: this gets a little crazy especially in the rendering. */ - -/* space we need for every process being monitored */ -typedef struct _vwm_perproc_ctxt_t { - typeof(vmon.generation) generation; - typeof(((vmon_proc_stat_t *)0)->utime) last_utime; - typeof(((vmon_proc_stat_t *)0)->stime) last_stime; - typeof(((vmon_proc_stat_t *)0)->utime) utime_delta; - typeof(((vmon_proc_stat_t *)0)->stime) stime_delta; -} vwm_perproc_ctxt_t; - - -/* moves what's below a given row up above it if specified, the row becoming discarded */ -static void snowflake_row(vwm_xwindow_t *xwin, Picture pic, int copy, int row) -{ - VWM_TRACE("pid=%i xwin=%p row=%i copy=%i heirarhcy_end=%i", xwin->monitor->pid, xwin, row, copy, xwin->overlay.heirarchy_end); - - if (copy) { - /* copy row to tmp */ - XRenderComposite(display, PictOpSrc, pic, None, xwin->overlay.tmp_picture, - 0, row * OVERLAY_ROW_HEIGHT, /* src */ - 0, 0, /* mask */ - 0, 0, /* dest */ - xwin->overlay.width, OVERLAY_ROW_HEIGHT); /* dimensions */ - } - - /* shift up */ - XRenderChangePicture(display, pic, CPRepeat, &pa_no_repeat); - XRenderComposite(display, PictOpSrc, pic, None, pic, - 0, (1 + row) * OVERLAY_ROW_HEIGHT, /* src */ - 0, 0, /* mask */ - 0, row * OVERLAY_ROW_HEIGHT, /* dest */ - xwin->overlay.width, (1 + xwin->overlay.heirarchy_end) * OVERLAY_ROW_HEIGHT - (1 + row) * OVERLAY_ROW_HEIGHT); /* dimensions */ - XRenderChangePicture(display, pic, CPRepeat, &pa_repeat); - - if (copy) { - /* copy tmp to top of snowflakes */ - XRenderComposite(display, PictOpSrc, xwin->overlay.tmp_picture, None, pic, - 0, 0, /* src */ - 0, 0, /* mask */ - 0, (xwin->overlay.heirarchy_end) * OVERLAY_ROW_HEIGHT, /* dest */ - xwin->overlay.width, OVERLAY_ROW_HEIGHT); /* dimensions */ - } else { - /* clear the snowflake row */ - XRenderFillRectangle(display, PictOpSrc, pic, &overlay_trans_color, - 0, (xwin->overlay.heirarchy_end) * OVERLAY_ROW_HEIGHT, /* dest */ - xwin->overlay.width, OVERLAY_ROW_HEIGHT); /* dimensions */ - } -} - -/* XXX TODO libvmon automagic children following races with explicit X client pid monitoring with different outcomes, it should be irrelevant which wins, - * currently the only visible difference is the snowflakes gap (heirarchy_end) varies, which is why I haven't bothered to fix it, I barely even notice. - */ - -/* shifts what's below a given row down a row, and clears the row, preparing it for populating */ -static void allocate_row(vwm_xwindow_t *xwin, Picture pic, int row) -{ - VWM_TRACE("pid=%i xwin=%p row=%i", xwin->monitor->pid, xwin, row); - - /* shift everything below the row down */ - XRenderComposite(display, PictOpSrc, pic, None, pic, - 0, row * OVERLAY_ROW_HEIGHT, /* src */ - 0, 0, /* mask */ - 0, (1 + row) * OVERLAY_ROW_HEIGHT, /* dest */ - xwin->overlay.width, xwin->overlay.height - (1 + row) * OVERLAY_ROW_HEIGHT); /* dimensions */ - /* fill the space created with transparent pixels */ - XRenderFillRectangle(display, PictOpSrc, pic, &overlay_trans_color, - 0, row * OVERLAY_ROW_HEIGHT, /* dest */ - xwin->overlay.width, OVERLAY_ROW_HEIGHT); /* dimensions */ -} - - -/* shadow a row from the text layer in the shadow layer */ -static void shadow_row(vwm_xwindow_t *xwin, int row) -{ - /* the current technique for creating the shadow is to simply render the text at +1/-1 pixel offsets on both axis in translucent black */ - XRenderComposite(display, PictOpSrc, overlay_shadow_fill, xwin->overlay.text_picture, xwin->overlay.shadow_picture, - 0, 0, - -1, row * OVERLAY_ROW_HEIGHT, - 0, row * OVERLAY_ROW_HEIGHT, - xwin->attrs.width, OVERLAY_ROW_HEIGHT); - - XRenderComposite(display, PictOpOver, overlay_shadow_fill, xwin->overlay.text_picture, xwin->overlay.shadow_picture, - 0, 0, - 0, -1 + row * OVERLAY_ROW_HEIGHT, - 0, row * OVERLAY_ROW_HEIGHT, - xwin->attrs.width, OVERLAY_ROW_HEIGHT); - - XRenderComposite(display, PictOpOver, overlay_shadow_fill, xwin->overlay.text_picture, xwin->overlay.shadow_picture, - 0, 0, - 1, row * OVERLAY_ROW_HEIGHT, - 0, row * OVERLAY_ROW_HEIGHT, - xwin->attrs.width, OVERLAY_ROW_HEIGHT); - - XRenderComposite(display, PictOpOver, overlay_shadow_fill, xwin->overlay.text_picture, xwin->overlay.shadow_picture, - 0, 0, - 0, 1 + row * OVERLAY_ROW_HEIGHT, - 0, row * OVERLAY_ROW_HEIGHT, - xwin->attrs.width, OVERLAY_ROW_HEIGHT); -} - - -/* simple helper to map the vmon per-proc argv array into an XTextItem array, deals with threads vs. processes and the possibility of the comm field not getting read in before the process exited... */ -static void argv2xtext(vmon_proc_t *proc, XTextItem *items, int *nr_items) /* XXX TODO: reallocate items when too small... */ -{ - int i; - int nr = 0; - - if (proc->is_thread) { /* stick the thread marker at the start of threads */ - items[0].nchars = sizeof(OVERLAY_ISTHREAD_ARGV) - 1; - items[0].chars = OVERLAY_ISTHREAD_ARGV; - items[0].delta = 4; - items[0].font = None; - nr++; - } - - if (((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->comm.len) { - items[nr].nchars = ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->comm.len - 1; - items[nr].chars = ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->comm.array; - } else { - /* sometimes a process is so ephemeral we don't manage to sample its comm, XXX TODO: we always have a pid, stringify it? */ - items[nr].nchars = sizeof(OVERLAY_NOCOMM_ARGV) - 1; - items[nr].chars = OVERLAY_NOCOMM_ARGV; - } - items[nr].delta = 4; - items[nr].font = None; - nr++; - - for (i = 1; i < ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->argc; nr++, i++) { - items[nr].chars = ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->argv[i]; - items[nr].nchars = strlen(((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->argv[i]); /* TODO: libvmon should inform us of the length */ - items[nr].delta = 4; - items[nr].font = None; - } - - (*nr_items) = nr; -} - - -/* helper for counting number of existing descendants subtrees */ -static int count_rows(vmon_proc_t *proc) { - int count = 1; /* XXX maybe suppress proc->is_new? */ - vmon_proc_t *child; - - if (!proc->is_thread) { - list_for_each_entry(child, &proc->threads, threads) { - count += count_rows(child); - } - } - - list_for_each_entry(child, &proc->children, siblings) { - count += count_rows(child); - } - - return count; -} - - -/* recursive draw function for the consolidated version of the overlay rendering which also implements snowflakes */ -static void draw_overlay(vwm_xwindow_t *xwin, vmon_proc_t *proc, int *depth, int *row) -{ - vmon_proc_t *child; - vwm_perproc_ctxt_t *proc_ctxt = proc->foo; - vmon_proc_stat_t *proc_stat = proc->stores[VMON_STORE_PROC_STAT]; - - /* graph variables */ - int a_height, b_height; - double utime_delta, stime_delta; - - /* text variables */ - char str[256]; - int str_len; - XTextItem items[1024]; /* XXX TODO: dynamically allocate this and just keep it at the high water mark.. create a struct to encapsulate this, nr_items, and alloc_items... */ - int nr_items; - int direction, ascent, descent; - XCharStruct charstruct; - - if ((*row)) { /* except row 0 (Idle/IOWait graph), handle any stale and new processes/threads */ - if (proc->is_stale) { - /* what to do when a process (subtree) has gone away */ - static int in_stale = 0; - int in_stale_entrypoint = 0; - - /* I snowflake the stale processes from the leaves up for a more intuitive snowflake order... - * (I expect the command at the root of the subtree to appear at the top of the snowflakes...) */ - /* This does require that I do a separate forward recursion to determine the number of rows - * so I can correctly snowflake in reverse */ - if (!in_stale) { - VWM_TRACE("entered stale at xwin=%p depth=%i row=%i", xwin, *depth, *row); - in_stale_entrypoint = in_stale = 1; - (*row) += count_rows(proc) - 1; - } - - (*depth)++; - list_for_each_entry_prev(child, &proc->children, siblings) { - draw_overlay(xwin, child, depth, row); - (*row)--; - } - - if (!proc->is_thread) { - list_for_each_entry_prev(child, &proc->threads, threads) { - draw_overlay(xwin, child, depth, row); - (*row)--; - } - } - (*depth)--; - - VWM_TRACE("%i (%.*s) is stale @ depth %i row %i is_thread=%i", proc->pid, - ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->comm.len - 1, - ((vmon_proc_stat_t *)proc->stores[VMON_STORE_PROC_STAT])->comm.array, - (*depth), (*row), proc->is_thread); - - /* stamp the graphs with the finish line */ - XRenderComposite(display, PictOpSrc, overlay_finish_fill, None, xwin->overlay.grapha_picture, - 0, 0, /* src x, y */ - 0, 0, /* mask x, y */ - xwin->overlay.phase, (*row) * OVERLAY_ROW_HEIGHT, /* dst x, y */ - 1, OVERLAY_ROW_HEIGHT - 1); - XRenderComposite(display, PictOpSrc, overlay_finish_fill, None, xwin->overlay.graphb_picture, - 0, 0, /* src x, y */ - 0, 0, /* mask x, y */ - xwin->overlay.phase, (*row) * OVERLAY_ROW_HEIGHT, /* dst x, y */ - 1, OVERLAY_ROW_HEIGHT - 1); - - /* extract the row from the various layers */ - snowflake_row(xwin, xwin->overlay.grapha_picture, 1, (*row)); - snowflake_row(xwin, xwin->overlay.graphb_picture, 1, (*row)); - snowflake_row(xwin, xwin->overlay.text_picture, 0, (*row)); - snowflake_row(xwin, xwin->overlay.shadow_picture, 0, (*row)); - xwin->overlay.snowflakes_cnt++; - - /* stamp the name (and whatever else we include) into overlay.text_picture */ - argv2xtext(proc, items, &nr_items); - XDrawText(display, xwin->overlay.text_pixmap, text_gc, - 5, (xwin->overlay.heirarchy_end + 1) * OVERLAY_ROW_HEIGHT - 3,/* dst x, y */ - items, nr_items); - shadow_row(xwin, xwin->overlay.heirarchy_end); - - xwin->overlay.heirarchy_end--; - - if (in_stale_entrypoint) { - VWM_TRACE("exited stale at xwin=%p depth=%i row=%i", xwin, *depth, *row); - in_stale = 0; - } - - return; - } else if (proc->is_new) { - /* what to do when a process has been introduced */ - VWM_TRACE("%i is new", proc->pid); - - allocate_row(xwin, xwin->overlay.grapha_picture, (*row)); - allocate_row(xwin, xwin->overlay.graphb_picture, (*row)); - allocate_row(xwin, xwin->overlay.text_picture, (*row)); - allocate_row(xwin, xwin->overlay.shadow_picture, (*row)); - - xwin->overlay.heirarchy_end++; - } - } - -/* CPU utilization graphs */ - if (!(*row)) { - /* XXX: sortof kludged in IOWait and Idle % @ row 0 */ - stime_delta = iowait_delta; - utime_delta = idle_delta; - } else { - /* use the generation number to avoid recomputing this stuff for callbacks recurring on the same process in the same sample */ - if (proc_ctxt->generation != vmon.generation) { - proc_ctxt->stime_delta = proc_stat->stime - proc_ctxt->last_stime; - proc_ctxt->utime_delta = proc_stat->utime - proc_ctxt->last_utime; - proc_ctxt->last_utime = proc_stat->utime; - proc_ctxt->last_stime = proc_stat->stime; - - proc_ctxt->generation = vmon.generation; - } - - if (proc->is_new) { - /* we need a minimum of two samples before we can compute a delta to plot, - * so we suppress that and instead mark the start of monitoring with an impossible 100% of both graph contexts, a starting line. */ - stime_delta = utime_delta = total_delta; - } else { - stime_delta = proc_ctxt->stime_delta; - utime_delta = proc_ctxt->utime_delta; - } - } - - /* compute the bar heights for this sample */ - a_height = (stime_delta / total_delta * (double)(OVERLAY_ROW_HEIGHT - 1)); /* give up 1 pixel for the div */ - b_height = (utime_delta / total_delta * (double)(OVERLAY_ROW_HEIGHT - 1)); - - /* round up to 1 pixel when the scaled result is a fraction less than 1, - * I want to at least see 1 pixel blips for the slightest cpu utilization */ - if (stime_delta && !a_height) a_height = 1; - if (utime_delta && !b_height) b_height = 1; - - /* draw the two bars for this sample at the current phase in the graphs, note the first is ceiling-based, second floor-based */ - XRenderFillRectangle(display, PictOpSrc, xwin->overlay.grapha_picture, &overlay_visible_color, - xwin->overlay.phase, (*row) * OVERLAY_ROW_HEIGHT, /* dst x, y */ - 1, a_height); /* dst w, h */ - XRenderFillRectangle(display, PictOpSrc, xwin->overlay.graphb_picture, &overlay_visible_color, - xwin->overlay.phase, (*row) * OVERLAY_ROW_HEIGHT + (OVERLAY_ROW_HEIGHT - b_height) - 1, /* dst x, y */ - 1, b_height); /* dst w, h */ - - if (!(*row)) { - /* here's where the Idle/IOWait row drawing concludes */ - if (compositing_mode) { - snprintf(str, sizeof(str), "\\/\\/\\ %2iHz %n", (int)(sampling_interval < 0 ? 0 : 1 / sampling_intervals[sampling_interval]), &str_len); - /* TODO: I clear and redraw this row every time, which is unnecessary, small optimization would be to only do so when: - * - overlay resized, and then constrain the clear to the affected width - * - Hz changed - */ - XRenderFillRectangle(display, PictOpSrc, xwin->overlay.text_picture, &overlay_trans_color, - 0, 0, /* dst x, y */ - xwin->attrs.width, OVERLAY_ROW_HEIGHT); /* dst w, h */ - XTextExtents(overlay_font, str, str_len, &direction, &ascent, &descent, &charstruct); - XDrawString(display, xwin->overlay.text_pixmap, text_gc, - xwin->attrs.width - charstruct.width, OVERLAY_ROW_HEIGHT - 3, /* dst x, y */ - str, str_len); - shadow_row(xwin, 0); - } - (*row)++; - draw_overlay(xwin, proc, depth, row); - return; - } - -/* process heirarchy text and accompanying per-process details like wchan/pid/state... */ - if (compositing_mode) { /* this stuff can be skipped when monitors aren't visible */ - /* TODO: make the columns interactively configurable @ runtime */ - if (!proc->is_new) { - /* XXX for now always clear the row, this should be capable of being optimized in the future (if the datums driving the text haven't changed...) */ - XRenderFillRectangle(display, PictOpSrc, xwin->overlay.text_picture, &overlay_trans_color, - 0, (*row) * OVERLAY_ROW_HEIGHT, /* dst x, y */ - xwin->overlay.width, OVERLAY_ROW_HEIGHT); /* dst w, h */ - } - - /* put the process' wchan, state, and PID columns @ the far right */ - if (proc->is_thread || list_empty(&proc->threads)) { /* only threads or non-threaded processes include the wchan and state */ - snprintf(str, sizeof(str), " %.*s %5i %c %n", - proc_stat->wchan.len, - proc_stat->wchan.len == 1 && proc_stat->wchan.array[0] == '0' ? "-" : proc_stat->wchan.array, - proc->pid, - proc_stat->state, - &str_len); - } else { /* we're a process having threads, suppress the wchan and state, as they will be displayed for the thread of same pid */ - snprintf(str, sizeof(str), " %5i %n", proc->pid, &str_len); - } - - XTextExtents(overlay_font, str, str_len, &direction, &ascent, &descent, &charstruct); - - /* the process' comm label indented according to depth, followed with their respective argv's */ - argv2xtext(proc, items, &nr_items); - XDrawText(display, xwin->overlay.text_pixmap, text_gc, - (*depth) * (OVERLAY_ROW_HEIGHT / 2), ((*row) + 1) * OVERLAY_ROW_HEIGHT - 3, /* dst x, y */ - items, nr_items); - - /* ensure the area for the rest of the stuff is cleared, we don't put much text into thread rows so skip it for those. */ - if (!proc->is_thread) { - XRenderFillRectangle(display, PictOpSrc, xwin->overlay.text_picture, &overlay_trans_color, - xwin->attrs.width - charstruct.width, (*row) * OVERLAY_ROW_HEIGHT, /* dst x,y */ - xwin->overlay.width - (xwin->attrs.width - charstruct.width), OVERLAY_ROW_HEIGHT); /* dst w,h */ - } - - XDrawString(display, xwin->overlay.text_pixmap, text_gc, - xwin->attrs.width - charstruct.width, ((*row) + 1) * OVERLAY_ROW_HEIGHT - 3, /* dst x, y */ - str, str_len); - - /* only if this process isn't the root process @ the window shall we consider all relational drawing conditions */ - if (proc != xwin->monitor) { - vmon_proc_t *ancestor, *sibling, *last_sibling = NULL; - struct list_head *rem; - int needs_tee = 0; - int bar_x = 0, bar_y = 0; - int sub; - - /* XXX: everything done in this code block only dirties _this_ process' row in the rendered overlay output */ - - /* walk up the ancestors until reaching xwin->monitor, any ancestors we encounter which have more siblings we draw a vertical bar for */ - /* this draws the |'s in something like: | | | | comm */ - for (sub = 1, ancestor = proc->parent; ancestor && ancestor != xwin->monitor; ancestor = ancestor->parent) { - sub++; - bar_x = ((*depth) - sub) * (OVERLAY_ROW_HEIGHT / 2) + 4; - bar_y = ((*row) + 1) * OVERLAY_ROW_HEIGHT; - - /* determine if the ancestor has remaining siblings which are not stale, if so, draw a connecting bar at its depth */ - for (rem = ancestor->siblings.next; rem != &ancestor->parent->children; rem = rem->next) { - if (!(list_entry(rem, vmon_proc_t, siblings)->is_stale)) { - XDrawLine(display, xwin->overlay.text_pixmap, text_gc, - bar_x, bar_y - OVERLAY_ROW_HEIGHT, /* dst x1, y1 */ - bar_x, bar_y); /* dst x2, y2 (vertical line) */ - break; /* stop looking for more siblings at this ancestor when we find one that isn't stale */ - } - } - } - - /* determine if _any_ of our siblings have children requiring us to draw a tee immediately before our comm string. - * The only sibling which doesn't cause this to happen is the last one in the children list, if it has children it has no impact on its remaining - * siblings, as there are none. - * - * This draws the + in something like: | | | | +comm - */ - - /* find the last sibling (this has to be done due to the potential for stale siblings at the tail, and we'd rather not repeatedly check for it) */ - list_for_each_entry(sibling, &proc->parent->children, siblings) { - if (!sibling->is_stale) last_sibling = sibling; - } - - /* now look for siblings with non-stale children to determine if a tee is needed, ignoring the last sibling */ - list_for_each_entry(sibling, &proc->parent->children, siblings) { - /* skip stale siblings, they aren't interesting as they're invisible, and the last sibling has no bearing on wether we tee or not. */ - if (sibling->is_stale || sibling == last_sibling) continue; - - /* if any of the other siblings have children which are not stale, put a tee in front of our name, but ignore stale children */ - list_for_each_entry(child, &sibling->children, siblings) { - if (!child->is_stale) { - needs_tee = 1; - break; - } - } - - /* if we still don't think we need a tee, check if there are threads */ - if (!needs_tee) { - list_for_each_entry(child, &sibling->threads, threads) { - if (!child->is_stale) { - needs_tee = 1; - break; - } - } - } - - /* found a tee is necessary, all that's left is to determine if the tee is a corner and draw it accordingly, stopping the search. */ - if (needs_tee) { - bar_x = ((*depth) - 1) * (OVERLAY_ROW_HEIGHT / 2) + 4; - - /* if we're the last sibling, corner the tee by shortening the vbar */ - if (proc == last_sibling) { - XDrawLine(display, xwin->overlay.text_pixmap, text_gc, - bar_x, bar_y - OVERLAY_ROW_HEIGHT, /* dst x1, y1 */ - bar_x, bar_y - 4); /* dst x2, y2 (vertical bar) */ - } else { - XDrawLine(display, xwin->overlay.text_pixmap, text_gc, - bar_x, bar_y - OVERLAY_ROW_HEIGHT, /* dst x1, y1 */ - bar_x, bar_y); /* dst x2, y2 (vertical bar) */ - } - - XDrawLine(display, xwin->overlay.text_pixmap, text_gc, - bar_x, bar_y - 4, /* dst x1, y1 */ - bar_x + 2, bar_y - 4); /* dst x2, y2 (horizontal bar) */ - - /* terminate the outer sibling loop upon drawing the tee... */ - break; - } - } - } - shadow_row(xwin, (*row)); - } - - (*row)++; - - /* recur any threads first, then any children processes */ - (*depth)++; - if (!proc->is_thread) { /* XXX: the threads member serves as the list head only when not a thread */ - list_for_each_entry(child, &proc->threads, threads) { - draw_overlay(xwin, child, depth, row); - } - } - - list_for_each_entry(child, &proc->children, siblings) { - draw_overlay(xwin, child, depth, row); - } - (*depth)--; -} - - -/* consolidated version of overlay text and graph rendering, makes snowflakes integration cleaner, this always gets called regadless of the overlays mode */ -static void maintain_overlay(vwm_xwindow_t *xwin) -{ - int row = 0, depth = 0; - - if (!xwin->monitor || !xwin->monitor->stores[VMON_STORE_PROC_STAT]) return; - - /* TODO: - * I side effect of responding to window resizes in this function is there's a latency proportional to the current sample_interval. - * Something to fix is to resize the overlays when the window resizes. - * However, simply resizing the overlays is insufficient. Their contents need to be redrawn in the new dimensions, this is where it - * gets annoying. The current maintain/draw_overlay makes assumptions about being run from the periodic vmon per-process callback. - * There needs to be a redraw mode added where draw_overlay is just reconstructing the current state, which requires that we suppress - * the phase advance and in maintain_overlay() and just enter draw_overlay() to redraw everything for the same generation. - * So this probably requires some tweaking of draw_overlay() as well as maintain_overlay(). I want to be able tocall mainta_overlays() - * from anywhere, and have it detect if it's being called on the same generation or if the generation has advanced. - * For now, the monitors will just be a little latent in window resizes which is pretty harmless artifact. - */ - - /* if the window is larger than the overlays currently are, enlarge them */ - if (xwin->attrs.width > xwin->overlay.width || xwin->attrs.height > xwin->overlay.height) { - vwm_overlay_t existing; - Pixmap pixmap; - - existing = xwin->overlay; - - xwin->overlay.width = MAX(xwin->overlay.width, MAX(xwin->attrs.width, OVERLAY_GRAPH_MIN_WIDTH)); - xwin->overlay.height = MAX(xwin->overlay.height, MAX(xwin->attrs.height, OVERLAY_GRAPH_MIN_HEIGHT)); - - pixmap = XCreatePixmap(display, RootWindow(display, screen_num), xwin->overlay.width, xwin->overlay.height, OVERLAY_MASK_DEPTH); - xwin->overlay.grapha_picture = XRenderCreatePicture(display, pixmap, XRenderFindStandardFormat(display, OVERLAY_MASK_FORMAT), CPRepeat, &pa_repeat); - XFreePixmap(display, pixmap); - XRenderFillRectangle(display, PictOpSrc, xwin->overlay.grapha_picture, &overlay_trans_color, 0, 0, xwin->overlay.width, xwin->overlay.height); - - pixmap = XCreatePixmap(display, RootWindow(display, screen_num), xwin->overlay.width, xwin->overlay.height, OVERLAY_MASK_DEPTH); - xwin->overlay.graphb_picture = XRenderCreatePicture(display, pixmap, XRenderFindStandardFormat(display, OVERLAY_MASK_FORMAT), CPRepeat, &pa_repeat); - XFreePixmap(display, pixmap); - XRenderFillRectangle(display, PictOpSrc, xwin->overlay.graphb_picture, &overlay_trans_color, 0, 0, xwin->overlay.width, xwin->overlay.height); - - pixmap = XCreatePixmap(display, RootWindow(display, screen_num), xwin->overlay.width, OVERLAY_ROW_HEIGHT, OVERLAY_MASK_DEPTH); - xwin->overlay.tmp_picture = XRenderCreatePicture(display, pixmap, XRenderFindStandardFormat(display, OVERLAY_MASK_FORMAT), 0, NULL); - XFreePixmap(display, pixmap); - - /* keep the text_pixmap reference around for XDrawText usage */ - xwin->overlay.text_pixmap = XCreatePixmap(display, RootWindow(display, screen_num), xwin->overlay.width, xwin->overlay.height, OVERLAY_MASK_DEPTH); - xwin->overlay.text_picture = XRenderCreatePicture(display, xwin->overlay.text_pixmap, XRenderFindStandardFormat(display, OVERLAY_MASK_FORMAT), 0, NULL); - XRenderFillRectangle(display, PictOpSrc, xwin->overlay.text_picture, &overlay_trans_color, 0, 0, xwin->overlay.width, xwin->overlay.height); - - pixmap = XCreatePixmap(display, RootWindow(display, screen_num), xwin->overlay.width, xwin->overlay.height, OVERLAY_MASK_DEPTH); - xwin->overlay.shadow_picture = XRenderCreatePicture(display, pixmap, XRenderFindStandardFormat(display, OVERLAY_MASK_FORMAT), 0, NULL); - XFreePixmap(display, pixmap); - XRenderFillRectangle(display, PictOpSrc, xwin->overlay.shadow_picture, &overlay_trans_color, 0, 0, xwin->overlay.width, xwin->overlay.height); - - pixmap = XCreatePixmap(display, RootWindow(display, screen_num), xwin->overlay.width, xwin->overlay.height, 32); - xwin->overlay.picture = XRenderCreatePicture(display, pixmap, XRenderFindStandardFormat(display, PictStandardARGB32), 0, NULL); - XFreePixmap(display, pixmap); - - if (existing.width) { - /* XXX: note the graph pictures are copied from their current phase in the x dimension */ - XRenderComposite(display, PictOpSrc, existing.grapha_picture, None, xwin->overlay.grapha_picture, - existing.phase, 0, /* src x, y */ - 0, 0, /* mask x, y */ - 0, 0, /* dest x, y */ - existing.width, existing.height); - XRenderComposite(display, PictOpSrc, existing.graphb_picture, None, xwin->overlay.graphb_picture, - existing.phase, 0, /* src x, y */ - 0, 0, /* mask x, y */ - 0, 0, /* dest x, y */ - existing.width, existing.height); - XRenderComposite(display, PictOpSrc, existing.text_picture, None, xwin->overlay.text_picture, - 0, 0, /* src x, y */ - 0, 0, /* mask x, y */ - 0, 0, /* dest x, y */ - existing.width, existing.height); - XRenderComposite(display, PictOpSrc, existing.shadow_picture, None, xwin->overlay.shadow_picture, - 0, 0, /* src x, y */ - 0, 0, /* mask x, y */ - 0, 0, /* dest x, y */ - existing.width, existing.height); - XRenderComposite(display, PictOpSrc, existing.picture, None, xwin->overlay.picture, - 0, 0, /* src x, y */ - 0, 0, /* mask x, y */ - 0, 0, /* dest x, y */ - existing.width, existing.height); - xwin->overlay.phase = 0; /* having unrolled the existing graph[ab] pictures into the larger ones, phase is reset to 0 */ - XRenderFreePicture(display, existing.grapha_picture); - XRenderFreePicture(display, existing.graphb_picture); - XRenderFreePicture(display, existing.tmp_picture); - XRenderFreePicture(display, existing.text_picture); - XFreePixmap(display, existing.text_pixmap); - XRenderFreePicture(display, existing.shadow_picture); - XRenderFreePicture(display, existing.picture); - } - } - - xwin->overlay.phase += (xwin->overlay.width - 1); /* simply change this to .phase++ to scroll the other direction */ - xwin->overlay.phase %= xwin->overlay.width; - XRenderFillRectangle(display, PictOpSrc, xwin->overlay.grapha_picture, &overlay_trans_color, xwin->overlay.phase, 0, 1, xwin->overlay.height); - XRenderFillRectangle(display, PictOpSrc, xwin->overlay.graphb_picture, &overlay_trans_color, xwin->overlay.phase, 0, 1, xwin->overlay.height); - - /* recursively draw the monitored processes to the overlay */ - draw_overlay(xwin, xwin->monitor, &depth, &row); -} - - -/* return the composed height of the overlay */ -static int overlay_composed_height(vwm_xwindow_t *xwin) -{ - int snowflakes = xwin->overlay.snowflakes_cnt ? 1 + xwin->overlay.snowflakes_cnt : 0; /* don't include the separator row if there are no snowflakes */ - return MIN((xwin->overlay.heirarchy_end + snowflakes) * OVERLAY_ROW_HEIGHT, xwin->attrs.height); -} - - -/* this composes the maintained overlay into the window's overlay picture, this gets called from paint_all() on every repaint of xwin */ -/* we noop the call if the gen_last_composed and monitor->proc.generation numbers match, indicating there's nothing new to compose. */ -static void compose_overlay(vwm_xwindow_t *xwin) -{ - XserverRegion region; - XRectangle damage; - int height; - - if (!xwin->overlay.width) return; /* prevent winning race with maintain_overlay() and using an unready overlay... */ - - if (xwin->overlay.gen_last_composed == xwin->monitor->generation) return; /* noop if no sampling occurred since last compose */ - xwin->overlay.gen_last_composed = xwin->monitor->generation; /* remember this generation */ - - //VWM_TRACE("composing %p", xwin); - - height = overlay_composed_height(xwin); - - /* fill the overlay picture with the background */ - XRenderComposite(display, PictOpSrc, overlay_bg_fill, None, xwin->overlay.picture, - 0, 0, - 0, 0, - 0, 0, - xwin->attrs.width, height); - - /* draw the graphs into the overlay through the stencils being maintained by the sample callbacks */ - XRenderComposite(display, PictOpOver, overlay_grapha_fill, xwin->overlay.grapha_picture, xwin->overlay.picture, - 0, 0, - xwin->overlay.phase, 0, - 0, 0, - xwin->attrs.width, height); - XRenderComposite(display, PictOpOver, overlay_graphb_fill, xwin->overlay.graphb_picture, xwin->overlay.picture, - 0, 0, - xwin->overlay.phase, 0, - 0, 0, - xwin->attrs.width, height); - - /* draw the shadow into the overlay picture using a translucent black source drawn through the shadow mask */ - XRenderComposite(display, PictOpOver, overlay_shadow_fill, xwin->overlay.shadow_picture, xwin->overlay.picture, - 0, 0, - 0, 0, - 0, 0, - xwin->attrs.width, height); - - /* render overlay text into the overlay picture using a white source drawn through the overlay text as a mask, on top of everything */ - XRenderComposite(display, PictOpOver, overlay_text_fill, xwin->overlay.text_picture, xwin->overlay.picture, - 0, 0, - 0, 0, - 0, 0, - xwin->attrs.width, (xwin->overlay.heirarchy_end * OVERLAY_ROW_HEIGHT)); - - XRenderComposite(display, PictOpOver, overlay_snowflakes_text_fill, xwin->overlay.text_picture, xwin->overlay.picture, - 0, 0, - 0, xwin->overlay.heirarchy_end * OVERLAY_ROW_HEIGHT, - 0, xwin->overlay.heirarchy_end * OVERLAY_ROW_HEIGHT, - xwin->attrs.width, height - (xwin->overlay.heirarchy_end * OVERLAY_ROW_HEIGHT)); - - /* damage the window to ensure the updated overlay is drawn (TODO: this can be done more selectively/efficiently) */ - damage.x = xwin->attrs.x + xwin->attrs.border_width; - damage.y = xwin->attrs.y + xwin->attrs.border_width; - damage.width = xwin->attrs.width; - damage.height = height; - region = XFixesCreateRegion(display, &damage, 1); - vwm_comp_damage_add(region); -} - - -/* this callback gets invoked at sample time for every process we've explicitly monitored (not autofollowed children/threads) - * It's where we update the cumulative data for all windows, including the graph masks, regardless of their visibility - * It's also where we compose the graphs and text for visible windows into a picture ready for compositing with the window contents */ -static void proc_sample_callback(vmon_t *vmon, vmon_proc_t *proc, vwm_xwindow_t *xwin) -{ - //VWM_TRACE("proc=%p xwin=%p", proc, xwin); - /* render the various always-updated overlays, this is the component we do regardless of the overlays mode and window visibility, - * essentially the incrementally rendered/historic components */ - maintain_overlay(xwin); - - /* render other non-historic things and compose the various layers into an updated overlay */ - /* this leaves everything ready to be composed with the window contents in paint_all() */ - /* paint_all() also enters compose_overlay() to update the overlays on windows which become mapped (desktop switches) */ - if (compositing_mode && vwm_xwin_is_mapped(xwin)) compose_overlay(xwin); -} - - -/* this callback gets invoked at sample time once "per sys" */ -static void sample_callback(vmon_t *_vmon) -{ - vmon_sys_stat_t *sys_stat = vmon.stores[VMON_STORE_SYS_STAT]; - this_total = sys_stat->user + sys_stat->nice + sys_stat->system + - sys_stat->idle + sys_stat->iowait + sys_stat->irq + - sys_stat->softirq + sys_stat->steal + sys_stat->guest; - - total_delta = this_total - last_total; - idle_delta = sys_stat->idle - last_idle; - iowait_delta = sys_stat->iowait - last_iowait; -} - - -/* these callbacks are invoked by the vmon library when process instances become monitored/unmonitored */ -static void vmon_ctor_cb(vmon_t *vmon, vmon_proc_t *proc) -{ - VWM_TRACE("proc->pid=%i", proc->pid); - proc->foo = calloc(1, sizeof(vwm_perproc_ctxt_t)); -} - - -static void vmon_dtor_cb(vmon_t *vmon, vmon_proc_t *proc) -{ - VWM_TRACE("proc->pid=%i", proc->pid); - if (proc->foo) { - free(proc->foo); - proc->foo = NULL; - } -} - - - /* Xinerama/multihead screen functions */ - -/* return what fraction (0.0-1.0) of vwin overlaps with scr */ -static float vwm_screen_overlaps_xwin(const vwm_screen_t *scr, vwm_xwindow_t *xwin) -{ - float pct = 0, xover = 0, yover = 0; - - if (scr->x_org + scr->width < xwin->attrs.x || scr->x_org > xwin->attrs.x + xwin->attrs.width || - scr->y_org + scr->height < xwin->attrs.y || scr->y_org > xwin->attrs.y + xwin->attrs.height) - goto _out; - - /* they overlap, by how much? */ - xover = MIN(scr->x_org + scr->width, xwin->attrs.x + xwin->attrs.width) - MAX(scr->x_org, xwin->attrs.x); - yover = MIN(scr->y_org + scr->height, xwin->attrs.y + xwin->attrs.height) - MAX(scr->y_org, xwin->attrs.y); - - pct = (xover * yover) / (xwin->attrs.width * xwin->attrs.height); -_out: - VWM_TRACE("xover=%f yover=%f width=%i height=%i pct=%.4f", xover, yover, xwin->attrs.width, xwin->attrs.height, pct); - return pct; -} - - -/* return the appropriate screen, don't use the return value across event loops because randr events reallocate the array. */ -typedef enum _vwm_screen_rel_t { - VWM_SCREEN_REL_XWIN, /* return the screen the supplied window most resides in */ - VWM_SCREEN_REL_POINTER, /* return the screen the pointer resides in */ - VWM_SCREEN_REL_TOTAL, /* return the bounding rectangle of all screens as one */ -} vwm_screen_rel_t; - -static const vwm_screen_t * vwm_screen_find(vwm_screen_rel_t rel, ...) -{ - static vwm_screen_t faux; - vwm_screen_t *scr, *best = &faux; /* default to faux as best */ - int i; - - faux.screen_number = 0; - faux.x_org = 0; - faux.y_org = 0; - faux.width = WidthOfScreen(DefaultScreenOfDisplay(display)); - faux.height = HeightOfScreen(DefaultScreenOfDisplay(display)); - - if (!xinerama_screens) goto _out; - -#define for_each_screen(_tmp) \ - for (i = 0, _tmp = xinerama_screens; i < xinerama_screens_cnt; _tmp = &xinerama_screens[++i]) - - switch (rel) { - case VWM_SCREEN_REL_XWIN: { - va_list ap; - vwm_xwindow_t *xwin; - float best_pct = 0, this_pct; - - va_start(ap, rel); - xwin = va_arg(ap, vwm_xwindow_t *); - va_end(ap); - - for_each_screen(scr) { - this_pct = vwm_screen_overlaps_xwin(scr, xwin); - if (this_pct > best_pct) { - best = scr; - best_pct = this_pct; - } - } - break; - } - - case VWM_SCREEN_REL_POINTER: { - int root_x, root_y, win_x, win_y; - unsigned int mask; - Window root, child; - - /* get the pointer coordinates and find which screen it's in */ - XQueryPointer(display, RootWindow(display, screen_num), &root, &child, &root_x, &root_y, &win_x, &win_y, &mask); - - for_each_screen(scr) { - if (root_x >= scr->x_org && root_x < scr->x_org + scr->width && - root_y >= scr->y_org && root_y < scr->y_org + scr->height) { - best = scr; - break; - } - } - break; - } - - case VWM_SCREEN_REL_TOTAL: { - short x1 = MAXSHORT, y1 = MAXSHORT, x2 = MINSHORT, y2 = MINSHORT; - /* find the smallest x_org and y_org, the highest x_org + width and y_org + height, those are the two corners of the total rect */ - for_each_screen(scr) { - if (scr->x_org < x1) x1 = scr->x_org; - if (scr->y_org < y1) y1 = scr->y_org; - if (scr->x_org + scr->width > x2) x2 = scr->x_org + scr->width; - if (scr->y_org + scr->height > y2) y2 = scr->y_org + scr->height; - } - faux.x_org = x1; - faux.y_org = y1; - faux.width = x2 - x1; - faux.height = y2 - y1; - best = &faux; - break; - } - } -_out: - VWM_TRACE("Found Screen #%i: %hix%hi @ %hi,%hi", best->screen_number, best->width, best->height, best->x_org, best->y_org); - - return best; -} - - -/* check if a screen contains any windows (assuming the current desktop) */ -static int vwm_screen_is_empty(const vwm_screen_t *scr) -{ - vwm_xwindow_t *xwin; - int is_empty = 1; - - list_for_each_entry(xwin, &xwindows, xwindows) { - if (!xwin->mapped) continue; - if (!xwin->managed || (xwin->managed->desktop == focused_desktop && !xwin->managed->shelved && !xwin->managed->configuring)) { - /* XXX: it may make more sense to see what %age of the screen is overlapped by windows, and consider it empty if < some % */ - /* This is just seeing if any window is predominantly within the specified screen, the rationale being if you had a focusable - * window on the screen you would have used the keyboard to make windows go there; this function is only used in determining - * wether a new window should go where the pointer is or not. */ - if (vwm_screen_overlaps_xwin(scr, xwin) >= 0.05) { - is_empty = 0; - break; - } - } - } - - return is_empty; -} - - - /* startup logo */ - -/* animated \/\/\ logo done with simple XOR'd lines, a display of the WM being started and ready */ -#define VWM_LOGO_POINTS 6 -static void vwm_draw_logo(void) -{ - int i; - unsigned int width, height, yoff, xoff; - XPoint points[VWM_LOGO_POINTS]; - const vwm_screen_t *scr = vwm_screen_find(VWM_SCREEN_REL_POINTER); - - XGrabServer(display); - - /* use the dimensions of the pointer-containing screen */ - width = scr->width; - height = scr->height; - xoff = scr->x_org; - yoff = scr->y_org + ((float)height * .333); - height /= 3; - - /* the logo gets shrunken vertically until it's essentially a flat line */ - while (height -= 2) { - /* scale and center the points to the screen size */ - for (i = 0; i < VWM_LOGO_POINTS; i++) { - points[i].x = xoff + (i * .2 * (float)width); - points[i].y = (i % 2 * (float)height) + yoff; - } - - XDrawLines(display, RootWindow(display, screen_num), gc, points, sizeof(points) / sizeof(XPoint), CoordModeOrigin); - XFlush(display); - usleep(3333); - XDrawLines(display, RootWindow(display, screen_num), gc, points, sizeof(points) / sizeof(XPoint), CoordModeOrigin); - XFlush(display); - - /* the width is shrunken as well, but only by as much as it is tall */ - yoff++; - width -= 4; - xoff += 2; - } - - XUngrabServer(display); -} - - - /* launching of external processes / X clients */ - -/* launch a child command specified in argv, mode decides if we wait for the child to exit before returning. */ -typedef enum _vwm_launch_mode_t { - VWM_LAUNCH_MODE_FG, - VWM_LAUNCH_MODE_BG, -} vwm_launch_mode_t; - -static void vwm_launch(char **argv, vwm_launch_mode_t mode) -{ - /* XXX: in BG mode I double fork and let init inherit the orphan so I don't have to collect the return status */ - if (mode == VWM_LAUNCH_MODE_FG || !fork()) { - if (!fork()) { - /* child */ - setpriority(PRIO_PROCESS, getpid(), priority + LAUNCHED_RELATIVE_PRIORITY); - execvp(argv[0], argv); - } - if (mode == VWM_LAUNCH_MODE_BG) exit(0); - } - wait(NULL); /* TODO: could wait for the specific pid, particularly in FG mode ... */ -} - - - /* desktop/shelf context handling */ - -/* switch to the desired context if it isn't already the focused one, inform caller if anything happened */ -static int vwm_context_focus(vwm_context_focus_t desired_context) -{ - vwm_context_focus_t entry_context = focused_context; - - switch (focused_context) { - vwm_xwindow_t *xwin; - vwm_window_t *vwin; - - case VWM_CONTEXT_FOCUS_SHELF: - if (desired_context == VWM_CONTEXT_FOCUS_SHELF) break; - - /* desired == DESKTOP && focused == SHELF */ - - VWM_TRACE("unmapping shelf window \"%s\"", focused_shelf->xwindow->name); - vwm_win_unmap(focused_shelf); - XFlush(display); /* for a more responsive feel */ - - /* map the focused desktop, from the top of the stack down */ - list_for_each_entry_prev(xwin, &xwindows, xwindows) { - if (!(vwin = xwin->managed)) continue; - if (vwin->desktop == focused_desktop && !vwin->shelved) { - VWM_TRACE("Mapping desktop window \"%s\"", xwin->name); - vwm_win_map(vwin); - } - } - - if (focused_desktop->focused_window) { - VWM_TRACE("Focusing \"%s\"", focused_desktop->focused_window->xwindow->name); - XSetInputFocus(display, focused_desktop->focused_window->xwindow->id, RevertToPointerRoot, CurrentTime); - } - - focused_context = VWM_CONTEXT_FOCUS_DESKTOP; - break; - - case VWM_CONTEXT_FOCUS_DESKTOP: - /* unmap everything, map the shelf */ - if (desired_context == VWM_CONTEXT_FOCUS_DESKTOP) break; - - /* desired == SHELF && focused == DESKTOP */ - - /* there should be a focused shelf if the shelf contains any windows, we NOOP the switch if the shelf is empty. */ - if (focused_shelf) { - /* unmap everything on the current desktop */ - list_for_each_entry(xwin, &xwindows, xwindows) { - if (!(vwin = xwin->managed)) continue; - if (vwin->desktop == focused_desktop) { - VWM_TRACE("Unmapping desktop window \"%s\"", xwin->name); - vwm_win_unmap(vwin); - } - } - - XFlush(display); /* for a more responsive feel */ - - VWM_TRACE("Mapping shelf window \"%s\"", focused_shelf->xwindow->name); - vwm_win_map(focused_shelf); - vwm_win_focus(focused_shelf); - - focused_context = VWM_CONTEXT_FOCUS_SHELF; - } - break; - - default: - VWM_BUG("unexpected focused context %x", focused_context); - break; - } - - /* return if the context has been changed, the caller may need to branch differently if nothing happened */ - return (focused_context != entry_context); -} - - - /* virtual desktops */ - -/* make the specified desktop the most recently used one */ -static void vwm_desktop_mru(vwm_desktop_t *desktop) -{ - VWM_TRACE("MRU desktop: %p", desktop); - list_move(&desktop->desktops_mru, &desktops_mru); -} - - -/* focus a virtual desktop */ -/* this switches to the desktop context if necessary, maps and unmaps windows accordingly if necessary */ -static int vwm_desktop_focus(vwm_desktop_t *desktop) -{ - XGrabServer(display); - XSync(display, False); - - /* if the context switched and the focused desktop is the desired desktop there's nothing else to do */ - if ((vwm_context_focus(VWM_CONTEXT_FOCUS_DESKTOP) && focused_desktop != desktop) || focused_desktop != desktop) { - vwm_xwindow_t *xwin; - vwm_window_t *vwin; - - /* unmap the windows on the currently focused desktop, map those on the newly focused one */ - list_for_each_entry(xwin, &xwindows, xwindows) { - if (!(vwin = xwin->managed) || vwin->shelved) continue; - if (vwin->desktop == focused_desktop) vwm_win_unmap(vwin); - } - - XFlush(display); - - list_for_each_entry_prev(xwin, &xwindows, xwindows) { - if (!(vwin = xwin->managed) || vwin->shelved) continue; - if (vwin->desktop == desktop) vwm_win_map(vwin); - } - - focused_desktop = desktop; - } - - /* directly focus the desktop's focused window if there is one, we don't use vwm_win_focus() intentionally XXX */ - if (focused_desktop->focused_window) { - VWM_TRACE("Focusing \"%s\"", focused_desktop->focused_window->xwindow->name); - XSetInputFocus(display, focused_desktop->focused_window->xwindow->id, RevertToPointerRoot, CurrentTime); - } - - XUngrabServer(display); - - return 1; -} - - -/* create a virtual desktop */ -static vwm_desktop_t * vwm_desktop_create(char *name) -{ - vwm_desktop_t *desktop; - - desktop = malloc(sizeof(vwm_desktop_t)); - if (desktop == NULL) { - VWM_PERROR("Failed to allocate desktop"); - goto _fail; - } - - desktop->name = name == NULL ? name : strdup(name); - desktop->focused_window = NULL; - - list_add_tail(&desktop->desktops, &desktops); - list_add_tail(&desktop->desktops_mru, &desktops_mru); - - return desktop; - -_fail: - return NULL; -} - - -/* destroy a virtual desktop */ -static void vwm_desktop_destroy(vwm_desktop_t *desktop) -{ - /* silently refuse to destroy a desktop having windows (for now) */ - /* there's _always_ a focused window on a desktop having mapped windows */ - /* also silently refuse to destroy the last desktop (for now) */ - if (desktop->focused_window || (desktop->desktops.next == desktop->desktops.prev)) return; - - /* focus the MRU desktop that isn't this one if we're the focused desktop */ - if (desktop == focused_desktop) { - vwm_desktop_t *next_desktop; - - list_for_each_entry(next_desktop, &desktops_mru, desktops_mru) { - if (next_desktop != desktop) { - vwm_desktop_focus(next_desktop); - break; - } - } - } - - list_del(&desktop->desktops); - list_del(&desktop->desktops_mru); -} - - - /* bare X windows stuff, there's a distinction between bare xwindows and the vwm managed windows */ - -/* send a client message to a window (currently used for WM_DELETE) */ -static void vwm_xwin_message(vwm_xwindow_t *xwin, Atom type, long foo) -{ - XEvent event; - - memset(&event, 0, sizeof(event)); - event.xclient.type = ClientMessage; - event.xclient.window = xwin->id; - event.xclient.message_type = type; - event.xclient.format = 32; - event.xclient.data.l[0] = foo; - event.xclient.data.l[1] = CurrentTime; /* XXX TODO: is CurrentTime actually correct to use for this purpose? */ - - XSendEvent(display, xwin->id, False, 0, &event); -} - - -/* look up the X window in the global xwindows list (includes unmanaged windows like override_redirect/popup menus) */ -static vwm_xwindow_t * vwm_xwin_lookup(Window win) -{ - vwm_xwindow_t *tmp, *xwin = NULL; - - list_for_each_entry(tmp, &xwindows, xwindows) { - if (tmp->id == win) { - xwin = tmp; - break; - } - } - - return xwin; -} - - -/* determine if a window is mapped (vwm-mapped) according to the current context */ -static inline int vwm_xwin_is_mapped(vwm_xwindow_t *xwin) -{ - int ret = 0; - - if (!xwin->mapped) return 0; - - if (xwin->managed) { - switch (focused_context) { - case VWM_CONTEXT_FOCUS_SHELF: - if (focused_shelf == xwin->managed) ret = xwin->mapped; - break; - - case VWM_CONTEXT_FOCUS_DESKTOP: - if (focused_desktop == xwin->managed->desktop && !xwin->managed->shelved) ret = xwin->mapped; - break; - - default: - VWM_BUG("Unsupported context"); - break; - } - } else { /* unmanaged xwins like popup dialogs when mapped are always visible */ - ret = 1; - } - - /* annoyingly, Xorg stops delivering VisibilityNotify events for redirected windows, so we don't conveniently know if a window is obscured or not :( */ - /* I could maintain my own data structure for answering this question, but that's pretty annoying when Xorg already has that knowledge. */ - - return ret; -} - - -/* bind the window to a "namewindowpixmap" and create a picture from it (compositing) */ -void vwm_xwin_bind_namewindow(vwm_xwindow_t *xwin) -{ - xwin->pixmap = XCompositeNameWindowPixmap(display, xwin->id); - xwin->picture = XRenderCreatePicture(display, xwin->pixmap, - XRenderFindVisualFormat(display, xwin->attrs.visual), - CPSubwindowMode, &pa_inferiors); - XFreePixmap(display, xwin->pixmap); -} - - -/* free the window's picture for accessing its redirected contents (compositing) */ -void vwm_xwin_unbind_namewindow(vwm_xwindow_t *xwin) -{ - XRenderFreePicture(display, xwin->picture); -} - - -/* install a monitor on the window if it doesn't already have one and has _NET_WM_PID set */ -static void vwm_xwin_monitor(vwm_xwindow_t *xwin) -{ - Atom type; - int fmt; - unsigned long nitems; - unsigned long nbytes; - long *foo = NULL; - int pid = -1; - - if (xwin->monitor) return; - - if (XGetWindowProperty(display, xwin->id, wm_pid_atom, 0, 1, False, XA_CARDINAL, - &type, &fmt, &nitems, &nbytes, (unsigned char **)&foo) != Success || !foo) return; - - pid = *foo; - XFree(foo); - - /* add the client process to the monitoring heirarchy */ - /* XXX note libvmon here maintains a unique callback for each unique callback+xwin pair, so multi-window processes work */ - xwin->monitor = vmon_proc_monitor(&vmon, NULL, pid, VMON_WANT_PROC_INHERIT, (void (*)(vmon_t *, vmon_proc_t *, void *))proc_sample_callback, xwin); - /* FIXME: count_rows() isn't returning the right count sometimes (off by ~1), it seems to be related to racing with the automatic child monitoring */ - /* the result is an extra row sometimes appearing below the process heirarchy */ - xwin->overlay.heirarchy_end = 1 + count_rows(xwin->monitor); - xwin->overlay.snowflakes_cnt = 0; -} - - -/* creates and potentially manages a new window (called in response to CreateNotify events, and during startup for all existing windows) */ -/* if the window is already mapped and not an override_redirect window, it becomes managed here. */ -typedef enum _vwm_grab_mode_t { - VWM_NOT_GRABBED = 0, - VWM_GRABBED -} vwm_grab_mode_t; - -static vwm_xwindow_t * vwm_xwin_create(Window win, vwm_grab_mode_t grabbed) -{ - XWindowAttributes attrs; - vwm_xwindow_t *xwin = NULL; - - VWM_TRACE("creating %#x", (unsigned int)win); - - /* prevent races */ - if (!grabbed) { - XGrabServer(display); - XSync(display, False); - } - - /* verify the window still exists */ - if (!XGetWindowAttributes(display, win, &attrs)) goto _out_grabbed; - - /* don't create InputOnly windows */ - if (attrs.class == InputOnly) goto _out_grabbed; - - if (!(xwin = (vwm_xwindow_t *)malloc(sizeof(vwm_xwindow_t)))) { - VWM_PERROR("Failed to allocate xwin"); - goto _out_grabbed; - } - - xwin->id = win; - xwin->attrs = attrs; - xwin->managed = NULL; - xwin->name = NULL; - XFetchName(display, win, &xwin->name); - - xwin->monitor = NULL; - xwin->overlay.width = xwin->overlay.height = xwin->overlay.phase = 0; - xwin->overlay.gen_last_composed = -1; - - /* This is so we get the PropertyNotify event and can get the pid when it's set post-create, - * with my _NET_WM_PID patch the property is immediately available */ - XSelectInput(display, win, PropertyChangeMask); - - vwm_xwin_monitor(xwin); - - /* we must track the mapped-by-client state of the window independent of managed vs. unmanaged because - * in the case of override_redirect windows they may be unmapped (invisible) or mapped (visible) like menus without being managed. - * otherwise we could just use !xwin.managed to indicate unmapped, which is more vwm2-like, but insufficient when compositing. */ - xwin->mapped = (attrs.map_state != IsUnmapped); - - if (compositing_mode) { - vwm_xwin_bind_namewindow(xwin); - xwin->damage = XDamageCreate(display, xwin->id, XDamageReportNonEmpty); - } - - list_add_tail(&xwin->xwindows, &xwindows); /* created windows are always placed on the top of the stacking order */ - -#ifdef HONOR_OVERRIDE_REDIRECT - if (!attrs.override_redirect && xwin->mapped) vwm_win_manage_xwin(xwin); -#else - if (xwin->mapped) vwm_win_manage_xwin(xwin); -#endif -_out_grabbed: - if (!grabbed) XUngrabServer(display); - - return xwin; -} - - -/* destroy a window, called in response to DestroyNotify events */ -/* if the window is also managed it will be unmanaged first */ -static void vwm_xwin_destroy(vwm_xwindow_t *xwin) -{ - XGrabServer(display); - XSync(display, False); - - if (xwin->managed) vwm_win_unmanage(xwin->managed); - - list_del(&xwin->xwindows); - - if (xwin->monitor) vmon_proc_unmonitor(&vmon, xwin->monitor, (void (*)(vmon_t *, vmon_proc_t *, void *))proc_sample_callback, xwin); - if (xwin->name) XFree(xwin->name); - - if (compositing_mode) { - vwm_xwin_unbind_namewindow(xwin); - XDamageDestroy(display, xwin->damage); - } - free(xwin); - - XUngrabServer(display); -} - - -/* maintain the stack-ordered xwindows list, when new_above is != None xwin is to be placed above new_above, when == None xwin goes to the bottom. */ -void vwm_xwin_restack(vwm_xwindow_t *xwin, Window new_above) -{ - Window old_above; -#ifdef TRACE - vwm_xwindow_t *tmp; - fprintf(stderr, "restack of %#x new_above=%#x\n", (unsigned int)xwin->id, (unsigned int)new_above); - fprintf(stderr, "restack pre:"); - list_for_each_entry(tmp, &xwindows, xwindows) { - fprintf(stderr, " %#x", (unsigned int)tmp->id); - } - fprintf(stderr, "\n"); -#endif - if (xwin->xwindows.prev != &xwindows) { - old_above = list_entry(xwin->xwindows.prev, vwm_xwindow_t, xwindows)->id; - } else { - old_above = None; - } - - if (old_above != new_above) { - vwm_xwindow_t *new; - - if (new_above == None) { /* to the bottom of the stack, so just above the &xwindows head */ - list_move(&xwin->xwindows, &xwindows); - } else if ((new = vwm_xwin_lookup(new_above))) { /* to just above new_above */ - list_move(&xwin->xwindows, &new->xwindows); - } - } -#ifdef TRACE - fprintf(stderr, "restack post:"); - list_for_each_entry(tmp, &xwindows, xwindows) { - fprintf(stderr, " %#x", (unsigned int)tmp->id); - } - fprintf(stderr, "\n\n"); -#endif -} - - - /* vwm "managed" windows (vwm_window_t) (which are built upon the "core" X windows (vwm_xwindow_t)) */ - -/* unmap the specified window and set the unmapping-in-progress flag so we can discard vwm-generated UnmapNotify events */ -static void vwm_win_unmap(vwm_window_t *vwin) -{ - if (!vwin->xwindow->mapped) { - VWM_TRACE("inhibited unmap of \"%s\", not mapped by client", vwin->xwindow->name); - return; - } - VWM_TRACE("Unmapping \"%s\"", vwin->xwindow->name); - vwin->unmapping = 1; - XUnmapWindow(display, vwin->xwindow->id); -} - - -/* map the specified window and set the mapping-in-progress flag so we can discard vwm-generated MapNotify events */ -static void vwm_win_map(vwm_window_t *vwin) -{ - if (!vwin->xwindow->mapped) { - VWM_TRACE("inhibited map of \"%s\", not mapped by client", vwin->xwindow->name); - return; - } - VWM_TRACE("Mapping \"%s\"", vwin->xwindow->name); - vwin->mapping = 1; - XMapWindow(display, vwin->xwindow->id); -} - - -/* make the specified window the most recently used one */ -static void vwm_win_mru(vwm_window_t *vwin) -{ - list_move(&vwin->windows_mru, &windows_mru); -} - - -/* look up the X window in the global managed windows list */ -static vwm_window_t * vwm_win_lookup(Window win) -{ - vwm_window_t *tmp, *vwin = NULL; - - list_for_each_entry(tmp, &windows_mru, windows_mru) { - if (tmp->xwindow->id == win) { - vwin = tmp; - break; - } - } - - return vwin; -} - - -/* return the currently focused window (considers current context...), may return NULL */ -static vwm_window_t * vwm_win_focused(void) -{ - vwm_window_t *vwin = NULL; - - switch (focused_context) { - case VWM_CONTEXT_FOCUS_SHELF: - vwin = focused_shelf; - break; - - case VWM_CONTEXT_FOCUS_DESKTOP: - if (focused_desktop) vwin = focused_desktop->focused_window; - break; - - default: - VWM_BUG("Unsupported context"); - break; - } - - return vwin; -} - - -/* "autoconfigure" windows (configuration shortcuts like fullscreen/halfscreen/quarterscreen) and restoring the window */ -typedef enum _vwm_win_autoconf_t { - VWM_WIN_AUTOCONF_NONE, /* un-autoconfigured window (used to restore the configuration) */ - VWM_WIN_AUTOCONF_QUARTER, /* quarter-screened */ - VWM_WIN_AUTOCONF_HALF, /* half-screened */ - VWM_WIN_AUTOCONF_FULL, /* full-screened */ - VWM_WIN_AUTOCONF_ALL /* all-screened (borderless) */ -} vwm_win_autoconf_t; - -typedef enum _vwm_side_t { - VWM_SIDE_TOP, - VWM_SIDE_BOTTOM, - VWM_SIDE_LEFT, - VWM_SIDE_RIGHT -} vwm_side_t; - -typedef enum _vwm_corner_t { - VWM_CORNER_TOP_LEFT, - VWM_CORNER_TOP_RIGHT, - VWM_CORNER_BOTTOM_RIGHT, - VWM_CORNER_BOTTOM_LEFT -} vwm_corner_t; - -static void vwm_win_autoconf(vwm_window_t *vwin, vwm_screen_rel_t rel, vwm_win_autoconf_t conf, ...) -{ - const vwm_screen_t *scr; - va_list ap; - XWindowChanges changes = { .border_width = WINDOW_BORDER_WIDTH }; - - /* remember the current configuration as the "client" configuration if it's not an autoconfigured one. */ - if (vwin->autoconfigured == VWM_WIN_AUTOCONF_NONE) vwin->client = vwin->xwindow->attrs; - - scr = vwm_screen_find(rel, vwin->xwindow); /* XXX FIXME: this becomes a bug when vwm_screen_find() uses non-xwin va_args */ - va_start(ap, conf); - switch (conf) { - case VWM_WIN_AUTOCONF_QUARTER: { - vwm_corner_t corner = va_arg(ap, vwm_corner_t); - changes.width = scr->width / 2 - (WINDOW_BORDER_WIDTH * 2); - changes.height = scr->height / 2 - (WINDOW_BORDER_WIDTH * 2); - switch (corner) { - case VWM_CORNER_TOP_LEFT: - changes.x = scr->x_org; - changes.y = scr->y_org; - break; - - case VWM_CORNER_TOP_RIGHT: - changes.x = scr->x_org + scr->width / 2; - changes.y = scr->y_org; - break; - - case VWM_CORNER_BOTTOM_RIGHT: - changes.x = scr->x_org + scr->width / 2; - changes.y = scr->y_org + scr->height / 2; - break; - - case VWM_CORNER_BOTTOM_LEFT: - changes.x = scr->x_org; - changes.y = scr->y_org + scr->height / 2; - break; - } - break; - } - - case VWM_WIN_AUTOCONF_HALF: { - vwm_side_t side = va_arg(ap, vwm_side_t); - switch (side) { - case VWM_SIDE_TOP: - changes.width = scr->width - (WINDOW_BORDER_WIDTH * 2); - changes.height = scr->height / 2 - (WINDOW_BORDER_WIDTH * 2); - changes.x = scr->x_org; - changes.y = scr->y_org; - break; - - case VWM_SIDE_BOTTOM: - changes.width = scr->width - (WINDOW_BORDER_WIDTH * 2); - changes.height = scr->height / 2 - (WINDOW_BORDER_WIDTH * 2); - changes.x = scr->x_org; - changes.y = scr->y_org + scr->height / 2; - break; - - case VWM_SIDE_LEFT: - changes.width = scr->width / 2 - (WINDOW_BORDER_WIDTH * 2); - changes.height = scr->height - (WINDOW_BORDER_WIDTH * 2); - changes.x = scr->x_org; - changes.y = scr->y_org; - break; - - case VWM_SIDE_RIGHT: - changes.width = scr->width / 2 - (WINDOW_BORDER_WIDTH * 2); - changes.height = scr->height - (WINDOW_BORDER_WIDTH * 2); - changes.x = scr->x_org + scr->width / 2; - changes.y = scr->y_org; - break; - } - break; - } - - case VWM_WIN_AUTOCONF_FULL: - changes.width = scr->width - WINDOW_BORDER_WIDTH * 2; - changes.height = scr->height - WINDOW_BORDER_WIDTH * 2; - changes.x = scr->x_org; - changes.y = scr->y_org; - break; - - case VWM_WIN_AUTOCONF_ALL: - changes.width = scr->width; - changes.height = scr->height; - changes.x = scr->x_org; - changes.y = scr->y_org; - changes.border_width = 0; - break; - - case VWM_WIN_AUTOCONF_NONE: /* restore window if autoconfigured */ - changes.width = vwin->client.width; - changes.height = vwin->client.height; - changes.x = vwin->client.x; - changes.y = vwin->client.y; - break; - } - va_end(ap); - - XConfigureWindow(display, vwin->xwindow->id, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &changes); - vwin->autoconfigured = conf; -} - - -/* focus a window */ -/* this updates window border color as needed and the X input focus if mapped */ -static void vwm_win_focus(vwm_window_t *vwin) -{ - VWM_TRACE("focusing: %#x", (unsigned int)vwin->xwindow->id); - - if (vwm_xwin_is_mapped(vwin->xwindow)) { - /* if vwin is mapped give it the input focus */ - XSetInputFocus(display, vwin->xwindow->id, RevertToPointerRoot, CurrentTime); - } - - /* update the border color accordingly */ - if (vwin->shelved) { - /* set the border of the newly focused window to the shelved color */ - XSetWindowBorder(display, vwin->xwindow->id, vwin == console ? shelved_console_border_color.pixel : shelved_window_border_color.pixel); - /* fullscreen windows in the shelf when focused, since we don't intend to overlap there */ - vwm_win_autoconf(vwin, VWM_SCREEN_REL_POINTER, VWM_WIN_AUTOCONF_FULL); /* XXX TODO: for now the shelf follows the pointer, it's simple. */ - } else { - if (vwin->desktop->focused_window) { - /* set the border of the previously focused window on the same desktop to the unfocused color */ - XSetWindowBorder(display, vwin->desktop->focused_window->xwindow->id, unfocused_window_border_color.pixel); - } - - /* set the border of the newly focused window to the focused color */ - XSetWindowBorder(display, vwin->xwindow->id, focused_window_border_color.pixel); - - /* persist this on a per-desktop basis so it can be restored on desktop switches */ - vwin->desktop->focused_window = vwin; - } -} - - -/* focus the next window on a virtual desktop relative to the supplied window, in the specified context, respecting screen boundaries according to fence. */ -typedef enum _vwm_fence_t { - VWM_FENCE_IGNORE = 0, /* behave as if screen boundaries don't exist (like the pre-Xinerama code) */ - VWM_FENCE_RESPECT, /* confine operation to within the screen */ - VWM_FENCE_TRY_RESPECT, /* confine operation to within the screen, unless no options exist. */ - VWM_FENCE_VIOLATE, /* leave the screen for any other */ - VWM_FENCE_MASKED_VIOLATE /* leave the screen for any other not masked */ -} vwm_fence_t; - -static vwm_window_t * vwm_win_focus_next(vwm_window_t *vwin, vwm_fence_t fence) -{ - const vwm_screen_t *scr = vwm_screen_find(VWM_SCREEN_REL_XWIN, vwin->xwindow), *next_scr = NULL; - vwm_window_t *next; - unsigned long visited_mask; - -_retry: - visited_mask = 0; - list_for_each_entry(next, &vwin->windows_mru, windows_mru) { - /* searching for the next mapped window in this context, using vwin->windows as the head */ - if (&next->windows_mru == &windows_mru) continue; /* XXX: skip the containerless head, we're leveraging the circular list implementation */ - - if ((vwin->shelved && next->shelved) || - ((!vwin->shelved && !next->shelved && next->desktop == vwin->desktop) && - (fence == VWM_FENCE_IGNORE || - ((fence == VWM_FENCE_RESPECT || fence == VWM_FENCE_TRY_RESPECT) && vwm_screen_find(VWM_SCREEN_REL_XWIN, next->xwindow) == scr) || - (fence == VWM_FENCE_VIOLATE && vwm_screen_find(VWM_SCREEN_REL_XWIN, next->xwindow) != scr) || - (fence == VWM_FENCE_MASKED_VIOLATE && (next_scr = vwm_screen_find(VWM_SCREEN_REL_XWIN, next->xwindow)) != scr && - !((1UL << next_scr->screen_number) & fence_mask)) - ))) break; - - if (fence == VWM_FENCE_MASKED_VIOLATE && next_scr && next_scr != scr) visited_mask |= (1UL << next_scr->screen_number); - } - - if (fence == VWM_FENCE_TRY_RESPECT && next == vwin) { - /* if we tried to respect the fence and failed to find a next, fallback to ignoring the fence and try again */ - fence = VWM_FENCE_IGNORE; - goto _retry; - } else if (fence == VWM_FENCE_MASKED_VIOLATE && next_scr) { - /* if we did a masked violate update the mask with the potentially new screen number */ - if (next == vwin && visited_mask) { - /* if we failed to find a next window on a different screen but had candidates we've exhausted screens and need to reset the mask then retry */ - VWM_TRACE("all candidate screens masked @ 0x%lx, resetting mask", fence_mask); - fence_mask = 0; - goto _retry; - } - fence_mask |= (1UL << next_scr->screen_number); - VWM_TRACE("VWM_FENCE_MASKED_VIOLATE fence_mask now: 0x%lx\n", fence_mask); - } - - if (vwin->shelved) { - if (next != focused_shelf) { - /* shelf switch, unmap the focused shelf and take it over */ - /* TODO FIXME: this makes assumptions about the shelf being focused calling unmap/map directly.. */ - vwm_win_unmap(focused_shelf); - - XFlush(display); - - vwm_win_map(next); - focused_shelf = next; - vwm_win_focus(next); - } - } else { - if (next != next->desktop->focused_window) { - /* focus the changed window */ - vwm_win_focus(next); - XRaiseWindow(display, next->xwindow->id); - } - } - - VWM_TRACE("vwin=%p xwin=%p name=\"%s\"", next, next->xwindow, next->xwindow->name); - - return next; -} - - -/* shelves a window, if the window is focused we focus the next one (if possible) */ -static void vwm_win_shelve(vwm_window_t *vwin) -{ - /* already shelved, NOOP */ - if (vwin->shelved) return; - - /* shelving focused window, focus the next window */ - if (vwin == vwin->desktop->focused_window) { - vwm_win_mru(vwm_win_focus_next(vwin, VWM_FENCE_RESPECT)); - } - - if (vwin == vwin->desktop->focused_window) { - /* TODO: we can probably put this into vwm_win_focus_next() and have it always handled there... */ - vwin->desktop->focused_window = NULL; - } - - vwin->shelved = 1; - vwm_win_mru(vwin); - - /* newly shelved windows always become the focused shelf */ - focused_shelf = vwin; - - vwm_win_unmap(vwin); -} - - -/* helper for (idempotently) unfocusing a window, deals with context switching etc... */ -static void vwm_win_unfocus(vwm_window_t *vwin) -{ - /* if we're the focused shelved window, cycle the focus to the next shelved window if possible, if there's no more shelf, switch to the desktop */ - /* TODO: there's probably some icky behaviors for focused windows unmapping/destroying in unfocused contexts, we probably jump contexts suddenly. */ - if (vwin == focused_shelf) { - VWM_TRACE("unfocusing focused shelf"); - vwm_win_focus_next(vwin, VWM_FENCE_IGNORE); - - if (vwin == focused_shelf) { - VWM_TRACE("shelf empty, leaving"); - /* no other shelved windows, exit the shelf context */ - vwm_context_focus(VWM_CONTEXT_FOCUS_DESKTOP); - focused_shelf = NULL; - } - } - - /* if we're the focused window cycle the focus to the next window on the desktop if possible */ - if (vwin->desktop->focused_window == vwin) { - VWM_TRACE("unfocusing focused window"); - vwm_win_focus_next(vwin, VWM_FENCE_TRY_RESPECT); - } - - if (vwin->desktop->focused_window == vwin) { - VWM_TRACE("desktop empty"); - vwin->desktop->focused_window = NULL; - } -} - - -/* demote an managed window to an unmanaged one */ -static vwm_xwindow_t * vwm_win_unmanage(vwm_window_t *vwin) -{ - vwm_win_mru(vwin); /* bump vwin to the mru head before unfocusing so we always move focus to the current head on unmanage of the focused window */ - vwm_win_unfocus(vwin); - list_del(&vwin->windows_mru); - - if (vwin == console) console = NULL; - if (vwin == focused_origin) focused_origin = NULL; - - vwin->xwindow->managed = NULL; - - return vwin->xwindow; -} - - -/* promote an unmanaged window to a managed one */ -static vwm_window_t * vwm_win_manage_xwin(vwm_xwindow_t *xwin) -{ - vwm_window_t *focused, *vwin = NULL; - - if (xwin->managed) { - VWM_TRACE("suppressed re-management of xwin=%p", xwin); - goto _fail; - } - - if (!(vwin = (vwm_window_t *)malloc(sizeof(vwm_window_t)))) { - VWM_PERROR("Failed to allocate vwin"); - goto _fail; - } - - XUngrabButton(display, AnyButton, AnyModifier, xwin->id); - XGrabButton(display, AnyButton, WM_GRAB_MODIFIER, xwin->id, False, (PointerMotionMask | ButtonPressMask | ButtonReleaseMask), GrabModeAsync, GrabModeAsync, None, None); - XGrabKey(display, AnyKey, WM_GRAB_MODIFIER, xwin->id, False, GrabModeAsync, GrabModeAsync); - XSetWindowBorder(display, xwin->id, unfocused_window_border_color.pixel); - - vwin->hints = XAllocSizeHints(); - if (!vwin->hints) { - VWM_PERROR("Failed to allocate WM hints"); - goto _fail; - } - XGetWMNormalHints(display, xwin->id, vwin->hints, &vwin->hints_supplied); - - xwin->managed = vwin; - vwin->xwindow = xwin; - - vwin->desktop = focused_desktop; - vwin->autoconfigured = VWM_WIN_AUTOCONF_NONE; - vwin->mapping = vwin->unmapping = vwin->configuring = 0; - vwin->shelved = (focused_context == VWM_CONTEXT_FOCUS_SHELF); /* if we're in the shelf when the window is created, the window is shelved */ - vwin->client = xwin->attrs; /* remember whatever the current attributes are */ - - VWM_TRACE("hints: flags=%lx x=%i y=%i w=%i h=%i minw=%i minh=%i maxw=%i maxh=%i winc=%i hinc=%i basew=%i baseh=%i grav=%x", - vwin->hints->flags, - vwin->hints->x, vwin->hints->y, - vwin->hints->width, vwin->hints->height, - vwin->hints->min_width, vwin->hints->min_height, - vwin->hints->max_width, vwin->hints->max_height, - vwin->hints->width_inc, vwin->hints->height_inc, - vwin->hints->base_width, vwin->hints->base_height, - vwin->hints->win_gravity); - - if ((vwin->hints_supplied & (USSize | PSize))) { - vwin->client.width = vwin->hints->base_width; - vwin->client.height = vwin->hints->base_height; - } - - /* put it on the global windows_mru list, if there's a focused window insert the new one after it */ - if (!list_empty(&windows_mru) && (focused = vwm_win_focused())) { - /* insert the vwin immediately after the focused window, so Mod1+Tab goes to the new window */ - list_add(&vwin->windows_mru, &focused->windows_mru); - } else { - list_add(&vwin->windows_mru, &windows_mru); - } - - /* always raise newly managed windows so we know about them. */ - XRaiseWindow(display, xwin->id); - - /* if the desktop has no focused window yet, automatically focus the newly managed one, provided we're on the desktop context */ - if (!focused_desktop->focused_window && focused_context == VWM_CONTEXT_FOCUS_DESKTOP) { - VWM_TRACE("Mapped new window \"%s\" is alone on desktop \"%s\", focusing", xwin->name, focused_desktop->name); - vwm_win_focus(vwin); - } - - return vwin; - -_fail: - if (vwin) { - if (vwin->hints) XFree(vwin->hints); - free(vwin); - } - return NULL; -} - - -/* migrate a window to a new desktop, focuses the destination desktop as well */ -static void vwm_win_migrate(vwm_window_t *vwin, vwm_desktop_t *desktop) -{ - vwm_win_unfocus(vwin); /* go through the motions of unfocusing the window if it is focused */ - vwin->shelved = 0; /* ensure not shelved */ - vwin->desktop = desktop; /* assign the new desktop */ - vwm_desktop_focus(desktop); /* currently we always focus the new desktop in a migrate */ - - vwm_win_focus(vwin); /* focus the window so borders get updated */ - vwm_win_mru(vwin); /* TODO: is this right? shouldn't the Mod1 release be what's responsible for this? I migrate so infrequently it probably doesn't matter */ - - XRaiseWindow(display, vwin->xwindow->id); /* ensure the window is raised */ -} - - - /* compositing manager stuff */ - -/* add damage to the global combined damage queue where we accumulate damage between calls to paint_all() */ -static void vwm_comp_damage_add(XserverRegion damage) -{ - if (combined_damage != None) { - XFixesUnionRegion(display, combined_damage, combined_damage, damage); - XFixesDestroyRegion(display, damage); - } else { - combined_damage = damage; - } -} - - -/* take what regions of the damaged window have been damaged, subtract them from the per-window damage object, and add them to the combined damage */ -static void vwm_comp_damage_event(XDamageNotifyEvent *ev) -{ - XserverRegion region; - vwm_xwindow_t *xwin; - - xwin = vwm_xwin_lookup(ev->drawable); - if (!xwin) { - VWM_ERROR("damaged unknown drawable %x", (unsigned int)ev->drawable); - return; - } - - region = XFixesCreateRegion(display, NULL, 0); - XDamageSubtract(display, xwin->damage, None, region); - XFixesTranslateRegion(display, region, xwin->attrs.x + xwin->attrs.border_width, xwin->attrs.y + xwin->attrs.border_width); - vwm_comp_damage_add(region); -} - - -/* helper to damage an entire window including the border */ -static void vwm_comp_damage_win(vwm_xwindow_t *xwin) -{ - XserverRegion region; - XRectangle rect = { xwin->attrs.x, - xwin->attrs.y, - xwin->attrs.width + xwin->attrs.border_width * 2, - xwin->attrs.height + xwin->attrs.border_width * 2 }; - region = XFixesCreateRegion(display, &rect, 1); - vwm_comp_damage_add(region); -} - - -/* throw away our double buffered root pictures so they get recreated on the next paint_all() */ -/* used in response to screen configuration changes... */ -static void vwm_comp_invalidate_root() -{ - if (root_picture) XRenderFreePicture(display, root_picture); - root_picture = None; - if (root_buffer) XRenderFreePicture(display, root_picture); - root_buffer = None; -} - - -/* consume combined_damage by iterating the xwindows list from the top down, drawing visible windows as encountered, subtracting their area from combined_damage */ -/* when compositing is active this is the sole function responsible for making things show up on the screen */ -static void vwm_comp_paint_all() -{ - vwm_xwindow_t *xwin; - XRenderColor bgcolor = {0x0000, 0x00, 0x00, 0xffff}; - Region occluded = XCreateRegion(); - static XserverRegion undamage_region = None; - - if (!undamage_region) undamage_region = XFixesCreateRegion(display, NULL, 0); - - /* (re)create the root picture from the root window and allocate a double buffer for the off-screen composition of the damaged contents */ - if (root_picture == None) { - Pixmap root_pixmap; - - XGetWindowAttributes(display, RootWindow(display, screen_num), &root_attrs); - root_picture = XRenderCreatePicture(display, RootWindow(display, screen_num), - XRenderFindVisualFormat(display, DefaultVisual(display, screen_num)), - CPSubwindowMode, &pa_inferiors); - root_pixmap = XCreatePixmap (display, RootWindow(display, screen_num), root_attrs.width, root_attrs.height, DefaultDepth (display, screen_num)); - root_buffer = XRenderCreatePicture (display, root_pixmap, XRenderFindVisualFormat (display, DefaultVisual (display, screen_num)), 0, 0); - XFreePixmap(display, root_pixmap); - } - - /* compose overlays for all visible windows up front in a separate pass (kind of lame, but it's simpler since compose_overlay() adds to combined_damage) */ - list_for_each_entry_prev(xwin, &xwindows, xwindows) { - XRectangle r; - - if (!vwm_xwin_is_mapped(xwin)) continue; /* if !mapped skip */ - - /* Everything mapped next goes through an occlusion check. - * Since the composite extension stops delivery of VisibilityNotify events for redirected windows, - * (it assumes redirected windows should be treated as part of a potentially transparent composite, and provides no api to alter this assumption) - * we can't simply select the VisibilityNotify events on all windows and cache their visibility state in vwm_xwindow_t then skip - * xwin->state==VisibilityFullyObscured windows here to avoid the cost of pointlessly composing overlays and rendering fully obscured windows :(. - * - * Instead we accumulate an occluded region (starting empty) of painted windows from the top-down on every paint_all(). - * Before we compose_overlay() a window, we check if the window's rectangle fits entirely within the occluded region. - * If it does, no compose_overlay() is performed. - * If it doesn't, compose_overlay() is called, and the window's rect is added to the occluded region. - * The occluded knowledge is also cached for the XRenderComposite() loop immediately following, where we skip the rendering of - * occluded windows as well. - * This does technically break SHAPE windows (xeyes, xmms), but only when monitoring is enabled which covers them with rectangular overlays anyways. - */ - r.x = xwin->attrs.x; - r.y = xwin->attrs.y; - r.width = xwin->attrs.width + xwin->attrs.border_width * 2; - r.height = xwin->attrs.height + xwin->attrs.border_width * 2; - if (XRectInRegion(occluded, r.x, r.y, r.width, r.height) != RectangleIn) { - /* the window isn't fully occluded, compose it and add it to occluded */ - if (xwin->monitor && !xwin->attrs.override_redirect) compose_overlay(xwin); - XUnionRectWithRegion(&r, occluded, occluded); - xwin->occluded = 0; - } else { - xwin->occluded = 1; - VWM_TRACE("window %#x occluded, skipping compose_overlay()", (int)xwin->id); - } - } - XDestroyRegion(occluded); - - /* start with the clip regions set to the damaged area accumulated since the previous paint_all() */ - XFixesSetPictureClipRegion(display, root_buffer, 0, 0, combined_damage); /* this is the double buffer where the in-flight screen contents are staged */ - XFixesSetPictureClipRegion(display, root_picture, 0, 0, combined_damage); /* this is the visible root window */ - - /* since translucent windows aren't supported in vwm, I can do this more efficiently */ - list_for_each_entry_prev(xwin, &xwindows, xwindows) { - XRectangle r; - - if (!vwm_xwin_is_mapped(xwin) || xwin->occluded) continue; /* if !mapped or occluded skip */ - - /* these coordinates + dimensions incorporate the border (since XCompositeNameWindowPixmap is being used) */ - r.x = xwin->attrs.x; - r.y = xwin->attrs.y; - r.width = xwin->attrs.width + xwin->attrs.border_width * 2; - r.height = xwin->attrs.height + xwin->attrs.border_width * 2; - - /* render the redirected window contents into root_buffer, note root_buffer has the remaining combined_damage set as the clip region */ - XRenderComposite(display, PictOpSrc, xwin->picture, None, root_buffer, - 0, 0, 0, 0, /* src x, y, mask x, y */ - r.x, r.y, /* dst x, y */ - r.width, r.height); - - if (xwin->monitor && !xwin->attrs.override_redirect && xwin->overlay.width) { - /* draw the monitoring overlay atop the window, note we stay within the window borders here. */ - XRenderComposite(display, PictOpOver, xwin->overlay.picture, None, root_buffer, - 0, 0, 0, 0, /* src x,y, maxk x, y */ - xwin->attrs.x + xwin->attrs.border_width, /* dst x */ - xwin->attrs.y + xwin->attrs.border_width, /* dst y */ - xwin->attrs.width, overlay_composed_height(xwin)); /* w, h */ - } - - /* subtract the region of the window from the combined damage and update the root_buffer clip region to reflect the remaining damage */ - XFixesSetRegion(display, undamage_region, &r, 1); - XFixesSubtractRegion(display, combined_damage, combined_damage, undamage_region); - XFixesSetPictureClipRegion(display, root_buffer, 0, 0, combined_damage); - } - - /* at this point all of the visible windows have been subtracted from the clip region, so paint any root window damage (draw background) */ - XRenderFillRectangle(display, PictOpSrc, root_buffer, &bgcolor, 0, 0, root_attrs.width, root_attrs.height); - - /* discard the root_buffer clip region and copy root_buffer to root_picture, root_picture still has the combined damage as its clip region */ - XFixesSetPictureClipRegion(display, root_buffer, 0, 0, None); - XRenderComposite(display, PictOpSrc, root_buffer, None, root_picture, 0, 0, 0, 0, 0, 0, root_attrs.width, root_attrs.height); - - /* fin */ - XFixesDestroyRegion(display, combined_damage); - combined_damage = None; -} - - -/* toggle compositing/monitoring overlays on/off */ -static void vwm_comp_toggle(void) -{ - vwm_xwindow_t *xwin; - - XGrabServer(display); - XSync(display, False); - - switch (compositing_mode) { - case VWM_COMPOSITING_OFF: - VWM_TRACE("enabling compositing"); - compositing_mode = VWM_COMPOSITING_MONITORS; - XCompositeRedirectSubwindows(display, RootWindow(display, screen_num), CompositeRedirectManual); - list_for_each_entry_prev(xwin, &xwindows, xwindows) { - vwm_xwin_bind_namewindow(xwin); - xwin->damage = XDamageCreate(display, xwin->id, XDamageReportNonEmpty); - } - /* damage everything */ - /* TODO: keep a list of rects reflecting all the current screens and create a region from that... */ - vwm_comp_damage_add(XFixesCreateRegionFromWindow(display, RootWindow(display, screen_num), WindowRegionBounding)); - break; - - case VWM_COMPOSITING_MONITORS: { - XEvent ev; - - VWM_TRACE("disabling compositing"); - compositing_mode = VWM_COMPOSITING_OFF; - list_for_each_entry_prev(xwin, &xwindows, xwindows) { - vwm_xwin_unbind_namewindow(xwin); - XDamageDestroy(display, xwin->damage); - } - XCompositeUnredirectSubwindows(display, RootWindow(display, screen_num), CompositeRedirectManual); - vwm_comp_invalidate_root(); - - /* if there's any damage queued up discard it so we don't enter paint_all() until compositing is reenabled again. */ - if (combined_damage) { - XFixesDestroyRegion(display, combined_damage); - combined_damage = None; - } - while (XCheckTypedEvent(display, damage_event + XDamageNotify, &ev) != False); - break; - } - } - - XUngrabServer(display); -} - - - /* input event handling stuff */ - -/* simple little state machine for managing mouse click/drag/release sequences so we don't need another event loop */ -typedef enum _vwm_adjust_mode_t { - VWM_ADJUST_RESIZE, - VWM_ADJUST_MOVE -} vwm_adjust_mode_t; - -typedef struct _vwm_clickety_t { - vwm_window_t *vwin; - vwm_adjust_mode_t mode; - XWindowAttributes orig, lastrect; - int impetus_x, impetus_y, impetus_x_root, impetus_y_root; -} vwm_clickety_t; - -/* helper function for resizing the window, how the motion is applied depends on where in the window the impetus event occurred */ -static void compute_resize(vwm_clickety_t *clickety, XEvent *terminus, XWindowAttributes *new) -{ - vwm_window_t *vwin; - int dw = (clickety->orig.width / 2); - int dh = (clickety->orig.height / 2); - int xdelta = (terminus->xbutton.x_root - clickety->impetus_x_root); - int ydelta = (terminus->xbutton.y_root - clickety->impetus_y_root); - int min_width = 0, min_height = 0; - int width_inc = 1, height_inc = 1; - - /* TODO: there's a problem here WRT border width, I should be considering it, I just haven't bothered to fix it since it doesn't seem to matter */ - if ((vwin = clickety->vwin) && vwin->hints) { - if ((vwin->hints_supplied & PMinSize)) { - min_width = vwin->hints->min_width; - min_height = vwin->hints->min_height; - VWM_TRACE("window size hints exist and minimum sizes are w=%i h=%i", min_width, min_height); - } - - if ((vwin->hints_supplied & PResizeInc)) { - width_inc = vwin->hints->width_inc; - height_inc = vwin->hints->height_inc; - VWM_TRACE("window size hints exist and resize increments are w=%i h=%i", width_inc, height_inc); - if (!width_inc) width_inc = 1; - if (!height_inc) height_inc = 1; - } - } - - xdelta = xdelta / width_inc * width_inc; - ydelta = ydelta / height_inc * height_inc; - - if (clickety->impetus_x < dw && clickety->impetus_y < dh) { - /* grabbed top left */ - new->x = clickety->orig.x + xdelta; - new->y = clickety->orig.y + ydelta; - new->width = clickety->orig.width - xdelta; - new->height = clickety->orig.height - ydelta; - } else if (clickety->impetus_x > dw && clickety->impetus_y < dh) { - /* grabbed top right */ - new->x = clickety->orig.x; - new->y = clickety->orig.y + ydelta; - new->width = clickety->orig.width + xdelta; - new->height = clickety->orig.height - ydelta; - } else if (clickety->impetus_x < dw && clickety->impetus_y > dh) { - /* grabbed bottom left */ - new->x = clickety->orig.x + xdelta; - new->y = clickety->orig.y; - new->width = clickety->orig.width - xdelta; - new->height = clickety->orig.height + ydelta; - } else if (clickety->impetus_x > dw && clickety->impetus_y > dh) { - /* grabbed bottom right */ - new->x = clickety->orig.x; - new->y = clickety->orig.y; - new->width = clickety->orig.width + xdelta; - new->height = clickety->orig.height + ydelta; - } - - /* constrain the width and height of the window according to the minimums */ - if (new->width < min_width) { - if (clickety->orig.x != new->x) new->x -= (min_width - new->width); - new->width = min_width; - } - - if (new->height < min_height) { - if (clickety->orig.y != new->y) new->y -= (min_height - new->height); - new->height = min_height; - } -} - - -static void vwm_clickety_motion(vwm_clickety_t *clickety, Window win, XMotionEvent *motion) -{ - XWindowChanges changes = { .border_width = WINDOW_BORDER_WIDTH }; - - if (!clickety->vwin) return; - - /* TODO: verify win matches clickety->vwin? */ - switch (clickety->mode) { - case VWM_ADJUST_MOVE: - changes.x = clickety->orig.x + (motion->x_root - clickety->impetus_x_root); - changes.y = clickety->orig.y + (motion->y_root - clickety->impetus_y_root); - XConfigureWindow(display, win, CWX | CWY | CWBorderWidth, &changes); - break; - - case VWM_ADJUST_RESIZE: { - XWindowAttributes resized; - - /* XXX: it just so happens the XMotionEvent structure is identical to XButtonEvent in the fields - * needed by compute_resize... */ - compute_resize(clickety, (XEvent *)motion, &resized); - /* TODO: this is probably broken with compositing active, but it doesn't seem to be too messed up in practice */ - /* erase the last rectangle */ - XDrawRectangle(display, RootWindow(display, screen_num), gc, clickety->lastrect.x, clickety->lastrect.y, clickety->lastrect.width, clickety->lastrect.height); - /* draw a frame @ resized coordinates */ - XDrawRectangle(display, RootWindow(display, screen_num), gc, resized.x, resized.y, resized.width, resized.height); - /* remember the last rectangle */ - clickety->lastrect = resized; - break; - } - - default: - break; - } -} - - -static void vwm_clickety_released(vwm_clickety_t *clickety, Window win, XButtonPressedEvent *terminus) -{ - XWindowChanges changes = { .border_width = WINDOW_BORDER_WIDTH }; - - if (!clickety->vwin) return; - - switch (clickety->mode) { - case VWM_ADJUST_MOVE: - changes.x = clickety->orig.x + (terminus->x_root - clickety->impetus_x_root); - changes.y = clickety->orig.y + (terminus->y_root - clickety->impetus_y_root); - XConfigureWindow(display, win, CWX | CWY | CWBorderWidth, &changes); - break; - - case VWM_ADJUST_RESIZE: { - XWindowAttributes resized; - compute_resize(clickety, (XEvent *)terminus, &resized); - /* move and resize the window @ resized */ - XDrawRectangle(display, RootWindow(display, screen_num), gc, clickety->lastrect.x, clickety->lastrect.y, clickety->lastrect.width, clickety->lastrect.height); - changes.x = resized.x; - changes.y = resized.y; - changes.width = resized.width; - changes.height = resized.height; - XConfigureWindow(display, win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &changes); - XUngrabServer(display); - break; - } - - default: - break; - } - /* once you manipulate the window it's no longer fullscreened, simply hitting Mod1+Return once will restore fullscreened mode */ - clickety->vwin->autoconfigured = VWM_WIN_AUTOCONF_NONE; - - clickety->vwin = NULL; /* reset clickety */ - - XFlush(display); - XUngrabPointer(display, CurrentTime); -} - - -/* on pointer buttonpress we initiate a clickety sequence; setup clickety with the window and impetus coordinates.. */ -static int vwm_clickety_pressed(vwm_clickety_t *clickety, Window win, XButtonPressedEvent *impetus) -{ - vwm_window_t *vwin; - - /* verify the window still exists */ - if (!XGetWindowAttributes(display, win, &clickety->orig)) goto _fail; - - if (!(vwin = vwm_win_lookup(win))) goto _fail; - - if (impetus->state & WM_GRAB_MODIFIER) { - - /* always set the input focus to the clicked window, note if we allow this to happen on the root window, it enters sloppy focus mode - * until a non-root window is clicked, which is an interesting hybrid but not how I prefer it. */ - if (vwin != focused_desktop->focused_window && vwin->xwindow->id != RootWindow(display, screen_num)) { - vwm_win_focus(vwin); - vwm_win_mru(vwin); - } - - switch (impetus->button) { - case Button1: - /* immediately raise the window if we're relocating, - * resizes are supported without raising (which also enables NULL resizes to focus without raising) */ - clickety->mode = VWM_ADJUST_MOVE; - XRaiseWindow(display, win); - break; - - case Button3: - /* grab the server on resize for the xor rubber-banding's sake */ - XGrabServer(display); - XSync(display, False); - - /* FIXME: none of the resize DrawRectangle() calls consider the window border. */ - XDrawRectangle(display, RootWindow(display, screen_num), gc, clickety->orig.x, clickety->orig.y, clickety->orig.width, clickety->orig.height); - clickety->lastrect = clickety->orig; - - clickety->mode = VWM_ADJUST_RESIZE; - break; - - default: - goto _fail; - } - clickety->vwin = vwin; - clickety->impetus_x_root = impetus->x_root; - clickety->impetus_y_root = impetus->y_root; - clickety->impetus_x = impetus->x; - clickety->impetus_y = impetus->y; - } - - return 1; - -_fail: - XUngrabPointer(display, CurrentTime); - - return 0; -} - -/* Poll the keyboard state to see if _any_ keys are pressed */ -static int vwm_keyspressed() { - int i; - char state[32]; - - XQueryKeymap(display, state); - - for (i = 0; i < sizeof(state); i++) { - if (state[i]) return 1; - } - - return 0; -} - -/* Called in response to KeyRelease events, for now only interesting for detecting when Mod1 is released termintaing - * window cycling for application of MRU on the focused window */ -static void vwm_keyreleased(Window win, XEvent *keyrelease) -{ - vwm_window_t *vwin; - KeySym sym; - - switch ((sym = XLookupKeysym(&keyrelease->xkey, 0))) { - case XK_Alt_R: - case XK_Alt_L: /* TODO: actually use the modifier mapping, for me XK_Alt_[LR] is Mod1. XGetModifierMapping()... */ - VWM_TRACE("XK_Alt_[LR] released"); - - /* aborted? try restore focused_origin */ - if (key_is_grabbed > 1 && focused_origin) { - VWM_TRACE("restoring %p on %p", focused_origin, focused_origin->desktop); - vwm_desktop_focus(focused_origin->desktop); - vwm_win_focus(focused_origin); - } - - /* make the focused window the most recently used */ - if ((vwin = vwm_win_focused())) vwm_win_mru(vwin); - - /* make the focused desktop the most recently used */ - if (focused_context == VWM_CONTEXT_FOCUS_DESKTOP && focused_desktop) vwm_desktop_mru(focused_desktop); - - break; - - default: - VWM_TRACE("Unhandled keycode: %x", (unsigned int)sym); - break; - } - - if (key_is_grabbed && !vwm_keyspressed()) { - XUngrabKeyboard(display, CurrentTime); - XFlush(display); - key_is_grabbed = 0; - fence_mask = 0; /* reset the fence mask on release for VWM_FENCE_MASKED_VIOLATE */ - } -} - - -/* Called in response to KeyPress events, I currenly only grab Mod1 keypress events */ -static void vwm_keypressed(Window win, XEvent *keypress) -{ - vwm_window_t *vwin; - KeySym sym; - static KeySym last_sym; - static typeof(keypress->xkey.state) last_state; - static int repeat_cnt = 0; - int do_grab = 0; - char *quit_console_args[] = {"/bin/sh", "-c", "screen -dr " CONSOLE_SESSION_STRING " -X quit", NULL}; - - sym = XLookupKeysym(&keypress->xkey, 0); - - /* detect repeaters, note repeaters do not span interrupted Mod1 sequences! */ - if (key_is_grabbed && sym == last_sym && keypress->xkey.state == last_state) { - repeat_cnt++; - } else { - repeat_cnt = 0; - } - - vwin = vwm_win_focused(); - - switch (sym) { - -#define launcher(_sym, _label, _argv)\ - case _sym: \ - { \ - char *args[] = {"/bin/sh", "-c", "screen -dr " CONSOLE_SESSION_STRING " -X screen /bin/sh -i -x -c \"" _argv " || sleep 86400\"", NULL};\ - vwm_launch(args, VWM_LAUNCH_MODE_BG);\ - break; \ - } -#include "launchers.def" -#undef launcher - case XK_Alt_L: /* transaction abort */ - case XK_Alt_R: - if (key_is_grabbed) key_is_grabbed++; - VWM_TRACE("aborting with origin %p", focused_origin); - break; - - case XK_grave: /* toggle shelf visibility */ - vwm_context_focus(VWM_CONTEXT_FOCUS_OTHER); - break; - - case XK_Tab: /* cycle focused window */ - do_grab = 1; /* update MRU window on commit (Mod1 release) */ - - /* focus the next window, note this doesn't affect MRU yet, that happens on Mod1 release */ - if (vwin) { - if (keypress->xkey.state & ShiftMask) { - vwm_win_focus_next(vwin, VWM_FENCE_MASKED_VIOLATE); - } else { - vwm_win_focus_next(vwin, VWM_FENCE_RESPECT); - } - } - break; - - case XK_space: { /* cycle focused desktop utilizing MRU */ - vwm_desktop_t *next_desktop = list_entry(focused_desktop->desktops_mru.next == &desktops_mru ? focused_desktop->desktops_mru.next->next : focused_desktop->desktops_mru.next, vwm_desktop_t, desktops_mru); /* XXX: note the sensitivity to the desktops_mru head here, we want to look past it. */ - - do_grab = 1; /* update MRU desktop on commit (Mod1 release) */ - - if (keypress->xkey.state & ShiftMask) { - /* migrate the focused window with the desktop focus to the most recently used desktop */ - if (vwin) vwm_win_migrate(vwin, next_desktop); - } else { - vwm_desktop_focus(next_desktop); - } - break; - } - - case XK_d: /* destroy focused */ - if (vwin) { - if (keypress->xkey.state & ShiftMask) { /* brutally destroy the focused window */ - XKillClient(display, vwin->xwindow->id); - } else { /* kindly destroy the focused window */ - vwm_xwin_message(vwin->xwindow, wm_protocols_atom, wm_delete_atom); - } - } else if (focused_context == VWM_CONTEXT_FOCUS_DESKTOP) { - /* destroy the focused desktop when destroy occurs without any windows */ - vwm_desktop_destroy(focused_desktop); - } - break; - - case XK_Escape: /* leave VWM rudely, after triple press */ - do_grab = 1; - - if (repeat_cnt == 2) { - vwm_launch(quit_console_args, VWM_LAUNCH_MODE_FG); - exit(42); - } - break; - - case XK_v: /* instantiate (and focus) a new (potentially empty, unless migrating) virtual desktop */ - do_grab = 1; /* update MRU desktop on commit (Mod1 release) */ - - if (keypress->xkey.state & ShiftMask) { - if (vwin) { - /* migrate the focused window to a newly created virtual desktop, focusing the new desktop simultaneously */ - vwm_win_migrate(vwin, vwm_desktop_create(NULL)); - } - } else { - vwm_desktop_focus(vwm_desktop_create(NULL)); - vwm_desktop_mru(focused_desktop); - } - break; - - case XK_h: /* previous virtual desktop, if we're in the shelf context this will simply switch to desktop context */ - do_grab = 1; /* update MRU desktop on commit (Mod1 release) */ - - if (keypress->xkey.state & ShiftMask) { - if (vwin && vwin->desktop->desktops.prev != &desktops) { - /* migrate the focused window with the desktop focus to the previous desktop */ - vwm_win_migrate(vwin, list_entry(vwin->desktop->desktops.prev, vwm_desktop_t, desktops)); - } - } else { - if (focused_context == VWM_CONTEXT_FOCUS_SHELF) { - /* focus the focused desktop instead of the shelf */ - vwm_context_focus(VWM_CONTEXT_FOCUS_DESKTOP); - } else if (focused_desktop->desktops.prev != &desktops) { - /* focus the previous desktop */ - vwm_desktop_focus(list_entry(focused_desktop->desktops.prev, vwm_desktop_t, desktops)); - } - } - break; - - case XK_l: /* next virtual desktop, if we're in the shelf context this will simply switch to desktop context */ - do_grab = 1; /* update MRU desktop on commit (Mod1 release) */ - - if (keypress->xkey.state & ShiftMask) { - if (vwin && vwin->desktop->desktops.next != &desktops) { - /* migrate the focused window with the desktop focus to the next desktop */ - vwm_win_migrate(vwin, list_entry(vwin->desktop->desktops.next, vwm_desktop_t, desktops)); - } - } else { - if (focused_context == VWM_CONTEXT_FOCUS_SHELF) { - /* focus the focused desktop instead of the shelf */ - vwm_context_focus(VWM_CONTEXT_FOCUS_DESKTOP); - } else if (focused_desktop->desktops.next != &desktops) { - /* focus the next desktop */ - vwm_desktop_focus(list_entry(focused_desktop->desktops.next, vwm_desktop_t, desktops)); - } - } - break; - - case XK_k: /* raise or shelve the focused window */ - if (vwin) { - if (keypress->xkey.state & ShiftMask) { /* shelf the window and focus the shelf */ - if (focused_context != VWM_CONTEXT_FOCUS_SHELF) { - /* shelve the focused window while focusing the shelf */ - vwm_win_shelve(vwin); - vwm_context_focus(VWM_CONTEXT_FOCUS_SHELF); - } - } else { - do_grab = 1; - - XRaiseWindow(display, vwin->xwindow->id); - - if (repeat_cnt == 1) { - /* double: reraise & fullscreen */ - vwm_win_autoconf(vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_FULL); - } else if (repeat_cnt == 2) { - /* triple: reraise & fullscreen w/borders obscured by screen perimiter */ - vwm_win_autoconf(vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_ALL); - } else if (xinerama_screens_cnt > 1) { - if (repeat_cnt == 3) { - /* triple: reraise & fullscreen across all screens */ - vwm_win_autoconf(vwin, VWM_SCREEN_REL_TOTAL, VWM_WIN_AUTOCONF_FULL); - } else if (repeat_cnt == 4) { - /* quadruple: reraise & fullscreen w/borders obscured by screen perimiter */ - vwm_win_autoconf(vwin, VWM_SCREEN_REL_TOTAL, VWM_WIN_AUTOCONF_ALL); - } - } - XFlush(display); - } - } - break; - - case XK_j: /* lower or unshelve the focused window */ - if (vwin) { - if (keypress->xkey.state & ShiftMask) { /* unshelf the window to the focused desktop, and focus the desktop */ - if (focused_context == VWM_CONTEXT_FOCUS_SHELF) { - /* unshelve the focused window, focus the desktop it went to */ - vwm_win_migrate(vwin, focused_desktop); - } - } else { - if (vwin->autoconfigured == VWM_WIN_AUTOCONF_ALL) { - vwm_win_autoconf(vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_FULL); - } else { - XLowerWindow(display, vwin->xwindow->id); - } - XFlush(display); - } - } - break; - - case XK_Return: /* (full-screen / restore) focused window */ - if (vwin) { - if (vwin->autoconfigured) { - vwm_win_autoconf(vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_NONE); - } else { - vwm_win_autoconf(vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_FULL); - } - } - break; - - case XK_s: /* shelve focused window */ - if (vwin && !vwin->shelved) vwm_win_shelve(vwin); - break; - - case XK_bracketleft: /* reconfigure the focused window to occupy the left or top half of the screen or left quarters on repeat */ - if (vwin) { - do_grab = 1; - - if (keypress->xkey.state & ShiftMask) { - if (!repeat_cnt) { - vwm_win_autoconf(vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_HALF, VWM_SIDE_TOP); - } else { - vwm_win_autoconf(vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_QUARTER, VWM_CORNER_TOP_LEFT); - } - } else { - if (!repeat_cnt) { - vwm_win_autoconf(vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_HALF, VWM_SIDE_LEFT); - } else { - vwm_win_autoconf(vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_QUARTER, VWM_CORNER_BOTTOM_LEFT); - } - } - } - break; - - case XK_bracketright: /* reconfigure the focused window to occupy the right or bottom half of the screen or right quarters on repeat */ - if (vwin) { - do_grab = 1; - - if (keypress->xkey.state & ShiftMask) { - if (!repeat_cnt) { - vwm_win_autoconf(vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_HALF, VWM_SIDE_BOTTOM); - } else { - vwm_win_autoconf(vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_QUARTER, VWM_CORNER_BOTTOM_RIGHT); - } - } else { - if (!repeat_cnt) { - vwm_win_autoconf(vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_HALF, VWM_SIDE_RIGHT); - } else { - vwm_win_autoconf(vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_QUARTER, VWM_CORNER_TOP_RIGHT); - } - } - } - break; - - case XK_semicolon: /* toggle composited overlays */ - vwm_comp_toggle(); - break; - - case XK_apostrophe: /* reset snowflakes of the focused window, suppressed when not compositing */ - if (vwin && compositing_mode && vwin->xwindow->overlay.snowflakes_cnt) { - vwin->xwindow->overlay.snowflakes_cnt = 0; - vwm_comp_damage_win(vwin->xwindow); - } - break; - - case XK_Right: /* increase sampling frequency */ - if (sampling_interval + 1 < sizeof(sampling_intervals) / sizeof(sampling_intervals[0])) sampling_interval++; - break; - - case XK_Left: /* decrease sampling frequency, -1 pauses */ - if (sampling_interval >= 0) sampling_interval--; - break; - default: - VWM_TRACE("Unhandled keycode: %x", (unsigned int)sym); - break; - } - - /* if what we're doing requests a grab, if not already grabbed, grab keyboard */ - if (!key_is_grabbed && do_grab) { - VWM_TRACE("saving focused_origin of %p", vwin); - focused_origin = vwin; /* for returning to on abort */ - XGrabKeyboard(display, RootWindow(display, screen_num), False, GrabModeAsync, GrabModeAsync, CurrentTime); - key_is_grabbed = 1; - } - - /* remember the symbol for repeater detection */ - last_sym = sym; - last_state = keypress->xkey.state; -} - - - /* some randomish things called from main() */ - -/* manage all existing windows (for startup) */ -static int vwm_manage_existing(void) -{ - Window root, parent; - Window *children = NULL; - unsigned int n_children, i; - - XGrabServer(display); - XSync(display, False); - XQueryTree(display, RootWindow(display, screen_num), &root, &parent, &children, &n_children); - - for (i = 0; i < n_children; i++) { - if (children[i] == None) continue; - - if ((vwm_xwin_create(children[i], VWM_GRABBED) == NULL)) goto _fail_grabbed; - } - - XUngrabServer(display); - - if (children) XFree(children); - - return 1; - -_fail_grabbed: - XUngrabServer(display); - - if (children) XFree(children); - - return 0; -} - - -/* comvenience function for returning the time delta as a seconds.fraction float */ -static float delta(struct timeval *cur, struct timeval *prev) -{ - struct timeval res; - float delta; - - /* determine the # of whole.fractional seconds between prev and cur */ - timersub(cur, prev, &res); - - delta = res.tv_sec; - delta += (float)((float)res.tv_usec) / 1000000.0; - - return delta; -} - -static int errhandler(Display *display, XErrorEvent *err) -{ - /* TODO */ - return 1; -} - -int main(int argc, char *argv[]) -{ - int err = 0; - int done = 0; - XEvent event; - Cursor pointer; - struct pollfd pfd; - char *console_args[] = {"xterm", "-class", CONSOLE_WM_CLASS, "-e", "/bin/sh", "-c", "screen -D -RR " CONSOLE_SESSION_STRING, NULL}; - Window bitmask; - vwm_clickety_t clickety = { .vwin = NULL }; - -#define reterr_if(_cond, _fmt, _args...) \ - err++;\ - if (_cond) {\ - VWM_ERROR(_fmt, ##_args);\ - return err;\ - } - - /* open connection with the server */ - reterr_if((display = XOpenDisplay(NULL)) == NULL, "Cannot open display"); - - /* prevent children from inheriting the X connection */ - reterr_if(fcntl(ConnectionNumber(display), F_SETFD, FD_CLOEXEC) < 0, "Cannot set FD_CLOEXEC on X connection"); - - /* get our scheduling priority, clients are launched with a priority LAUNCHED_RELATIVE_PRIORITY nicer than this */ - reterr_if((priority = getpriority(PRIO_PROCESS, getpid())) == -1, "Cannot get scheduling priority"); - - XSetErrorHandler(errhandler); - - screen_num = DefaultScreen(display); - - reterr_if(!XQueryExtension (display, COMPOSITE_NAME, &composite_opcode, &composite_event, &composite_error), "No composite extension available"); - reterr_if(!XDamageQueryExtension(display, &damage_event, &damage_error), "No damage extension available"); - if (XSyncQueryExtension(display, &sync_event, &sync_error)) { - /* set the window manager to the maximum X client priority */ - XSyncSetPriority(display, RootWindow(display, screen_num), 0x7fffffff); - } - - if (XineramaQueryExtension(display, &xinerama_event, &xinerama_error)) { - xinerama_screens = XineramaQueryScreens(display, &xinerama_screens_cnt); - } - - if (XRRQueryExtension(display, &randr_event, &randr_error)) { - XRRSelectInput(display, RootWindow(display, screen_num), RRScreenChangeNotifyMask); - } - - /* allocate colors, I make assumptions about the X server's color capabilities since I'll only use this on modern-ish computers... */ - cmap = DefaultColormap(display, screen_num); - -#define color(_sym, _str) \ - XAllocNamedColor(display, cmap, _str, &_sym ## _color, &_sym ## _color); -#include "colors.def" -#undef color - - wm_delete_atom = XInternAtom(display, "WM_DELETE_WINDOW", False); - wm_protocols_atom = XInternAtom(display, "WM_PROTOCOLS", False); - wm_pid_atom = XInternAtom(display, "_NET_WM_PID", False); - - XSelectInput(display, RootWindow(display, screen_num), - PropertyChangeMask | SubstructureNotifyMask | SubstructureRedirectMask | PointerMotionMask | ButtonPressMask | ButtonReleaseMask); - XGrabKey(display, AnyKey, WM_GRAB_MODIFIER, RootWindow(display, screen_num), False, GrabModeAsync, GrabModeAsync); - - XFlush(display); - - XSetInputFocus(display, RootWindow(display, screen_num), RevertToPointerRoot, CurrentTime); - - /* initialize libvmon */ - vmon_init(&vmon, VMON_FLAG_2PASS, VMON_WANT_SYS_STAT, (VMON_WANT_PROC_STAT | VMON_WANT_PROC_FOLLOW_CHILDREN | VMON_WANT_PROC_FOLLOW_THREADS)); - vmon.proc_ctor_cb = vmon_ctor_cb; - vmon.proc_dtor_cb = vmon_dtor_cb; - vmon.sample_cb = sample_callback; - - /* get all the text and graphics stuff setup for overlays */ - reterr_if(!(overlay_font = XLoadQueryFont(display, OVERLAY_FIXED_FONT)), "failed to open font: " OVERLAY_FIXED_FONT); - - /* create a GC for rendering the text using Xlib into the text overlay stencils */ - bitmask = XCreatePixmap(display, RootWindow(display, screen_num), 1, 1, OVERLAY_MASK_DEPTH); - text_gc = XCreateGC(display, bitmask, 0, NULL); - XSetForeground(display, text_gc, WhitePixel(display, screen_num)); - XFreePixmap(display, bitmask); - - /* create some repeating source fill pictures for drawing through the text and graph stencils */ - bitmask = XCreatePixmap(display, RootWindow(display, screen_num), 1, 1, 32); - overlay_text_fill = XRenderCreatePicture(display, bitmask, XRenderFindStandardFormat(display, PictStandardARGB32), CPRepeat, &pa_repeat); - XRenderFillRectangle(display, PictOpSrc, overlay_text_fill, &overlay_visible_color, 0, 0, 1, 1); - - bitmask = XCreatePixmap(display, RootWindow(display, screen_num), 1, 1, 32); - overlay_shadow_fill = XRenderCreatePicture(display, bitmask, XRenderFindStandardFormat(display, PictStandardARGB32), CPRepeat, &pa_repeat); - XRenderFillRectangle(display, PictOpSrc, overlay_shadow_fill, &overlay_shadow_color, 0, 0, 1, 1); - - bitmask = XCreatePixmap(display, RootWindow(display, screen_num), 1, OVERLAY_ROW_HEIGHT, 32); - overlay_bg_fill = XRenderCreatePicture(display, bitmask, XRenderFindStandardFormat(display, PictStandardARGB32), CPRepeat, &pa_repeat); - XRenderFillRectangle(display, PictOpSrc, overlay_bg_fill, &overlay_bg_color, 0, 0, 1, OVERLAY_ROW_HEIGHT); - XRenderFillRectangle(display, PictOpSrc, overlay_bg_fill, &overlay_div_color, 0, OVERLAY_ROW_HEIGHT - 1, 1, 1); - - bitmask = XCreatePixmap(display, RootWindow(display, screen_num), 1, 1, 32); - overlay_snowflakes_text_fill = XRenderCreatePicture(display, bitmask, XRenderFindStandardFormat(display, PictStandardARGB32), CPRepeat, &pa_repeat); - XRenderFillRectangle(display, PictOpSrc, overlay_snowflakes_text_fill, &overlay_snowflakes_visible_color, 0, 0, 1, 1); - - bitmask = XCreatePixmap(display, RootWindow(display, screen_num), 1, 1, 32); - overlay_grapha_fill = XRenderCreatePicture(display, bitmask, XRenderFindStandardFormat(display, PictStandardARGB32), CPRepeat, &pa_repeat); - XRenderFillRectangle(display, PictOpSrc, overlay_grapha_fill, &overlay_grapha_color, 0, 0, 1, 1); - - bitmask = XCreatePixmap(display, RootWindow(display, screen_num), 1, 1, 32); - overlay_graphb_fill = XRenderCreatePicture(display, bitmask, XRenderFindStandardFormat(display, PictStandardARGB32), CPRepeat, &pa_repeat); - XRenderFillRectangle(display, PictOpSrc, overlay_graphb_fill, &overlay_graphb_color, 0, 0, 1, 1); - - bitmask = XCreatePixmap(display, RootWindow(display, screen_num), 1, 2, 32); - overlay_finish_fill = XRenderCreatePicture(display, bitmask, XRenderFindStandardFormat(display, PictStandardARGB32), CPRepeat, &pa_repeat); - XRenderFillRectangle(display, PictOpSrc, overlay_finish_fill, &overlay_visible_color, 0, 0, 1, 1); - XRenderFillRectangle(display, PictOpSrc, overlay_finish_fill, &overlay_trans_color, 0, 1, 1, 1); - - /* create initial virtual desktop */ - vwm_desktop_focus(vwm_desktop_create(NULL)); - vwm_desktop_mru(focused_desktop); - - /* manage all preexisting windows */ - vwm_manage_existing(); - - /* create GC for logo drawing and window rubber-banding */ - gc = XCreateGC(display, RootWindow(display, screen_num), 0, NULL); - XSetSubwindowMode(display, gc, IncludeInferiors); - XSetFunction(display, gc, GXxor); - - /* launch the console here so it's likely ready by the time the logo animation finishes (there's no need to synchronize with it currently) */ - vwm_launch(console_args, VWM_LAUNCH_MODE_BG); - - /* first the logo color is the foreground */ - XSetForeground(display, gc, logo_color.pixel); - vwm_draw_logo(); - - /* change to the rubber-banding foreground color */ - XSetForeground(display, gc, rubberband_color.pixel); - - XClearWindow(display, RootWindow(display, screen_num)); - - /* set the pointer */ - pointer = XCreateFontCursor(display, XC_X_cursor); - XDefineCursor(display, RootWindow(display, screen_num), pointer); - - pfd.events = POLLIN; - pfd.revents = 0; - pfd.fd = ConnectionNumber(display); - - gettimeofday(&this_sample, NULL); - while (!done) { - do { - static int sampling_paused = 0; - static int contiguous_drops = 0; - float this_delta; - - gettimeofday(&maybe_sample, NULL); - if ((sampling_interval == -1 && !sampling_paused) || /* XXX this is kind of a kludge to get the 0 Hz indicator drawn before pausing */ - (sampling_interval != -1 && ((this_delta = delta(&maybe_sample, &this_sample)) >= sampling_intervals[sampling_interval]))) { - vmon_sys_stat_t *sys_stat; - - /* automatically lower the sample rate if we can't keep up with the current sample rate */ - if (sampling_interval != -1 && sampling_interval <= prev_sampling_interval && - this_delta >= (sampling_intervals[sampling_interval] * 1.5)) { - contiguous_drops++; - /* require > 1 contiguous drops before lowering the rate, tolerates spurious one-off stalls */ - if (contiguous_drops > 2) sampling_interval--; - } else contiguous_drops = 0; - - /* age the sys-wide sample data into "last" variables, before the new sample overwrites them. */ - last_sample = this_sample; - this_sample = maybe_sample; - if ((sys_stat = vmon.stores[VMON_STORE_SYS_STAT])) { - last_user_cpu = sys_stat->user; - last_system_cpu = sys_stat->system; - last_total = sys_stat->user + - sys_stat->nice + - sys_stat->system + - sys_stat->idle + - sys_stat->iowait + - sys_stat->irq + - sys_stat->softirq + - sys_stat->steal + - sys_stat->guest; - - last_idle = sys_stat->idle; - last_iowait = sys_stat->iowait; - } - - vmon_sample(&vmon); /* XXX: calls proc_sample_callback() for explicitly monitored processes after sampling their descendants */ - /* XXX: also calls sample_callback() per invocation after sampling the sys wants */ - sampling_paused = (sampling_interval == -1); - prev_sampling_interval = sampling_interval; - } - - XFlush(display); - - if (!XPending(display)) { - /* TODO: make some effort to compute how long to sleep, but this is perfectly fine for now. */ - if (poll(&pfd, 1, sampling_interval != -1 ? sampling_intervals[sampling_interval] * 300.0 : -1) == 0) break; - } - - XNextEvent(display, &event); - switch (event.type) { - case KeyPress: - VWM_TRACE("keypress"); - vwm_keypressed(event.xkey.window, &event); - break; - - case KeyRelease: - VWM_TRACE("keyrelease"); - vwm_keyreleased(event.xkey.window, &event); - break; - - case ButtonPress: - VWM_TRACE("buttonpresss"); - vwm_clickety_pressed(&clickety, event.xbutton.window, &event.xbutton); - break; - - case MotionNotify: - //VWM_TRACE("motionnotify"); - vwm_clickety_motion(&clickety, event.xmotion.window, &event.xmotion); - break; - - case ButtonRelease: - VWM_TRACE("buttonrelease"); - vwm_clickety_released(&clickety, event.xbutton.window, &event.xbutton); - break; - - case CreateNotify: - VWM_TRACE("createnotify"); - vwm_xwin_create(event.xcreatewindow.window, VWM_NOT_GRABBED); - break; - - case DestroyNotify: { - vwm_xwindow_t *xwin; - VWM_TRACE("destroynotify"); - if ((xwin = vwm_xwin_lookup(event.xdestroywindow.window))) { - vwm_xwin_destroy(xwin); - } - break; - } - - case ConfigureRequest: { - XWindowChanges changes = { - .x = event.xconfigurerequest.x, /* TODO: for now I don't manipulate anything */ - .y = event.xconfigurerequest.y, - .width = event.xconfigurerequest.width, - .height = event.xconfigurerequest.height, - .border_width = WINDOW_BORDER_WIDTH /* except I do override whatever the border width may be */ - }; - unsigned long change_mask = (event.xconfigurerequest.value_mask & (CWX | CWY | CWWidth | CWHeight)) | CWBorderWidth; - vwm_xwindow_t *xwin; - - /* XXX: windows raising themselves is annoying, so discard CWSibling and CWStackMode. */ - VWM_TRACE("configurerequest x=%i y=%i w=%i h=%i", changes.x, changes.y, changes.width, changes.height); - - if ((xwin = vwm_xwin_lookup(event.xconfigure.window)) && - xwin->managed && - xwin->managed->autoconfigured == VWM_WIN_AUTOCONF_ALL) { - /* this is to allow auto-allscreen to succeed in getting a borderless window configured */ - change_mask &= ~CWBorderWidth; - } - - XConfigureWindow(display, event.xconfigurerequest.window, change_mask, &changes); - break; - } - - case ConfigureNotify: { - vwm_xwindow_t *xwin; - VWM_TRACE("configurenotify"); - if ((xwin = vwm_xwin_lookup(event.xconfigure.window))) { - XWindowAttributes attrs; - vwm_xwin_restack(xwin, event.xconfigure.above); - XGetWindowAttributes(display, event.xconfigure.window, &attrs); - if (compositing_mode) { - /* damage the old and new window areas */ - XserverRegion region; - XRectangle rects[2] = { { xwin->attrs.x, - xwin->attrs.y, - xwin->attrs.width + xwin->attrs.border_width * 2, - xwin->attrs.height + xwin->attrs.border_width * 2 }, - { attrs.x, - attrs.y, - attrs.width + attrs.border_width * 2, - attrs.height + attrs.border_width * 2 } }; - - region = XFixesCreateRegion(display, rects, 2); - vwm_comp_damage_add(region); - vwm_xwin_unbind_namewindow(xwin); - vwm_xwin_bind_namewindow(xwin); - } - VWM_TRACE("pre x=%i y=%i w=%i h=%i\n", xwin->attrs.x, xwin->attrs.y, xwin->attrs.width, xwin->attrs.height); - xwin->attrs = attrs; - VWM_TRACE("post x=%i y=%i w=%i h=%i\n", xwin->attrs.x, xwin->attrs.y, xwin->attrs.width, xwin->attrs.height); - } - break; - } - - case UnmapNotify: { - vwm_xwindow_t *xwin; - VWM_TRACE("unmapnotify"); - /* unlike MapRequest, we simply are notified when a window is unmapped. */ - if ((xwin = vwm_xwin_lookup(event.xunmap.window))) { - if (xwin->managed) { - if (xwin->managed->unmapping) { - VWM_TRACE("swallowed vwm-induced UnmapNotify"); - xwin->managed->unmapping = 0; - } else { - /* client requested unmap, demote the window and note the unmapped state */ - vwm_win_unmanage(xwin->managed); - xwin->mapped = 0; - } - } else { - /* if it's not managed, we can't have caused the map */ - xwin->mapped = 0; - } - - if (compositing_mode) vwm_comp_damage_win(xwin); - } - break; - } - - case MapNotify: { - vwm_xwindow_t *xwin; - VWM_TRACE("mapnotify"); - if ((xwin = vwm_xwin_lookup(event.xmap.window))) { - if (xwin->managed && xwin->managed->mapping) { - VWM_TRACE("swallowed vwm-induced MapNotify"); - xwin->managed->mapping = 0; - } else { - /* some windows like popup dialog boxes bypass MapRequest */ - xwin->mapped = 1; - } - - if (compositing_mode) { - vwm_comp_damage_win(xwin); - vwm_xwin_unbind_namewindow(xwin); - vwm_xwin_bind_namewindow(xwin); - } - } - break; - } - - case MapRequest: { - vwm_xwindow_t *xwin; - vwm_window_t *vwin = NULL; - int domap = 1; - VWM_TRACE("maprequest"); - if ((xwin = vwm_xwin_lookup(event.xmap.window)) && - ((vwin = xwin->managed) || (vwin = vwm_win_manage_xwin(xwin)))) { - XWindowAttributes attrs; - XWindowChanges changes = {.x = 0, .y = 0}; - unsigned changes_mask = (CWX | CWY); - XClassHint *classhint; - const vwm_screen_t *scr = NULL; - - xwin->mapped = 1; /* note that the client mapped the window */ - - /* figure out if the window is the console */ - if ((classhint = XAllocClassHint())) { - if (XGetClassHint(display, event.xmap.window, classhint) && !strcmp(classhint->res_class, CONSOLE_WM_CLASS)) { - console = vwin; - vwm_win_shelve(vwin); - vwm_win_autoconf(vwin, VWM_SCREEN_REL_XWIN, VWM_WIN_AUTOCONF_FULL); - domap = 0; - } - - if (classhint->res_class) XFree(classhint->res_class); - if (classhint->res_name) XFree(classhint->res_name); - XFree(classhint); - } - - /* TODO: this is a good place to hook in a window placement algo */ - - /* on client-requested mapping we place the window */ - if (!vwin->shelved) { - /* we place the window on the screen containing the the pointer only if that screen is empty, - * otherwise we place windows on the screen containing the currently focused window */ - /* since we query the geometry of windows in determining where to place them, a configuring - * flag is used to exclude the window being configured from those queries */ - scr = vwm_screen_find(VWM_SCREEN_REL_POINTER); - vwin->configuring = 1; - if (vwm_screen_is_empty(scr)) { - /* focus the new window if it isn't already focused when it's going to an empty screen */ - VWM_TRACE("window \"%s\" is alone on screen \"%i\", focusing", vwin->xwindow->name, scr->screen_number); - vwm_win_focus(vwin); - } else { - scr = vwm_screen_find(VWM_SCREEN_REL_XWIN, focused_desktop->focused_window->xwindow); - } - vwin->configuring = 0; - - changes.x = scr->x_org; - changes.y = scr->y_org; - } else if (focused_context == VWM_CONTEXT_FOCUS_SHELF) { - scr = vwm_screen_find(VWM_SCREEN_REL_XWIN, focused_shelf->xwindow); - changes.x = scr->x_org; - changes.y = scr->y_org; - } - - /* XXX TODO: does this belong here? */ - XGetWMNormalHints(display, event.xmap.window, vwin->hints, &vwin->hints_supplied); - XGetWindowAttributes(display, event.xmap.window, &attrs); - - - /* if the window size is precisely the screen size then directly "allscreen" the window right here */ - if (!vwin->shelved && scr && - attrs.width == scr->width && - attrs.height == scr->height) { - VWM_TRACE("auto-allscreened window \"%s\"", vwin->xwindow->name); - changes.border_width = 0; - changes_mask |= CWBorderWidth; - vwin->autoconfigured = VWM_WIN_AUTOCONF_ALL; - } - - vwin->client.x = changes.x; - vwin->client.y = changes.y; - vwin->client.height = attrs.height; - vwin->client.width = attrs.width; - - XConfigureWindow(display, event.xmap.window, changes_mask, &changes); - } - - if (domap) { - XMapWindow(display, event.xmap.window); - if (vwin && vwin->desktop->focused_window == vwin) { - XSync(display, False); - XSetInputFocus(display, vwin->xwindow->id, RevertToPointerRoot, CurrentTime); - } - } - break; - } - - case PropertyNotify: { - vwm_xwindow_t *xwin; - VWM_TRACE("property notify"); - if ((xwin = vwm_xwin_lookup(event.xproperty.window)) && - event.xproperty.atom == wm_pid_atom && - event.xproperty.state == PropertyNewValue) vwm_xwin_monitor(xwin); - break; - } - - case MappingNotify: - VWM_TRACE("mapping notify"); - XRefreshKeyboardMapping(&event.xmapping); - break; - - case Expose: - VWM_TRACE("expose"); - break; - case GravityNotify: - VWM_TRACE("gravitynotify"); - break; - case ReparentNotify: - VWM_TRACE("reparentnotify"); - break; - default: - if (event.type == randr_event + RRScreenChangeNotify) { - VWM_TRACE("rrscreenchangenotify"); - if (xinerama_screens) XFree(xinerama_screens); - xinerama_screens = XineramaQueryScreens(display, &xinerama_screens_cnt); - - if (compositing_mode) vwm_comp_invalidate_root(); - } else if (event.type == damage_event + XDamageNotify) { - //VWM_TRACE("damagenotify"); - vwm_comp_damage_event((XDamageNotifyEvent *)&event); - } else { - VWM_ERROR("Unhandled X op %i", event.type); - } - break; - } - } while (QLength(display)); - - if (combined_damage != None) { /* if there's damage to repaint, do it, this only happens when compositing for overlays is enabled */ - vwm_comp_paint_all(); - XSync(display, False); - } - } - - /* close connection to server */ - XFlush(display); - XCloseDisplay(display); - - return 0; -} diff --git a/vwm.h b/vwm.h deleted file mode 100644 index 7a85360..0000000 --- a/vwm.h +++ /dev/null @@ -1,84 +0,0 @@ -#ifndef _VWM_H -#define _VWM_H - -#include -#include -#include -#include - -#include "list.h" - -#define VWM_ERROR(_fmt, _args...) fprintf(stderr, "%s:%i\t%s() "_fmt"\n", __FILE__, __LINE__, __FUNCTION__, ##_args) -#define VWM_PERROR(_fmt, _args...) fprintf(stderr, "%s:%i\t%s() "_fmt"; %s\n", __FILE__, __LINE__, __FUNCTION__, ##_args, strerror(errno)) -#define VWM_BUG(_fmt, _args...) fprintf(stderr, "BUG %s:%i\t%s() "_fmt"; %s\n", __FILE__, __LINE__, __FUNCTION__, ##_args, strerror(errno)) - -#ifdef TRACE -#define VWM_TRACE(_fmt, _args...) fprintf(stderr, "%s:%i\t%s() "_fmt"\n", __FILE__, __LINE__, __FUNCTION__, ##_args) -#else -#define VWM_TRACE(_fmt, _args...) do { } while(0) -#endif - -typedef struct _vwm_desktop_t { - list_head_t desktops; /* global list of (virtual) desktops */ - list_head_t desktops_mru; /* global list of (virtual) desktops in MRU order */ - char *name; /* name of the desktop (TODO) */ - struct _vwm_window_t *focused_window; /* the focused window on this virtual desktop */ -} vwm_desktop_t; - -/* everything needed by the per-window overlay's context */ -typedef struct _vwm_overlay_t { - Pixmap text_pixmap; /* pixmap for overlayed text (kept around for XDrawText usage) */ - Picture text_picture; /* picture representation of text_pixmap */ - Picture shadow_picture; /* text shadow layer */ - Picture grapha_picture; /* graph A layer */ - Picture graphb_picture; /* graph B layer */ - Picture tmp_picture; /* 1 row worth of temporary picture space */ - Picture picture; /* overlay picture derived from the pixmap, for render compositing */ - int width; /* current width of the overlay */ - int height; /* current height of the overlay */ - int phase; /* current position within the (horizontally scrolling) graphs */ - int heirarchy_end; /* row where the process heirarchy currently ends */ - int snowflakes_cnt; /* count of snowflaked rows (reset to zero to truncate snowflakes display) */ - int gen_last_composed; /* the last composed vmon generation */ -} vwm_overlay_t; - -/* every window gets this, even non-managed ones. For compositing vwm must track everything visible, even popup menus. */ -typedef struct _vwm_xwindow_t { - list_head_t xwindows; /* global list of all windows kept in X stacking order */ - - Window id; /* X Window backing this instance */ - XWindowAttributes attrs; /* X window's current attributes, kept up-to-date in handling of ConfigureNotify events */ - Damage damage; /* X damage object associated with the window (for compositing) */ - Picture picture; /* X picture object representing the window (for compositing) */ - Pixmap pixmap; /* X pixmap object representing the window (for compositing) */ - - vmon_proc_t *monitor; /* vmon process monitor handle, may be NULL if for example the X client doesn't supply a PID */ - vwm_overlay_t overlay; /* monitoring overlay state */ - - char *name; /* client name */ - unsigned int mapped:1; /* is the window currently mapped (by client) */ - unsigned int occluded:1; /* is the window occluded entirely by another window? (used and valid only during paint_all()) */ - /* if only Xorg could send VisibilityNotify events when requested for redirected windows :( */ - struct _vwm_window_t *managed; /* is the window "managed"? NULL or this points to the managed context of the window */ -} vwm_xwindow_t; - -/* the managed window we create for every mapped window we actually manage */ -typedef struct _vwm_window_t { - list_head_t windows_mru; /* global list of managed windows kept in MRU order */ - - vwm_xwindow_t *xwindow; /* window being managed */ - vwm_desktop_t *desktop; /* desktop this window belongs to currently */ - - XWindowAttributes client; /* attrs of the client-configured window */ - - XSizeHints *hints; /* hints the client supplied */ - long hints_supplied; /* bitfield reflecting the hints the client supplied */ - - unsigned int autoconfigured:3; /* autoconfigured window states (none/quarter/half/full/all) */ - unsigned int mapping:1; /* is the window being mapped? (by vwm) */ - unsigned int unmapping:1; /* is the window being unmapped? (by vwm) */ - unsigned int configuring:1; /* is the window being configured/placed? (by vwm) */ - unsigned int shelved:1; /* is the window shelved? */ -} vwm_window_t; - -#endif -- cgit v1.2.3