Initial import.

This commit is contained in:
Hisham Muhammad 2006-03-04 18:16:49 +00:00
commit d6231bab89
87 changed files with 9306 additions and 0 deletions

1
AUTHORS Normal file
View File

@ -0,0 +1 @@
Hisham H. Muhammad

72
AvailableColumnsListBox.c Normal file
View File

@ -0,0 +1,72 @@
#include "AvailableColumnsListBox.h"
#include "Settings.h"
#include "Header.h"
#include "ScreenManager.h"
#include "ColumnsListBox.h"
#include "ListBox.h"
#include "debug.h"
#include <assert.h>
/*{
typedef struct AvailableColumnsListBox_ {
ListBox super;
ListBox* columns;
Settings* settings;
ScreenManager* scr;
} AvailableColumnsListBox;
}*/
AvailableColumnsListBox* AvailableColumnsListBox_new(Settings* settings, ListBox* columns, ScreenManager* scr) {
AvailableColumnsListBox* this = (AvailableColumnsListBox*) malloc(sizeof(AvailableColumnsListBox));
ListBox* super = (ListBox*) this;
ListBox_init(super, 1, 1, 1, 1, LISTITEM_CLASS, true);
((Object*)this)->delete = AvailableColumnsListBox_delete;
this->settings = settings;
this->scr = scr;
super->eventHandler = AvailableColumnsListBox_eventHandler;
ListBox_setHeader(super, "Available Columns");
for (int i = 1; i < LAST_PROCESSFIELD; i++) {
if (i != COMM)
ListBox_add(super, (Object*) ListItem_new(Process_fieldNames[i], 0));
}
this->columns = columns;
return this;
}
void AvailableColumnsListBox_delete(Object* object) {
ListBox* super = (ListBox*) object;
AvailableColumnsListBox* this = (AvailableColumnsListBox*) object;
ListBox_done(super);
free(this);
}
HandlerResult AvailableColumnsListBox_eventHandler(ListBox* super, int ch) {
AvailableColumnsListBox* this = (AvailableColumnsListBox*) super;
char* text = ((ListItem*) ListBox_getSelected(super))->value;
HandlerResult result = IGNORED;
switch(ch) {
case 13:
case KEY_ENTER:
case KEY_F(5):
{
int at = ListBox_getSelectedIndex(this->columns) + 1;
if (at == ListBox_getSize(this->columns))
at--;
ListBox_insert(this->columns, at, (Object*) ListItem_new(text, 0));
ColumnsListBox_update(this->columns);
result = HANDLED;
break;
}
}
return result;
}

31
AvailableColumnsListBox.h Normal file
View File

@ -0,0 +1,31 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_AvailableColumnsListBox
#define HEADER_AvailableColumnsListBox
#include "Settings.h"
#include "Header.h"
#include "ScreenManager.h"
#include "ListBox.h"
#include "debug.h"
#include <assert.h>
typedef struct AvailableColumnsListBox_ {
ListBox super;
Settings* settings;
ScreenManager* scr;
ListBox* columns;
} AvailableColumnsListBox;
AvailableColumnsListBox* AvailableColumnsListBox_new(Settings* settings, ListBox* columns, ScreenManager* scr);
void AvailableColumnsListBox_delete(Object* object);
HandlerResult AvailableColumnsListBox_eventHandler(ListBox* super, int ch);
#endif

103
AvailableMetersListBox.c Normal file
View File

@ -0,0 +1,103 @@
#include "AvailableMetersListBox.h"
#include "Settings.h"
#include "Header.h"
#include "ScreenManager.h"
#include "ListBox.h"
#include "debug.h"
#include <assert.h>
/*{
typedef struct AvailableMetersListBox_ {
ListBox super;
Settings* settings;
ListBox* leftBox;
ListBox* rightBox;
ScreenManager* scr;
} AvailableMetersListBox;
}*/
AvailableMetersListBox* AvailableMetersListBox_new(Settings* settings, ListBox* leftMeters, ListBox* rightMeters, ScreenManager* scr) {
AvailableMetersListBox* this = (AvailableMetersListBox*) malloc(sizeof(AvailableMetersListBox));
ListBox* super = (ListBox*) this;
ListBox_init(super, 1, 1, 1, 1, LISTITEM_CLASS, true);
((Object*)this)->delete = AvailableMetersListBox_delete;
this->settings = settings;
this->leftBox = leftMeters;
this->rightBox = rightMeters;
this->scr = scr;
super->eventHandler = AvailableMetersListBox_EventHandler;
ListBox_setHeader(super, "Available meters");
ListBox_add(super, (Object*) ListItem_new("Swap", 0));
ListBox_add(super, (Object*) ListItem_new("Memory", 0));
ListBox_add(super, (Object*) ListItem_new("Clock", 0));
ListBox_add(super, (Object*) ListItem_new("Load", 0));
ListBox_add(super, (Object*) ListItem_new("LoadAverage", 0));
ListBox_add(super, (Object*) ListItem_new("Uptime", 0));
ListBox_add(super, (Object*) ListItem_new("Tasks", 0));
if (settings->pl->processorCount > 1)
ListBox_add(super, (Object*) ListItem_new("CPUAverage", 0));
for (int i = 1; i <= settings->pl->processorCount; i++) {
char buffer[50];
sprintf(buffer, "CPU(%d)", i);
ListBox_add(super, (Object*) ListItem_new(buffer, 0));
}
return this;
}
void AvailableMetersListBox_delete(Object* object) {
ListBox* super = (ListBox*) object;
AvailableMetersListBox* this = (AvailableMetersListBox*) object;
ListBox_done(super);
free(this);
}
/* private */
inline void AvailableMetersListBox_addHeader(Header* header, ListBox* lb, char* name, HeaderSide side) {
Header_createMeter(header, name, side);
int i = Header_size(header, side) - 1;
Meter* meter = (Meter*) Header_getMeter(header, i, side);
ListBox_add(lb, (Object*) Meter_toListItem(meter));
}
HandlerResult AvailableMetersListBox_EventHandler(ListBox* super, int ch) {
AvailableMetersListBox* this = (AvailableMetersListBox*) super;
Header* header = this->settings->header;
ListItem* selected = (ListItem*) ListBox_getSelected(super);
char* name = selected->value;
HandlerResult result = IGNORED;
switch(ch) {
case KEY_F(5):
case 'l':
case 'L':
{
AvailableMetersListBox_addHeader(header, this->leftBox, name, LEFT_HEADER);
result = HANDLED;
break;
}
case KEY_F(6):
case 'r':
case 'R':
{
AvailableMetersListBox_addHeader(header, this->rightBox, name, RIGHT_HEADER);
result = HANDLED;
break;
}
}
if (result == HANDLED) {
this->settings->changed = true;
Header_calculateHeight(header);
Header_draw(header);
ScreenManager_resize(this->scr, this->scr->x1, header->height, this->scr->x2, this->scr->y2);
}
return result;
}

33
AvailableMetersListBox.h Normal file
View File

@ -0,0 +1,33 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_AvailableMetersListBox
#define HEADER_AvailableMetersListBox
#include "Settings.h"
#include "Header.h"
#include "ScreenManager.h"
#include "ListBox.h"
#include "debug.h"
#include <assert.h>
typedef struct AvailableMetersListBox_ {
ListBox super;
Settings* settings;
ListBox* leftBox;
ListBox* rightBox;
ScreenManager* scr;
} AvailableMetersListBox;
AvailableMetersListBox* AvailableMetersListBox_new(Settings* settings, ListBox* leftMeters, ListBox* rightMeters, ScreenManager* scr);
void AvailableMetersListBox_delete(Object* object);
HandlerResult AvailableMetersListBox_EventHandler(ListBox* super, int ch);
#endif

339
COPYING Normal file
View File

@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
675 Mass Ave, Cambridge, MA 02139, USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) 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
this service 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 make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. 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.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the 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 a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE 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.
END OF TERMS AND CONDITIONS
Appendix: 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
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) 19yy <name of author>
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) 19yy name of author
Gnomovision 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, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This 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 Library General
Public License instead of this License.

86
CPUMeter.c Normal file
View File

@ -0,0 +1,86 @@
/*
htop - CPUMeter.c
(C) 2004,2005 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "CPUMeter.h"
#include "Meter.h"
#include "ProcessList.h"
#include <stdlib.h>
#include <curses.h>
#include <string.h>
#include <math.h>
#include "debug.h"
#include <assert.h>
/*{
typedef struct CPUMeter_ CPUMeter;
struct CPUMeter_ {
Meter super;
ProcessList* pl;
int processor;
};
}*/
#ifndef MIN
#define MIN(a,b) ((a)<(b)?(a):(b))
#endif
#ifndef MAX
#define MAX(a,b) ((a)>(b)?(a):(b))
#endif
CPUMeter* CPUMeter_new(ProcessList* pl, int processor) {
CPUMeter* this = malloc(sizeof(CPUMeter));
char* caption;
if (pl->processorCount == 1 || processor == 0) {
caption = String_copy("CPU");
} else {
caption = (char*) malloc(4);
sprintf(caption, "%-3d", processor);
}
Meter_init((Meter*)this, NULL, caption, 3);
((Meter*)this)->name = malloc(20);
sprintf(((Meter*)this)->name, "CPU(%d)", processor);
((Meter*)this)->attributes[0] = CPU_NICE;
((Meter*)this)->attributes[1] = CPU_NORMAL;
((Meter*)this)->attributes[2] = CPU_KERNEL;
((Meter*)this)->setValues = CPUMeter_setValues;
((Object*)this)->display = CPUMeter_display;
((Meter*)this)->total = 1.0;
Meter_setMode((Meter*)this, BAR);
this->processor = processor;
this->pl = pl;
return this;
}
void CPUMeter_setValues(Meter* cast) {
CPUMeter* this = (CPUMeter*)cast;
cast->values[0] = this->pl->nicePeriod[this->processor] / (double)this->pl->totalPeriod[this->processor];
cast->values[1] = this->pl->userPeriod[this->processor] / (double)this->pl->totalPeriod[this->processor];
cast->values[2] = this->pl->systemPeriod[this->processor] / (double)this->pl->totalPeriod[this->processor];
double cpu = MIN(100.0, MAX(0.0, (cast->values[0]+cast->values[1]+cast->values[2])*100.0 ));
snprintf(cast->displayBuffer.c, 7, "%5.1f%%", cpu );
}
void CPUMeter_display(Object* cast, RichString* out) {
char buffer[50];
Meter* this = (Meter*)cast;
RichString_prune(out);
sprintf(buffer, "%5.1f%% ", this->values[1] * 100.0);
RichString_append(out, CRT_colors[METER_TEXT], ":");
RichString_append(out, CRT_colors[CPU_NORMAL], buffer);
sprintf(buffer, "%5.1f%% ", this->values[2] * 100.0);
RichString_append(out, CRT_colors[METER_TEXT], "sys:");
RichString_append(out, CRT_colors[CPU_KERNEL], buffer);
sprintf(buffer, "%5.1f%% ", this->values[0] * 100.0);
RichString_append(out, CRT_colors[METER_TEXT], "low:");
RichString_append(out, CRT_colors[CPU_NICE], buffer);
}

41
CPUMeter.h Normal file
View File

@ -0,0 +1,41 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_CPUMeter
#define HEADER_CPUMeter
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "Meter.h"
#include "ProcessList.h"
#include <stdlib.h>
#include <curses.h>
#include <string.h>
#include <math.h>
#include <sys/param.h>
#include "debug.h"
#include <assert.h>
typedef struct CPUMeter_ CPUMeter;
struct CPUMeter_ {
Meter super;
ProcessList* pl;
int processor;
};
CPUMeter* CPUMeter_new(ProcessList* pl, int processor);
void CPUMeter_setValues(Meter* cast);
void CPUMeter_display(Object* cast, RichString* out);
#endif

513
CRT.c Normal file
View File

@ -0,0 +1,513 @@
/*
htop - CRT.c
(C) 2004,2005 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "CRT.h"
#include <curses.h>
#include <signal.h>
#include <stdlib.h>
#include <stdbool.h>
#include "String.h"
#include "debug.h"
#define ColorPair(i,j) COLOR_PAIR((7-i)*8+j)
#define Black COLOR_BLACK
#define Red COLOR_RED
#define Green COLOR_GREEN
#define Yellow COLOR_YELLOW
#define Blue COLOR_BLUE
#define Magenta COLOR_MAGENTA
#define Cyan COLOR_CYAN
#define White COLOR_WHITE
//#link curses
bool CRT_hasColors;
/*{
typedef enum ColorElements_ {
RESET_COLOR,
DEFAULT_COLOR,
FUNCTION_BAR,
FUNCTION_KEY,
FAILED_SEARCH,
PANEL_HEADER_FOCUS,
PANEL_HEADER_UNFOCUS,
PANEL_HIGHLIGHT_FOCUS,
PANEL_HIGHLIGHT_UNFOCUS,
LARGE_NUMBER,
METER_TEXT,
METER_VALUE,
LED_COLOR,
UPTIME,
TASKS_TOTAL,
TASKS_RUNNING,
SWAP,
PROCESS,
PROCESS_SHADOW,
PROCESS_TAG,
PROCESS_MEGABYTES,
PROCESS_TREE,
PROCESS_R_STATE,
PROCESS_BASENAME,
PROCESS_HIGH_PRIORITY,
PROCESS_LOW_PRIORITY,
BAR_BORDER,
BAR_SHADOW,
GRAPH_1,
GRAPH_2,
GRAPH_3,
GRAPH_4,
GRAPH_5,
GRAPH_6,
GRAPH_7,
GRAPH_8,
GRAPH_9,
MEMORY_USED,
MEMORY_BUFFERS,
MEMORY_CACHE,
LOAD,
LOAD_AVERAGE_FIFTEEN,
LOAD_AVERAGE_FIVE,
LOAD_AVERAGE_ONE,
CHECK_BOX,
CHECK_MARK,
CHECK_TEXT,
CLOCK,
CPU_NICE,
CPU_NORMAL,
CPU_KERNEL,
HELP_BOLD,
LAST_COLORELEMENT
} ColorElements;
extern int CRT_delay;
extern int CRT_colors[LAST_COLORELEMENT];
}*/
// TODO: centralize these in Settings.
/* private property */
int CRT_delay;
/* private property */
int CRT_colorScheme;
/* private property */
int CRT_colors[LAST_COLORELEMENT];
// TODO: pass an instance of Settings instead.
void CRT_init(int delay, int colorScheme) {
initscr();
noecho();
CRT_delay = delay;
CRT_colorScheme = colorScheme;
halfdelay(CRT_delay);
nonl();
intrflush(stdscr, false);
keypad(stdscr, true);
curs_set(0);
if (has_colors()) {
start_color();
CRT_hasColors = true;
} else {
CRT_hasColors = false;
}
char* termType = getenv("TERM");
if (String_eq(termType, "xterm") || String_eq(termType, "xterm-color") || String_eq(termType, "vt220")) {
define_key("\033[H", KEY_HOME);
define_key("\033[F", KEY_END);
define_key("\033OP", KEY_F(1));
define_key("\033OQ", KEY_F(2));
define_key("\033OR", KEY_F(3));
define_key("\033OS", KEY_F(4));
define_key("\033[11~", KEY_F(1));
define_key("\033[12~", KEY_F(2));
define_key("\033[13~", KEY_F(3));
define_key("\033[14~", KEY_F(4));
define_key("\033[17;2~", KEY_F(18));
}
#ifndef DEBUG
signal(11, CRT_handleSIGSEGV);
#endif
signal(SIGTERM, CRT_handleSIGTERM);
use_default_colors();
if (!has_colors())
CRT_colorScheme = 1;
CRT_setColors(CRT_colorScheme);
mousemask(BUTTON1_CLICKED, NULL);
}
void CRT_done() {
curs_set(1);
endwin();
}
int CRT_readKey() {
nocbreak();
cbreak();
int ret = getch();
halfdelay(CRT_delay);
return ret;
}
void CRT_disableDelay() {
nocbreak();
cbreak();
nodelay(stdscr, TRUE);
}
void CRT_enableDelay() {
halfdelay(CRT_delay);
}
void CRT_handleSIGSEGV(int signal) {
CRT_done();
fprintf(stderr, "Aborted. Please report bug at http://htop.sf.net");
exit(1);
}
void CRT_handleSIGTERM(int signal) {
CRT_done();
exit(0);
}
void CRT_setColors(int colorScheme) {
CRT_colorScheme = colorScheme;
if (colorScheme == COLORSCHEME_BLACKNIGHT) {
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++)
init_pair((7-i)*8+j, i, j);
} else {
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++)
init_pair((7-i)*8+j, i, (j==0?-1:j));
}
if (colorScheme == COLORSCHEME_MONOCHROME) {
CRT_colors[RESET_COLOR] = A_NORMAL;
CRT_colors[DEFAULT_COLOR] = A_NORMAL;
CRT_colors[FUNCTION_BAR] = A_REVERSE;
CRT_colors[FUNCTION_KEY] = A_NORMAL;
CRT_colors[PANEL_HEADER_FOCUS] = A_REVERSE;
CRT_colors[PANEL_HEADER_UNFOCUS] = A_REVERSE;
CRT_colors[PANEL_HIGHLIGHT_FOCUS] = A_REVERSE | A_BOLD;
CRT_colors[PANEL_HIGHLIGHT_UNFOCUS] = A_REVERSE;
CRT_colors[FAILED_SEARCH] = A_REVERSE | A_BOLD;
CRT_colors[UPTIME] = A_BOLD;
CRT_colors[LARGE_NUMBER] = A_BOLD;
CRT_colors[METER_TEXT] = A_NORMAL;
CRT_colors[METER_VALUE] = A_BOLD;
CRT_colors[LED_COLOR] = A_NORMAL;
CRT_colors[TASKS_RUNNING] = A_BOLD;
CRT_colors[PROCESS] = A_NORMAL;
CRT_colors[PROCESS_SHADOW] = A_DIM;
CRT_colors[PROCESS_TAG] = A_BOLD;
CRT_colors[PROCESS_MEGABYTES] = A_BOLD;
CRT_colors[PROCESS_BASENAME] = A_BOLD;
CRT_colors[PROCESS_TREE] = A_BOLD;
CRT_colors[PROCESS_R_STATE] = A_BOLD;
CRT_colors[PROCESS_HIGH_PRIORITY] = A_BOLD;
CRT_colors[PROCESS_LOW_PRIORITY] = A_DIM;
CRT_colors[BAR_BORDER] = A_BOLD;
CRT_colors[BAR_SHADOW] = A_DIM;
CRT_colors[SWAP] = A_BOLD;
CRT_colors[GRAPH_1] = A_BOLD;
CRT_colors[GRAPH_2] = A_BOLD;
CRT_colors[GRAPH_3] = A_BOLD;
CRT_colors[GRAPH_4] = A_NORMAL;
CRT_colors[GRAPH_5] = A_NORMAL;
CRT_colors[GRAPH_6] = A_NORMAL;
CRT_colors[GRAPH_7] = A_DIM;
CRT_colors[GRAPH_8] = A_DIM;
CRT_colors[GRAPH_9] = A_DIM;
CRT_colors[MEMORY_USED] = A_BOLD;
CRT_colors[MEMORY_BUFFERS] = A_NORMAL;
CRT_colors[MEMORY_CACHE] = A_NORMAL;
CRT_colors[LOAD_AVERAGE_FIFTEEN] = A_DIM;
CRT_colors[LOAD_AVERAGE_FIVE] = A_NORMAL;
CRT_colors[LOAD_AVERAGE_ONE] = A_BOLD;
CRT_colors[LOAD] = A_BOLD;
CRT_colors[HELP_BOLD] = A_BOLD;
CRT_colors[CPU_NICE] = A_NORMAL;
CRT_colors[CPU_NORMAL] = A_BOLD;
CRT_colors[CPU_KERNEL] = A_BOLD;
CRT_colors[CLOCK] = A_BOLD;
CRT_colors[CHECK_BOX] = A_BOLD;
CRT_colors[CHECK_MARK] = A_NORMAL;
CRT_colors[CHECK_TEXT] = A_NORMAL;
} else if (CRT_colorScheme == COLORSCHEME_BLACKONWHITE) {
CRT_colors[RESET_COLOR] = ColorPair(Black,White);
CRT_colors[DEFAULT_COLOR] = ColorPair(Black,White);
CRT_colors[FUNCTION_BAR] = ColorPair(Black,Cyan);
CRT_colors[FUNCTION_KEY] = ColorPair(Black,White);
CRT_colors[PANEL_HEADER_FOCUS] = ColorPair(Black,Green);
CRT_colors[PANEL_HEADER_UNFOCUS] = ColorPair(Black,Green);
CRT_colors[PANEL_HIGHLIGHT_FOCUS] = ColorPair(Black,Cyan);
CRT_colors[PANEL_HIGHLIGHT_UNFOCUS] = ColorPair(Blue,White);
CRT_colors[FAILED_SEARCH] = ColorPair(Red,Cyan);
CRT_colors[UPTIME] = ColorPair(Yellow,White);
CRT_colors[LARGE_NUMBER] = ColorPair(Red,White);
CRT_colors[METER_TEXT] = ColorPair(Blue,White);
CRT_colors[METER_VALUE] = ColorPair(Black,White);
CRT_colors[LED_COLOR] = ColorPair(Green,White);
CRT_colors[TASKS_RUNNING] = ColorPair(Green,White);
CRT_colors[PROCESS] = ColorPair(Black,White);
CRT_colors[PROCESS_SHADOW] = A_BOLD | ColorPair(Black,White);
CRT_colors[PROCESS_TAG] = ColorPair(White,Blue);
CRT_colors[PROCESS_MEGABYTES] = ColorPair(Blue,White);
CRT_colors[PROCESS_BASENAME] = ColorPair(Green,White);
CRT_colors[PROCESS_TREE] = ColorPair(Blue,White);
CRT_colors[PROCESS_R_STATE] = ColorPair(Green,White);
CRT_colors[PROCESS_HIGH_PRIORITY] = ColorPair(Red,White);
CRT_colors[PROCESS_LOW_PRIORITY] = ColorPair(Red,White);
CRT_colors[BAR_BORDER] = ColorPair(Blue,White);
CRT_colors[BAR_SHADOW] = ColorPair(Black,White);
CRT_colors[SWAP] = ColorPair(Red,White);
CRT_colors[GRAPH_1] = ColorPair(Yellow,White);
CRT_colors[GRAPH_2] = ColorPair(Yellow,White);
CRT_colors[GRAPH_3] = ColorPair(Yellow,White);
CRT_colors[GRAPH_4] = ColorPair(Yellow,White);
CRT_colors[GRAPH_5] = ColorPair(Yellow,White);
CRT_colors[GRAPH_6] = ColorPair(Yellow,White);
CRT_colors[GRAPH_7] = ColorPair(Yellow,White);
CRT_colors[GRAPH_8] = ColorPair(Yellow,White);
CRT_colors[GRAPH_9] = ColorPair(Yellow,White);
CRT_colors[MEMORY_USED] = ColorPair(Green,White);
CRT_colors[MEMORY_BUFFERS] = ColorPair(Cyan,White);
CRT_colors[MEMORY_CACHE] = ColorPair(Yellow,White);
CRT_colors[LOAD_AVERAGE_FIFTEEN] = ColorPair(Black,White);
CRT_colors[LOAD_AVERAGE_FIVE] = ColorPair(Black,White);
CRT_colors[LOAD_AVERAGE_ONE] = ColorPair(Black,White);
CRT_colors[LOAD] = ColorPair(Black,White);
CRT_colors[HELP_BOLD] = ColorPair(Blue,White);
CRT_colors[CPU_NICE] = ColorPair(Cyan,White);
CRT_colors[CPU_NORMAL] = ColorPair(Green,White);
CRT_colors[CPU_KERNEL] = ColorPair(Red,White);
CRT_colors[CLOCK] = ColorPair(White,White);
CRT_colors[CHECK_BOX] = ColorPair(Blue,White);
CRT_colors[CHECK_MARK] = ColorPair(Black,White);
CRT_colors[CHECK_TEXT] = ColorPair(Black,White);
} else if (CRT_colorScheme == COLORSCHEME_BLACKONWHITE2) {
CRT_colors[RESET_COLOR] = ColorPair(Black,Black);
CRT_colors[DEFAULT_COLOR] = ColorPair(Black,Black);
CRT_colors[FUNCTION_BAR] = ColorPair(Black,Cyan);
CRT_colors[FUNCTION_KEY] = ColorPair(Black,Black);
CRT_colors[PANEL_HEADER_FOCUS] = ColorPair(Black,Green);
CRT_colors[PANEL_HEADER_UNFOCUS] = ColorPair(Black,Green);
CRT_colors[PANEL_HIGHLIGHT_FOCUS] = ColorPair(Black,Cyan);
CRT_colors[PANEL_HIGHLIGHT_UNFOCUS] = ColorPair(Blue,Black);
CRT_colors[FAILED_SEARCH] = ColorPair(Red,Cyan);
CRT_colors[UPTIME] = ColorPair(Yellow,Black);
CRT_colors[LARGE_NUMBER] = ColorPair(Red,Black);
CRT_colors[METER_TEXT] = ColorPair(Blue,Black);
CRT_colors[METER_VALUE] = ColorPair(Black,Black);
CRT_colors[LED_COLOR] = ColorPair(Green,Black);
CRT_colors[TASKS_RUNNING] = ColorPair(Green,Black);
CRT_colors[PROCESS] = ColorPair(Black,Black);
CRT_colors[PROCESS_SHADOW] = A_BOLD | ColorPair(Black,Black);
CRT_colors[PROCESS_TAG] = ColorPair(White,Blue);
CRT_colors[PROCESS_MEGABYTES] = ColorPair(Blue,Black);
CRT_colors[PROCESS_BASENAME] = ColorPair(Green,Black);
CRT_colors[PROCESS_TREE] = ColorPair(Blue,Black);
CRT_colors[PROCESS_R_STATE] = ColorPair(Green,Black);
CRT_colors[PROCESS_HIGH_PRIORITY] = ColorPair(Red,Black);
CRT_colors[PROCESS_LOW_PRIORITY] = ColorPair(Red,Black);
CRT_colors[BAR_BORDER] = ColorPair(Blue,Black);
CRT_colors[BAR_SHADOW] = ColorPair(Black,Black);
CRT_colors[SWAP] = ColorPair(Red,Black);
CRT_colors[GRAPH_1] = ColorPair(Yellow,Black);
CRT_colors[GRAPH_2] = ColorPair(Yellow,Black);
CRT_colors[GRAPH_3] = ColorPair(Yellow,Black);
CRT_colors[GRAPH_4] = ColorPair(Yellow,Black);
CRT_colors[GRAPH_5] = ColorPair(Yellow,Black);
CRT_colors[GRAPH_6] = ColorPair(Yellow,Black);
CRT_colors[GRAPH_7] = ColorPair(Yellow,Black);
CRT_colors[GRAPH_8] = ColorPair(Yellow,Black);
CRT_colors[GRAPH_9] = ColorPair(Yellow,Black);
CRT_colors[MEMORY_USED] = ColorPair(Green,Black);
CRT_colors[MEMORY_BUFFERS] = ColorPair(Cyan,Black);
CRT_colors[MEMORY_CACHE] = ColorPair(Yellow,Black);
CRT_colors[LOAD_AVERAGE_FIFTEEN] = ColorPair(Black,Black);
CRT_colors[LOAD_AVERAGE_FIVE] = ColorPair(Black,Black);
CRT_colors[LOAD_AVERAGE_ONE] = ColorPair(Black,Black);
CRT_colors[LOAD] = ColorPair(White,Black);
CRT_colors[HELP_BOLD] = ColorPair(Blue,Black);
CRT_colors[CPU_NICE] = ColorPair(Cyan,Black);
CRT_colors[CPU_NORMAL] = ColorPair(Green,Black);
CRT_colors[CPU_KERNEL] = ColorPair(Red,Black);
CRT_colors[CLOCK] = ColorPair(White,Black);
CRT_colors[CHECK_BOX] = ColorPair(Blue,Black);
CRT_colors[CHECK_MARK] = ColorPair(Black,Black);
CRT_colors[CHECK_TEXT] = ColorPair(Black,Black);
} else if (CRT_colorScheme == COLORSCHEME_MIDNIGHT) {
CRT_colors[RESET_COLOR] = ColorPair(White,Blue);
CRT_colors[DEFAULT_COLOR] = ColorPair(White,Blue);
CRT_colors[FUNCTION_BAR] = ColorPair(Black,Cyan);
CRT_colors[FUNCTION_KEY] = A_NORMAL;
CRT_colors[PANEL_HEADER_FOCUS] = ColorPair(Black,Cyan);
CRT_colors[PANEL_HEADER_UNFOCUS] = ColorPair(Black,Cyan);
CRT_colors[PANEL_HIGHLIGHT_FOCUS] = ColorPair(Black,White);
CRT_colors[PANEL_HIGHLIGHT_UNFOCUS] = A_BOLD | ColorPair(Yellow,Blue);
CRT_colors[FAILED_SEARCH] = ColorPair(Red,Cyan);
CRT_colors[UPTIME] = A_BOLD | ColorPair(Yellow,Blue);
CRT_colors[LARGE_NUMBER] = A_BOLD | ColorPair(Red,Blue);
CRT_colors[METER_TEXT] = ColorPair(Cyan,Blue);
CRT_colors[METER_VALUE] = A_BOLD | ColorPair(Cyan,Blue);
CRT_colors[LED_COLOR] = ColorPair(Green,Blue);
CRT_colors[TASKS_RUNNING] = A_BOLD | ColorPair(Green,Blue);
CRT_colors[PROCESS] = ColorPair(White,Blue);
CRT_colors[PROCESS_SHADOW] = A_BOLD | ColorPair(Black,Blue);
CRT_colors[PROCESS_TAG] = A_BOLD | ColorPair(Yellow,Blue);
CRT_colors[PROCESS_MEGABYTES] = ColorPair(Cyan,Blue);
CRT_colors[PROCESS_BASENAME] = A_BOLD | ColorPair(Cyan,Blue);
CRT_colors[PROCESS_TREE] = ColorPair(Cyan,Blue);
CRT_colors[PROCESS_R_STATE] = ColorPair(Green,Blue);
CRT_colors[PROCESS_HIGH_PRIORITY] = ColorPair(Red,Blue);
CRT_colors[PROCESS_LOW_PRIORITY] = ColorPair(Red,Blue);
CRT_colors[BAR_BORDER] = A_BOLD | ColorPair(Yellow,Blue);
CRT_colors[BAR_SHADOW] = ColorPair(Cyan,Blue);
CRT_colors[SWAP] = ColorPair(Red,Blue);
CRT_colors[GRAPH_1] = A_BOLD | ColorPair(Yellow,Blue);
CRT_colors[GRAPH_2] = A_BOLD | ColorPair(Yellow,Blue);
CRT_colors[GRAPH_3] = A_BOLD | ColorPair(Yellow,Blue);
CRT_colors[GRAPH_4] = A_BOLD | ColorPair(Yellow,Blue);
CRT_colors[GRAPH_5] = A_BOLD | ColorPair(Yellow,Blue);
CRT_colors[GRAPH_6] = A_BOLD | ColorPair(Yellow,Blue);
CRT_colors[GRAPH_7] = A_BOLD | ColorPair(Yellow,Blue);
CRT_colors[GRAPH_8] = A_BOLD | ColorPair(Yellow,Blue);
CRT_colors[GRAPH_9] = A_BOLD | ColorPair(Yellow,Blue);
CRT_colors[MEMORY_USED] = A_BOLD | ColorPair(Green,Blue);
CRT_colors[MEMORY_BUFFERS] = A_BOLD | ColorPair(Cyan,Blue);
CRT_colors[MEMORY_CACHE] = A_BOLD | ColorPair(Yellow,Blue);
CRT_colors[LOAD_AVERAGE_FIFTEEN] = A_BOLD | ColorPair(Black,Blue);
CRT_colors[LOAD_AVERAGE_FIVE] = A_NORMAL | ColorPair(White,Blue);
CRT_colors[LOAD_AVERAGE_ONE] = A_BOLD | ColorPair(White,Blue);
CRT_colors[LOAD] = A_BOLD | ColorPair(White,Blue);
CRT_colors[HELP_BOLD] = A_BOLD | ColorPair(Cyan,Blue);
CRT_colors[CPU_NICE] = A_BOLD | ColorPair(Cyan,Blue);
CRT_colors[CPU_NORMAL] = A_BOLD | ColorPair(Green,Blue);
CRT_colors[CPU_KERNEL] = A_BOLD | ColorPair(Red,Blue);
CRT_colors[CLOCK] = ColorPair(White,Blue);
CRT_colors[CHECK_BOX] = ColorPair(Cyan,Blue);
CRT_colors[CHECK_MARK] = A_BOLD | ColorPair(White,Blue);
CRT_colors[CHECK_TEXT] = A_NORMAL | ColorPair(White,Blue);
} else if (CRT_colorScheme == COLORSCHEME_BLACKNIGHT) {
CRT_colors[RESET_COLOR] = ColorPair(Cyan,Black);
CRT_colors[DEFAULT_COLOR] = ColorPair(Cyan,Black);
CRT_colors[FUNCTION_BAR] = ColorPair(Black,Green);
CRT_colors[FUNCTION_KEY] = ColorPair(Cyan,Black);
CRT_colors[PANEL_HEADER_FOCUS] = ColorPair(Black,Green);
CRT_colors[PANEL_HEADER_UNFOCUS] = ColorPair(Black,Green);
CRT_colors[PANEL_HIGHLIGHT_FOCUS] = ColorPair(Black,Cyan);
CRT_colors[PANEL_HIGHLIGHT_UNFOCUS] = ColorPair(Black,White);
CRT_colors[FAILED_SEARCH] = ColorPair(Red,Cyan);
CRT_colors[UPTIME] = ColorPair(Green,Black);
CRT_colors[LARGE_NUMBER] = A_BOLD | ColorPair(Red,Black);
CRT_colors[METER_TEXT] = ColorPair(Cyan,Black);
CRT_colors[METER_VALUE] = ColorPair(Green,Black);
CRT_colors[LED_COLOR] = ColorPair(Green,Black);
CRT_colors[TASKS_RUNNING] = A_BOLD | ColorPair(Green,Black);
CRT_colors[PROCESS] = ColorPair(Cyan,Black);
CRT_colors[PROCESS_SHADOW] = A_BOLD | ColorPair(Black,Black);
CRT_colors[PROCESS_TAG] = A_BOLD | ColorPair(Yellow,Black);
CRT_colors[PROCESS_MEGABYTES] = A_BOLD | ColorPair(Green,Black);
CRT_colors[PROCESS_BASENAME] = A_BOLD | ColorPair(Green,Black);
CRT_colors[PROCESS_TREE] = ColorPair(Cyan,Black);
CRT_colors[PROCESS_R_STATE] = ColorPair(Green,Black);
CRT_colors[PROCESS_HIGH_PRIORITY] = ColorPair(Red,Black);
CRT_colors[PROCESS_LOW_PRIORITY] = ColorPair(Red,Black);
CRT_colors[BAR_BORDER] = A_BOLD | ColorPair(Green,Black);
CRT_colors[BAR_SHADOW] = ColorPair(Cyan,Black);
CRT_colors[SWAP] = ColorPair(Red,Black);
CRT_colors[GRAPH_1] = A_BOLD | ColorPair(Red,Black);
CRT_colors[GRAPH_2] = ColorPair(Red,Black);
CRT_colors[GRAPH_3] = A_BOLD | ColorPair(Yellow,Black);
CRT_colors[GRAPH_4] = A_BOLD | ColorPair(Green,Black);
CRT_colors[GRAPH_5] = ColorPair(Green,Black);
CRT_colors[GRAPH_6] = ColorPair(Cyan,Black);
CRT_colors[GRAPH_7] = A_BOLD | ColorPair(Blue,Black);
CRT_colors[GRAPH_8] = ColorPair(Blue,Black);
CRT_colors[GRAPH_9] = A_BOLD | ColorPair(Black,Black);
CRT_colors[MEMORY_USED] = ColorPair(Green,Black);
CRT_colors[MEMORY_BUFFERS] = ColorPair(Blue,Black);
CRT_colors[MEMORY_CACHE] = ColorPair(Yellow,Black);
CRT_colors[LOAD_AVERAGE_FIFTEEN] = ColorPair(Green,Black);
CRT_colors[LOAD_AVERAGE_FIVE] = ColorPair(Green,Black);
CRT_colors[LOAD_AVERAGE_ONE] = A_BOLD | ColorPair(Green,Black);
CRT_colors[LOAD] = A_BOLD;
CRT_colors[HELP_BOLD] = A_BOLD | ColorPair(Cyan,Black);
CRT_colors[CPU_NICE] = ColorPair(Blue,Black);
CRT_colors[CPU_NORMAL] = ColorPair(Green,Black);
CRT_colors[CPU_KERNEL] = ColorPair(Red,Black);
CRT_colors[CLOCK] = A_BOLD;
CRT_colors[CHECK_BOX] = ColorPair(Green,Black);
CRT_colors[CHECK_MARK] = A_BOLD | ColorPair(Green,Black);
CRT_colors[CHECK_TEXT] = ColorPair(Cyan,Black);
} else {
/* Default */
CRT_colors[RESET_COLOR] = ColorPair(White,Black);
CRT_colors[DEFAULT_COLOR] = ColorPair(White,Black);
CRT_colors[FUNCTION_BAR] = ColorPair(Black,Cyan);
CRT_colors[FUNCTION_KEY] = ColorPair(White,Black);
CRT_colors[PANEL_HEADER_FOCUS] = ColorPair(Black,Green);
CRT_colors[PANEL_HEADER_UNFOCUS] = ColorPair(Black,Green);
CRT_colors[PANEL_HIGHLIGHT_FOCUS] = ColorPair(Black,Cyan);
CRT_colors[PANEL_HIGHLIGHT_UNFOCUS] = ColorPair(Black,White);
CRT_colors[FAILED_SEARCH] = ColorPair(Red,Cyan);
CRT_colors[UPTIME] = A_BOLD | ColorPair(Cyan,Black);
CRT_colors[LARGE_NUMBER] = A_BOLD | ColorPair(Red,Black);
CRT_colors[METER_TEXT] = ColorPair(Cyan,Black);
CRT_colors[METER_VALUE] = A_BOLD | ColorPair(Cyan,Black);
CRT_colors[LED_COLOR] = ColorPair(Green,Black);
CRT_colors[TASKS_RUNNING] = A_BOLD | ColorPair(Green,Black);
CRT_colors[PROCESS] = A_NORMAL;
CRT_colors[PROCESS_SHADOW] = A_BOLD | ColorPair(Black,Black);
CRT_colors[PROCESS_TAG] = A_BOLD | ColorPair(Yellow,Black);
CRT_colors[PROCESS_MEGABYTES] = ColorPair(Cyan,Black);
CRT_colors[PROCESS_BASENAME] = A_BOLD | ColorPair(Cyan,Black);
CRT_colors[PROCESS_TREE] = ColorPair(Cyan,Black);
CRT_colors[PROCESS_R_STATE] = ColorPair(Green,Black);
CRT_colors[PROCESS_HIGH_PRIORITY] = ColorPair(Red,Black);
CRT_colors[PROCESS_LOW_PRIORITY] = ColorPair(Red,Black);
CRT_colors[BAR_BORDER] = A_BOLD;
CRT_colors[BAR_SHADOW] = A_BOLD | ColorPair(Black,Black);
CRT_colors[SWAP] = ColorPair(Red,Black);
CRT_colors[GRAPH_1] = A_BOLD | ColorPair(Red,Black);
CRT_colors[GRAPH_2] = ColorPair(Red,Black);
CRT_colors[GRAPH_3] = A_BOLD | ColorPair(Yellow,Black);
CRT_colors[GRAPH_4] = A_BOLD | ColorPair(Green,Black);
CRT_colors[GRAPH_5] = ColorPair(Green,Black);
CRT_colors[GRAPH_6] = ColorPair(Cyan,Black);
CRT_colors[GRAPH_7] = A_BOLD | ColorPair(Blue,Black);
CRT_colors[GRAPH_8] = ColorPair(Blue,Black);
CRT_colors[GRAPH_9] = A_BOLD | ColorPair(Black,Black);
CRT_colors[MEMORY_USED] = ColorPair(Green,Black);
CRT_colors[MEMORY_BUFFERS] = ColorPair(Blue,Black);
CRT_colors[MEMORY_CACHE] = ColorPair(Yellow,Black);
CRT_colors[LOAD_AVERAGE_FIFTEEN] = A_BOLD | ColorPair(Black,Black);
CRT_colors[LOAD_AVERAGE_FIVE] = A_NORMAL;
CRT_colors[LOAD_AVERAGE_ONE] = A_BOLD;
CRT_colors[LOAD] = A_BOLD;
CRT_colors[HELP_BOLD] = A_BOLD | ColorPair(Cyan,Black);
CRT_colors[CPU_NICE] = ColorPair(Blue,Black);
CRT_colors[CPU_NORMAL] = ColorPair(Green,Black);
CRT_colors[CPU_KERNEL] = ColorPair(Red,Black);
CRT_colors[CLOCK] = A_BOLD;
CRT_colors[CHECK_BOX] = ColorPair(Cyan,Black);
CRT_colors[CHECK_MARK] = A_BOLD;
CRT_colors[CHECK_TEXT] = A_NORMAL;
}
}

112
CRT.h Normal file
View File

@ -0,0 +1,112 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_CRT
#define HEADER_CRT
/*
htop - CRT.h
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include <curses.h>
#include <signal.h>
#include <stdlib.h>
#include <stdbool.h>
#include "String.h"
#include "debug.h"
#define COLORSCHEME_DEFAULT 0
#define COLORSCHEME_MONOCHROME 1
#define COLORSCHEME_BLACKONWHITE 2
#define COLORSCHEME_BLACKONWHITE2 3
#define COLORSCHEME_MIDNIGHT 4
#define COLORSCHEME_BLACKNIGHT 5
//#link curses
bool CRT_hasColors;
typedef enum ColorElements_ {
RESET_COLOR,
DEFAULT_COLOR,
FUNCTION_BAR,
FUNCTION_KEY,
FAILED_SEARCH,
PANEL_HEADER_FOCUS,
PANEL_HEADER_UNFOCUS,
PANEL_HIGHLIGHT_FOCUS,
PANEL_HIGHLIGHT_UNFOCUS,
LARGE_NUMBER,
METER_TEXT,
METER_VALUE,
LED_COLOR,
UPTIME,
TASKS_TOTAL,
TASKS_RUNNING,
SWAP,
PROCESS,
PROCESS_SHADOW,
PROCESS_TAG,
PROCESS_MEGABYTES,
PROCESS_TREE,
PROCESS_R_STATE,
PROCESS_BASENAME,
PROCESS_HIGH_PRIORITY,
PROCESS_LOW_PRIORITY,
BAR_BORDER,
BAR_SHADOW,
GRAPH_1,
GRAPH_2,
GRAPH_3,
GRAPH_4,
GRAPH_5,
GRAPH_6,
GRAPH_7,
GRAPH_8,
GRAPH_9,
MEMORY_USED,
MEMORY_BUFFERS,
MEMORY_CACHE,
LOAD,
LOAD_AVERAGE_FIFTEEN,
LOAD_AVERAGE_FIVE,
LOAD_AVERAGE_ONE,
CHECK_BOX,
CHECK_MARK,
CHECK_TEXT,
CLOCK,
CPU_NICE,
CPU_NORMAL,
CPU_KERNEL,
HELP_BOLD,
LAST_COLORELEMENT
} ColorElements;
extern int CRT_colors[LAST_COLORELEMENT];
extern int CRT_colorScheme;
extern int CRT_delay;
void CRT_init();
void CRT_done();
int CRT_readKey();
void CRT_handleSIGSEGV(int signal);
void CRT_handleSIGTERM(int signal);
void CRT_setColors(int colorScheme);
void CRT_enableDelay();
void CRT_disableDelay();
#endif

134
CategoriesListBox.c Normal file
View File

@ -0,0 +1,134 @@
#include "CategoriesListBox.h"
#include "AvailableMetersListBox.h"
#include "MetersListBox.h"
#include "DisplayOptionsListBox.h"
#include "ColumnsListBox.h"
#include "ColorsListBox.h"
#include "AvailableColumnsListBox.h"
#include "ListBox.h"
#include "debug.h"
#include <assert.h>
/*{
typedef struct CategoriesListBox_ {
ListBox super;
Settings* settings;
ScreenManager* scr;
} CategoriesListBox;
}*/
/* private property */
char* MetersFunctions[10] = {" ", " ", " ", "Type ", " ", " ", "MoveUp", "MoveDn", "Remove", "Done "};
/* private property */
char* AvailableMetersFunctions[10] = {" ", " ", " ", " ", "Add L ", "Add R ", " ", " ", " ", "Done "};
/* private property */
char* DisplayOptionsFunctions[10] = {" ", " ", " ", " ", " ", " ", " ", " ", " ", "Done "};
/* private property */
char* ColumnsFunctions[10] = {" ", " ", " ", " ", " ", " ", "MoveUp", "MoveDn", "Remove", "Done "};
/* private property */
char* ColorsFunctions[10] = {" ", " ", " ", " ", " ", " ", " ", " ", " ", "Done "};
/* private property */
char* AvailableColumnsFunctions[10] = {" ", " ", " ", " ", "Add ", " ", " ", " ", " ", "Done "};
CategoriesListBox* CategoriesListBox_new(Settings* settings, ScreenManager* scr) {
CategoriesListBox* this = (CategoriesListBox*) malloc(sizeof(CategoriesListBox));
ListBox* super = (ListBox*) this;
ListBox_init(super, 1, 1, 1, 1, LISTITEM_CLASS, true);
((Object*)this)->delete = CategoriesListBox_delete;
this->settings = settings;
this->scr = scr;
super->eventHandler = CategoriesListBox_eventHandler;
ListBox_setHeader(super, "Setup");
ListBox_add(super, (Object*) ListItem_new("Meters", 0));
ListBox_add(super, (Object*) ListItem_new("Display options", 0));
ListBox_add(super, (Object*) ListItem_new("Colors", 0));
ListBox_add(super, (Object*) ListItem_new("Columns", 0));
return this;
}
void CategoriesListBox_delete(Object* object) {
ListBox* super = (ListBox*) object;
CategoriesListBox* this = (CategoriesListBox*) object;
ListBox_done(super);
free(this);
}
HandlerResult CategoriesListBox_eventHandler(ListBox* super, int ch) {
CategoriesListBox* this = (CategoriesListBox*) super;
HandlerResult result = IGNORED;
int previous = ListBox_getSelectedIndex(super);
switch (ch) {
case KEY_UP:
case KEY_DOWN:
case KEY_NPAGE:
case KEY_PPAGE:
case KEY_HOME:
case KEY_END: {
ListBox_onKey(super, ch);
int selected = ListBox_getSelectedIndex(super);
if (previous != selected) {
int size = ScreenManager_size(this->scr);
for (int i = 1; i < size; i++)
ScreenManager_remove(this->scr, 1);
switch (selected) {
case 0:
CategoriesListBox_makeMetersPage(this);
break;
case 1:
CategoriesListBox_makeDisplayOptionsPage(this);
break;
case 2:
CategoriesListBox_makeColorsPage(this);
break;
case 3:
CategoriesListBox_makeColumnsPage(this);
break;
}
}
result = HANDLED;
}
}
return result;
}
void CategoriesListBox_makeMetersPage(CategoriesListBox* this) {
ListBox* lbLeftMeters = (ListBox*) MetersListBox_new(this->settings, "Left column", this->settings->header->leftMeters, this->scr);
ListBox* lbRightMeters = (ListBox*) MetersListBox_new(this->settings, "Right column", this->settings->header->rightMeters, this->scr);
ListBox* lbAvailableMeters = (ListBox*) AvailableMetersListBox_new(this->settings, lbLeftMeters, lbRightMeters, this->scr);
ScreenManager_add(this->scr, lbLeftMeters, FunctionBar_new(10, MetersFunctions, NULL, NULL), 20);
ScreenManager_add(this->scr, lbRightMeters, FunctionBar_new(10, MetersFunctions, NULL, NULL), 20);
ScreenManager_add(this->scr, lbAvailableMeters, FunctionBar_new(10, AvailableMetersFunctions, NULL, NULL), -1);
}
void CategoriesListBox_makeDisplayOptionsPage(CategoriesListBox* this) {
ListBox* lbDisplayOptions = (ListBox*) DisplayOptionsListBox_new(this->settings, this->scr);
ScreenManager_add(this->scr, lbDisplayOptions, FunctionBar_new(10, DisplayOptionsFunctions, NULL, NULL), -1);
}
void CategoriesListBox_makeColorsPage(CategoriesListBox* this) {
ListBox* lbColors = (ListBox*) ColorsListBox_new(this->settings, this->scr);
ScreenManager_add(this->scr, lbColors, FunctionBar_new(10, ColorsFunctions, NULL, NULL), -1);
}
void CategoriesListBox_makeColumnsPage(CategoriesListBox* this) {
ListBox* lbColumns = (ListBox*) ColumnsListBox_new(this->settings, this->scr);
ListBox* lbAvailableColumns = (ListBox*) AvailableColumnsListBox_new(this->settings, lbColumns, this->scr);
ScreenManager_add(this->scr, lbColumns, FunctionBar_new(10, ColumnsFunctions, NULL, NULL), 20);
ScreenManager_add(this->scr, lbAvailableColumns, FunctionBar_new(10, AvailableColumnsFunctions, NULL, NULL), -1);
}

40
CategoriesListBox.h Normal file
View File

@ -0,0 +1,40 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_CategoriesListBox
#define HEADER_CategoriesListBox
#include "AvailableMetersListBox.h"
#include "MetersListBox.h"
#include "DisplayOptionsListBox.h"
#include "ListBox.h"
#include "debug.h"
#include <assert.h>
typedef struct CategoriesListBox_ {
ListBox super;
Settings* settings;
ScreenManager* scr;
} CategoriesListBox;
CategoriesListBox* CategoriesListBox_new(Settings* settings, ScreenManager* scr);
void CategoriesListBox_delete(Object* object);
HandlerResult CategoriesListBox_eventHandler(ListBox* super, int ch);
void CategoriesListBox_makeMetersPage(CategoriesListBox* this);
void CategoriesListBox_makeDisplayOptionsPage(CategoriesListBox* this);
void CategoriesListBox_makeColorsPage(CategoriesListBox* this);
void CategoriesListBox_makeColumnsPage(CategoriesListBox* this);
#endif

219
ChangeLog Normal file
View File

@ -0,0 +1,219 @@
What's new in version 0.6.1
* Included icon .desktop and desktop entry
(thanks to Peter Hyman)
* Added a check to make sure that a root-user htop closes
when its parent non-root terminal is closed.
(thanks to Ilya Evseev for the report)
* BUGFIX: does not crash anymore when $HOME is not set
(thanks to Henning Schild for the report)
What's new in version 0.6
* Configuration of columns merged into the Setup screen
* Integrated strace (press 's')
(thanks to Marinho Barcellos for the help)
* BUGFIX: some fixes, aided by Valgrind
(thanks to Wolfram Schlich for the report)
* BUGFIX: fixed bug when switching meter modes
(thanks to Eduardo Righes for the report)
* Show processes of a single user
* "SortBy" function now menu-based
* Improved mouse handling
* ...and on top of that reduced memory consumption!
What's new in version 0.5.4
* Color schemes
* -d flag, to configure delay between updates.
Note that the delay value is saved in ~/.htoprc.
* BUGFIX: Update of meters was halting after help screen.
(thanks to Matt Moore)
* BUGFIX: No longer display incorrect information
in first frame.
* BUGFIX: Fix auto-detection of /proc/stat,
correcting CPU usage information on multiprocessor
systems.
What's new in version 0.5.3
* Read new field "steal" on newer /proc/stat files
* Auto-detects format of /proc/stat, to cope
with patched 2.4 kernels which display 2.6-style
information (most notably those on RHEL 3)
(thanks to Fernando Dotta for the report)
* Support $HOME_ETC initiative
(see http://www.pld-linux.org/Docs/home-etc)
(thanks to Roman Barczynski for the tip)
* The configure script now tests for /proc, so
that it fails early on unsupported platforms
instead of during compilation/execution.
* Made presentation of the function keys in the
status bar consistent across views
(thanks to David Mathog for the report)
* Minor changes to make the codebase more friendly
to possible future ports
(thanks to Jari Aalto and David Mathog for the reports)
What's new in version 0.5.2
* BUGFIX: Correct display of user field
(thanks to Marcin Miroslaw for the report)
* Keyboard support improvements
(thanks to Aury Fink Filho for the report)
What's new in version 0.5.1
* BUGFIX: Correctly displays NPTL threads from
/proc/<pid>/task subdirectories
(thanks to Mike Pot for the report)
* BUGFIX: Fixes key handling on Signals listbox
(thanks to Ondrej Vlach)
* Renicing no longer displays temporary illegal values
(thanks to Ondrej Vlach)
* 'Hide userland threads' feature for NPTL threads
What's new in version 0.5
* Tree view
* New column, TIME (user + system time,
like in top, 'T' switches to "sort by time")
* Major reorganization of the underlying code of the
setup screen, to manage setup pages
* New setup page: Display options
* Hide kernel threads ('K' key)
* Colorized memory numbers
* Vastly improved support for monochromatic terminals
* Shadow processes that do not belong to user ('U' key)
* Header margin configuration accessible via setup screen
* Visual feedback on failing incremental search
* BUGFIX: fixed keyboard input issues on 64-bit machines
* BUGFIX: hopefully fixed the incorrect values
that show on status bars in some systems
* BUGFIX: doesn't mess with fields list anymore when
canceling after changing the number of items
* Uptime meter no longer says "1 days" ;)
What's new in version 0.4.1
* BUGFIX: compiles on 64-bit architectures again
(thanks to Bartosz Fenski for the report)
* BUGFIX: multi-processor support fixed on kernels 2.6
(thanks to Wolfram Schlich for the report)
What's new in version 0.4
* Support for multiple processors!
* Basic mouse support
* Modular header based on configurable meters;
supports 4 view modes: bar, text, LED, graph
* Uptime, load average meters
(thanks to Marc Calahan)
* Meters setup screen; should eventually evolve into a
general setup screen, with column setup, keybindings, etc.
* Thread hiding toggleable
(press 'T' to hide the nonstandard dotfiles in /proc)
* BUGFIX: Do not flicker screen on column configuration screen
* Clock and load average meters
(thanks to Marc Calahan)
* BUGFIX: numeric swap indicator was printing bogus value
* BUGFIX: internal fixes on ListBox widget
* Clear the bottom line when exiting
* Press "F3" during search to walk through the results
* Improved navigation on column configuration screen
* BUGFIX: fix segfault on kernels with restricted /proc
enabled
* BUGFIX: a few last-minute bugfixes in the setup UI
(thanks to Gaspare Bruno for the reports)
What's new in version 0.3.3
* Saves column and sorting configuration in ~/.htoprc
* Displays "hidden" threads on RedHat 9
(Thanks to Leonardo Godinho)
* BUGFIX: supports process names with spaces
(Thanks to Marc Calahan)
* BUGFIX: ...and parentheses :)
* BUGFIX: long process names overflowed RichString
(Thanks to Marc Calahan)
What's new in version 0.3.2
* Performance and memory usage improvements, aided by gprof
* BUGFIX: quite a few fixes, aided by Valgrind
* Header preview on column configuration screen
(Thanks to Marc Calahan)
What's new in version 0.3.1
* BUGFIX: crash fixes related to process list handling
(thanks to Marc Calahan)
* Man page
(thanks to Bartosz Fenski)
* Tag processes with the space bar
* Kill multiple process based on tag
* BUGFIX: corrected processing order of updates in list
* Screen refresh function on Ctrl-L
* Large numbers are shown in MB/GB notation in order to fit screen
(thanks to Marc Calahan)
* Realtime priority is correctly displayed
(thanks to Marc Calahan)
* Preliminary support for configurable columns, with 'C'
(thanks to Marc Calahan)
-- not all columns display properly yet
What's new in version 0.3
* BUGFIX: no dirt left on screen on horizontal scrolling
* Signal selection on "kill" command
* Color-coding for users, nice and process status
* "Follow" function
* Fully selectable sort order
* Function bar on last line
* Build system now uses autotools
What's new in version 0.2.1
* Sorting by process or memory usage ('P' and 'M', like top)
* Quicker default update (1.5 second, not yet configurable)
* Now the order of the elements in the process list stay
'locked' for a while after you move the cursor to ease
selecting a process
* Corrected the installation instructions in README
(Thanks to Jeremy Eglen)
* Should now compile cleanly on Conectiva 9 and similar systems
(Thanks to Adriano Frare for the report)
* Friendlier Makefile
* Help screen ('h')
What's new in version 0.2
* Memory indicators in header now show used and total, in MB
* Preliminary support for sorting (CPU% only)
* Memory percentage field (resident memory / used memory)
* BUGFIX: identified source of spurious crashes
* Can search names containing numbers
(Thanks to Rafael Jeffman)
* Correctly calculates memory page size
(Thanks to Rafael Jeffman)
What's new in version 0.13
* Handles terminal resize
* Display all user names (not only those in /etc/passwd)
(Thanks to Julio Biason)
What's new in version 0.12
* Support for 2.6 kernels
* Uses terminal default colors as a background
What's new in version 0.11
* BUGFIX: does not crash when UID is not in /etc/passwd
What's new in version 0.1
* Everything!

56
CheckItem.c Normal file
View File

@ -0,0 +1,56 @@
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "CheckItem.h"
#include "Object.h"
#include "CRT.h"
#include "debug.h"
/*{
typedef struct CheckItem_ {
Object super;
char* text;
bool* value;
} CheckItem;
extern char* CHECKITEM_CLASS;
}*/
/* private property */
char* CHECKITEM_CLASS = "CheckItem";
CheckItem* CheckItem_new(char* text, bool* value) {
CheckItem* this = malloc(sizeof(CheckItem));
((Object*)this)->class = CHECKITEM_CLASS;
((Object*)this)->display = CheckItem_display;
((Object*)this)->delete = CheckItem_delete;
this->text = text;
this->value = value;
return this;
}
void CheckItem_delete(Object* cast) {
CheckItem* this = (CheckItem*)cast;
assert (this != NULL);
free(this->text);
free(this);
}
void CheckItem_display(Object* cast, RichString* out) {
CheckItem* this = (CheckItem*)cast;
assert (this != NULL);
RichString_write(out, CRT_colors[CHECK_BOX], "[");
if (*(this->value))
RichString_append(out, CRT_colors[CHECK_MARK], "x");
else
RichString_append(out, CRT_colors[CHECK_MARK], " ");
RichString_append(out, CRT_colors[CHECK_BOX], "] ");
RichString_append(out, CRT_colors[CHECK_TEXT], this->text);
}

33
CheckItem.h Normal file
View File

@ -0,0 +1,33 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_CheckItem
#define HEADER_CheckItem
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "Object.h"
#include "CRT.h"
#include "debug.h"
typedef struct CheckItem_ {
Object super;
char* text;
bool* value;
} CheckItem;
extern char* CHECKITEM_CLASS;
CheckItem* CheckItem_new(char* text, bool* value);
void CheckItem_delete(Object* cast);
void CheckItem_display(Object* cast, RichString* out);
#endif

54
ClockMeter.c Normal file
View File

@ -0,0 +1,54 @@
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "ClockMeter.h"
#include "Meter.h"
#include "ProcessList.h"
#include <curses.h>
#include <time.h>
#include "debug.h"
/*{
typedef struct ClockMeter_ ClockMeter;
struct ClockMeter_ {
Meter super;
ProcessList* pl;
char clock[10];
};
}*/
ClockMeter* ClockMeter_new() {
ClockMeter* this = malloc(sizeof(ClockMeter));
Meter_init((Meter*)this, String_copy("Clock"), String_copy("Time: "), 1);
((Meter*)this)->attributes[0] = CLOCK;
((Meter*)this)->setValues = ClockMeter_setValues;
((Object*)this)->display = ClockMeter_display;
((Meter*)this)->total = 24 * 60;
Meter_setMode((Meter*)this, TEXT);
return this;
}
void ClockMeter_setValues(Meter* cast) {
ClockMeter* this = (ClockMeter*) cast;
time_t t = time(NULL);
struct tm *lt = localtime(&t);
cast->values[0] = lt->tm_hour * 60 + lt->tm_min;
strftime(this->clock, 9, "%H:%M:%S", lt);
snprintf(cast->displayBuffer.c, 9, "%s", this->clock);
}
void ClockMeter_display(Object* cast, RichString* out) {
Meter* super = (Meter*) cast;
ClockMeter* this = (ClockMeter*) cast;
RichString_write(out, CRT_colors[super->attributes[0]], this->clock);
}

37
ClockMeter.h Normal file
View File

@ -0,0 +1,37 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_ClockMeter
#define HEADER_ClockMeter
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "Meter.h"
#include "ProcessList.h"
#include <curses.h>
#include <time.h>
#include "debug.h"
typedef struct ClockMeter_ ClockMeter;
struct ClockMeter_ {
Meter super;
ProcessList* pl;
char clock[10];
};
ClockMeter* ClockMeter_new();
void ClockMeter_setValues(Meter* cast);
void ClockMeter_display(Object* cast, RichString* out);
#endif

98
ColorsListBox.c Normal file
View File

@ -0,0 +1,98 @@
#include "CRT.h"
#include "ColorsListBox.h"
#include "ListBox.h"
#include "CheckItem.h"
#include "Settings.h"
#include "ScreenManager.h"
#include "debug.h"
#include <assert.h>
// TO ADD A NEW SCHEME:
// * Increment the size of bool check in ColorsListBox.h
// * Add the entry in the ColorSchemes array below in the file
// * Add a define in CRT.h that matches the order of the array
// * Add the colors in CRT_setColors
/*{
typedef struct ColorsListBox_ {
ListBox super;
Settings* settings;
ScreenManager* scr;
bool check[5];
} ColorsListBox;
}*/
/* private property */
static char* ColorSchemes[] = {
"Default",
"Monochromatic",
"Black on White",
"Light Terminal",
"MC",
"Black Night",
NULL
};
ColorsListBox* ColorsListBox_new(Settings* settings, ScreenManager* scr) {
ColorsListBox* this = (ColorsListBox*) malloc(sizeof(ColorsListBox));
ListBox* super = (ListBox*) this;
ListBox_init(super, 1, 1, 1, 1, CHECKITEM_CLASS, true);
((Object*)this)->delete = ColorsListBox_delete;
this->settings = settings;
this->scr = scr;
super->eventHandler = ColorsListBox_EventHandler;
ListBox_setHeader(super, "Colors");
for (int i = 0; ColorSchemes[i] != NULL; i++) {
ListBox_add(super, (Object*) CheckItem_new(String_copy(ColorSchemes[i]), &(this->check[i])));
this->check[i] = false;
}
this->check[settings->colorScheme] = true;
return this;
}
void ColorsListBox_delete(Object* object) {
ListBox* super = (ListBox*) object;
ColorsListBox* this = (ColorsListBox*) object;
ListBox_done(super);
free(this);
}
HandlerResult ColorsListBox_EventHandler(ListBox* super, int ch) {
ColorsListBox* this = (ColorsListBox*) super;
HandlerResult result = IGNORED;
int mark = ListBox_getSelectedIndex(super);
switch(ch) {
case 0x0a:
case 0x0d:
case KEY_ENTER:
case ' ':
for (int i = 0; ColorSchemes[i] != NULL; i++) {
this->check[i] = false;
}
this->check[mark] = true;
this->settings->colorScheme = mark;
result = HANDLED;
}
if (result == HANDLED) {
Header* header = this->settings->header;
CRT_setColors(mark);
ListBox* lbMenu = (ListBox*) TypedVector_get(this->scr->items, 0);
Header_draw(header);
RichString_setAttr(&(super->header), CRT_colors[PANEL_HEADER_FOCUS]);
RichString_setAttr(&(lbMenu->header), CRT_colors[PANEL_HEADER_UNFOCUS]);
ScreenManager_resize(this->scr, this->scr->x1, header->height, this->scr->x2, this->scr->y2);
}
return result;
}

32
ColorsListBox.h Normal file
View File

@ -0,0 +1,32 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_ColorsListBox
#define HEADER_ColorsListBox
#include "ListBox.h"
#include "CheckItem.h"
#include "Settings.h"
#include "ScreenManager.h"
#include "debug.h"
#include <assert.h>
typedef struct ColorsListBox_ {
ListBox super;
Settings* settings;
ScreenManager* scr;
bool check[5];
} ColorsListBox;
ColorsListBox* ColorsListBox_new(Settings* settings, ScreenManager* scr);
void ColorsListBox_delete(Object* object);
HandlerResult ColorsListBox_EventHandler(ListBox* super, int ch);
#endif

104
ColumnsListBox.c Normal file
View File

@ -0,0 +1,104 @@
#include "ColumnsListBox.h"
#include "ListBox.h"
#include "Settings.h"
#include "ScreenManager.h"
#include "debug.h"
#include <assert.h>
/*{
typedef struct ColumnsListBox_ {
ListBox super;
Settings* settings;
ScreenManager* scr;
} ColumnsListBox;
}*/
ColumnsListBox* ColumnsListBox_new(Settings* settings, ScreenManager* scr) {
ColumnsListBox* this = (ColumnsListBox*) malloc(sizeof(ColumnsListBox));
ListBox* super = (ListBox*) this;
ListBox_init(super, 1, 1, 1, 1, LISTITEM_CLASS, true);
((Object*)this)->delete = ColumnsListBox_delete;
this->settings = settings;
this->scr = scr;
super->eventHandler = ColumnsListBox_eventHandler;
ListBox_setHeader(super, "Active Columns");
ProcessField* fields = this->settings->pl->fields;
for (; *fields; fields++) {
ListBox_add(super, (Object*) ListItem_new(Process_fieldNames[*fields], 0));
}
return this;
}
void ColumnsListBox_delete(Object* object) {
ListBox* super = (ListBox*) object;
ColumnsListBox* this = (ColumnsListBox*) object;
ListBox_done(super);
free(this);
}
void ColumnsListBox_update(ListBox* super) {
ColumnsListBox* this = (ColumnsListBox*) super;
int size = ListBox_getSize(super);
this->settings->changed = true;
// FIXME: this is crappily inefficient
free(this->settings->pl->fields);
this->settings->pl->fields = (ProcessField*) malloc(sizeof(ProcessField) * (size+1));
for (int i = 0; i < size; i++) {
char* text = ((ListItem*) ListBox_get(super, i))->value;
for (int j = 1; j <= LAST_PROCESSFIELD; j++) {
if (String_eq(text, Process_fieldNames[j])) {
this->settings->pl->fields[i] = j;
break;
}
}
}
this->settings->pl->fields[size] = 0;
}
HandlerResult ColumnsListBox_eventHandler(ListBox* super, int ch) {
int selected = ListBox_getSelectedIndex(super);
HandlerResult result = IGNORED;
int size = ListBox_getSize(super);
switch(ch) {
case KEY_F(7):
case '[':
case '-':
{
if (selected < size - 1)
ListBox_moveSelectedUp(super);
result = HANDLED;
break;
}
case KEY_F(8):
case ']':
case '+':
{
if (selected < size - 2)
ListBox_moveSelectedDown(super);
result = HANDLED;
break;
}
case KEY_F(9):
case KEY_DC:
{
if (selected < size - 1) {
ListBox_remove(super, selected);
}
result = HANDLED;
break;
}
}
if (result == HANDLED)
ColumnsListBox_update(super);
return result;
}

32
ColumnsListBox.h Normal file
View File

@ -0,0 +1,32 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_ColumnsListBox
#define HEADER_ColumnsListBox
#include "ListBox.h"
#include "Settings.h"
#include "ScreenManager.h"
#include "debug.h"
#include <assert.h>
typedef struct ColumnsListBox_ {
ListBox super;
Settings* settings;
TypedVector* columns;
ScreenManager* scr;
} ColumnsListBox;
ColumnsListBox* ColumnsListBox_new(Settings* settings, ScreenManager* scr);
void ColumnsListBox_delete(Object* object);
void ColumnsListBox_update(ListBox* super);
HandlerResult ColumnsListBox_eventHandler(ListBox* super, int ch);
#endif

187
DebugMemory.c Normal file
View File

@ -0,0 +1,187 @@
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "DebugMemory.h"
#undef strdup
#undef malloc
#undef realloc
#undef calloc
#undef free
/*{
typedef struct DebugMemoryItem_ DebugMemoryItem;
struct DebugMemoryItem_ {
void* data;
char* file;
int line;
DebugMemoryItem* next;
};
typedef struct DebugMemory_ {
DebugMemoryItem* first;
int allocations;
int deallocations;
int size;
FILE* file;
} DebugMemory;
}*/
/* private property */
DebugMemory* singleton = NULL;
void DebugMemory_new() {
if (singleton)
return;
singleton = malloc(sizeof(DebugMemory));
singleton->first = NULL;
singleton->allocations = 0;
singleton->deallocations = 0;
singleton->size = 0;
singleton->file = fopen("/tmp/htop-debug-alloc.txt", "w");
}
void* DebugMemory_malloc(int size, char* file, int line) {
void* data = malloc(size);
DebugMemory_registerAllocation(data, file, line);
fprintf(singleton->file, "%d\t%s:%d\n", size, file, line);
return data;
}
void* DebugMemory_calloc(int a, int b, char* file, int line) {
void* data = calloc(a, b);
DebugMemory_registerAllocation(data, file, line);
fprintf(singleton->file, "%d\t%s:%d\n", a*b, file, line);
return data;
}
void* DebugMemory_realloc(void* ptr, int size, char* file, int line) {
if (ptr != NULL)
DebugMemory_registerDeallocation(ptr, file, line);
void* data = realloc(ptr, size);
DebugMemory_registerAllocation(data, file, line);
fprintf(singleton->file, "%d\t%s:%d\n", size, file, line);
return data;
}
void* DebugMemory_strdup(char* str, char* file, int line) {
char* data = strdup(str);
DebugMemory_registerAllocation(data, file, line);
fprintf(singleton->file, "%d\t%s:%d\n", (int) strlen(str), file, line);
return data;
}
void DebugMemory_free(void* data, char* file, int line) {
DebugMemory_registerDeallocation(data, file, line);
free(data);
}
void DebugMemory_assertSize() {
if (!singleton->first) {
assert (singleton->size == 0);
}
DebugMemoryItem* walk = singleton->first;
int i = 0;
while (walk != NULL) {
i++;
walk = walk->next;
}
assert (i == singleton->size);
}
int DebugMemory_getBlockCount() {
if (!singleton->first) {
return 0;
}
DebugMemoryItem* walk = singleton->first;
int i = 0;
while (walk != NULL) {
i++;
walk = walk->next;
}
return i;
}
void DebugMemory_registerAllocation(void* data, char* file, int line) {
if (!singleton)
DebugMemory_new();
DebugMemory_assertSize();
DebugMemoryItem* item = (DebugMemoryItem*) malloc(sizeof(DebugMemoryItem));
item->data = data;
item->file = file;
item->line = line;
item->next = NULL;
int val = DebugMemory_getBlockCount();
if (singleton->first == NULL) {
assert (val == 0);
singleton->first = item;
} else {
DebugMemoryItem* walk = singleton->first;
while (true) {
if (walk->next == NULL) {
walk->next = item;
break;
}
walk = walk->next;
}
}
int nval = DebugMemory_getBlockCount();
assert(nval == val + 1);
singleton->allocations++;
singleton->size++;
DebugMemory_assertSize();
}
void DebugMemory_registerDeallocation(void* data, char* file, int line) {
assert(singleton);
assert(singleton->first);
DebugMemoryItem* walk = singleton->first;
DebugMemoryItem* prev = NULL;
int val = DebugMemory_getBlockCount();
while (walk != NULL) {
if (walk->data == data) {
if (prev == NULL) {
singleton->first = walk->next;
} else {
prev->next = walk->next;
}
free(walk);
assert(DebugMemory_getBlockCount() == val - 1);
singleton->deallocations++;
singleton->size--;
DebugMemory_assertSize();
return;
}
DebugMemoryItem* tmp = walk;
walk = walk->next;
prev = tmp;
}
DebugMemory_report();
fprintf(stderr, "Couldn't find allocation for memory freed at %s:%d\n", file, line);
assert(false);
}
void DebugMemory_report() {
assert(singleton);
DebugMemoryItem* walk = singleton->first;
int i = 0;
while (walk != NULL) {
i++;
fprintf(stderr, "%p %s:%d\n", walk->data, walk->file, walk->line);
walk = walk->next;
}
fprintf(stderr, "Total:\n");
fprintf(stderr, "%d allocations\n", singleton->allocations);
fprintf(stderr, "%d deallocations\n", singleton->deallocations);
fprintf(stderr, "%d size\n", singleton->size);
fprintf(stderr, "%d non-freed blocks\n", i);
fclose(singleton->file);
}

62
DebugMemory.h Normal file
View File

@ -0,0 +1,62 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_DebugMemory
#define HEADER_DebugMemory
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#undef strdup
#undef malloc
#undef realloc
#undef calloc
#undef free
typedef struct DebugMemoryItem_ DebugMemoryItem;
struct DebugMemoryItem_ {
void* data;
char* file;
int line;
DebugMemoryItem* next;
};
typedef struct DebugMemory_ {
DebugMemoryItem* first;
int allocations;
int deallocations;
int size;
FILE* file;
} DebugMemory;
void DebugMemory_new();
void* DebugMemory_malloc(int size, char* file, int line);
void* DebugMemory_calloc(int a, int b, char* file, int line);
void* DebugMemory_realloc(void* ptr, int size, char* file, int line);
void* DebugMemory_strdup(char* str, char* file, int line);
void DebugMemory_free(void* data, char* file, int line);
void DebugMemory_assertSize();
int DebugMemory_getBlockCount();
void DebugMemory_registerAllocation(void* data, char* file, int line);
void DebugMemory_registerDeallocation(void* data, char* file, int line);
void DebugMemory_report();
#endif

75
DisplayOptionsListBox.c Normal file
View File

@ -0,0 +1,75 @@
#include "DisplayOptionsListBox.h"
#include "ListBox.h"
#include "CheckItem.h"
#include "Settings.h"
#include "ScreenManager.h"
#include "debug.h"
#include <assert.h>
/*{
typedef struct DisplayOptionsListBox_ {
ListBox super;
Settings* settings;
ScreenManager* scr;
} DisplayOptionsListBox;
}*/
DisplayOptionsListBox* DisplayOptionsListBox_new(Settings* settings, ScreenManager* scr) {
DisplayOptionsListBox* this = (DisplayOptionsListBox*) malloc(sizeof(DisplayOptionsListBox));
ListBox* super = (ListBox*) this;
ListBox_init(super, 1, 1, 1, 1, CHECKITEM_CLASS, true);
((Object*)this)->delete = DisplayOptionsListBox_delete;
this->settings = settings;
this->scr = scr;
super->eventHandler = DisplayOptionsListBox_EventHandler;
ListBox_setHeader(super, "Display options");
ListBox_add(super, (Object*) CheckItem_new(String_copy("Tree view"), &(settings->pl->treeView)));
ListBox_add(super, (Object*) CheckItem_new(String_copy("Shadow other users' processes"), &(settings->pl->shadowOtherUsers)));
ListBox_add(super, (Object*) CheckItem_new(String_copy("Hide kernel threads"), &(settings->pl->hideKernelThreads)));
ListBox_add(super, (Object*) CheckItem_new(String_copy("Hide userland threads"), &(settings->pl->hideUserlandThreads)));
ListBox_add(super, (Object*) CheckItem_new(String_copy("Highlight program \"basename\""), &(settings->pl->highlightBaseName)));
ListBox_add(super, (Object*) CheckItem_new(String_copy("Highlight megabytes in memory counters"), &(settings->pl->highlightMegabytes)));
ListBox_add(super, (Object*) CheckItem_new(String_copy("Leave a margin around header"), &(settings->header->margin)));
return this;
}
void DisplayOptionsListBox_delete(Object* object) {
ListBox* super = (ListBox*) object;
DisplayOptionsListBox* this = (DisplayOptionsListBox*) object;
ListBox_done(super);
free(this);
}
HandlerResult DisplayOptionsListBox_EventHandler(ListBox* super, int ch) {
DisplayOptionsListBox* this = (DisplayOptionsListBox*) super;
HandlerResult result = IGNORED;
CheckItem* selected = (CheckItem*) ListBox_getSelected(super);
switch(ch) {
case 0x0a:
case 0x0d:
case KEY_ENTER:
case ' ':
*(selected->value) = ! *(selected->value);
result = HANDLED;
}
if (result == HANDLED) {
this->settings->changed = true;
Header* header = this->settings->header;
Header_calculateHeight(header);
Header_draw(header);
ScreenManager_resize(this->scr, this->scr->x1, header->height, this->scr->x2, this->scr->y2);
}
return result;
}

31
DisplayOptionsListBox.h Normal file
View File

@ -0,0 +1,31 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_DisplayOptionsListBox
#define HEADER_DisplayOptionsListBox
#include "ListBox.h"
#include "CheckItem.h"
#include "Settings.h"
#include "ScreenManager.h"
#include "debug.h"
#include <assert.h>
typedef struct DisplayOptionsListBox_ {
ListBox super;
Settings* settings;
ScreenManager* scr;
} DisplayOptionsListBox;
DisplayOptionsListBox* DisplayOptionsListBox_new(Settings* settings, ScreenManager* scr);
void DisplayOptionsListBox_delete(Object* object);
HandlerResult DisplayOptionsListBox_EventHandler(ListBox* super, int ch);
#endif

131
FunctionBar.c Normal file
View File

@ -0,0 +1,131 @@
/*
htop - FunctionBar.c
(C) 2004,2005 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "Object.h"
#include "FunctionBar.h"
#include "CRT.h"
#include "debug.h"
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <curses.h>
/*{
typedef struct FunctionBar_ {
Object super;
int size;
char** functions;
char** keys;
int* events;
bool staticData;
} FunctionBar;
extern char* FUNCTIONBAR_CLASS;
}*/
/* private property */
char* FUNCTIONBAR_CLASS = "FunctionBar";
/* private property */
static char* FunctionBar_FKeys[10] = {"F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10"};
/* private property */
static char* FunctionBar_FLabels[10] = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " "};
/* private property */
static int FunctionBar_FEvents[10] = {KEY_F(1), KEY_F(2), KEY_F(3), KEY_F(4), KEY_F(5), KEY_F(6), KEY_F(7), KEY_F(8), KEY_F(9), KEY_F(10)};
FunctionBar* FunctionBar_new(int size, char** functions, char** keys, int* events) {
FunctionBar* this = malloc(sizeof(FunctionBar));
((Object*) this)->class = FUNCTIONBAR_CLASS;
((Object*) this)->delete = FunctionBar_delete;
this->functions = functions;
this->size = size;
if (keys && events) {
this->staticData = false;
this->functions = malloc(sizeof(char*) * size);
this->keys = malloc(sizeof(char*) * size);
this->events = malloc(sizeof(int) * size);
for (int i = 0; i < size; i++) {
this->functions[i] = String_copy(functions[i]);
this->keys[i] = String_copy(keys[i]);
this->events[i] = events[i];
}
} else {
this->staticData = true;
this->functions = functions ? functions : FunctionBar_FLabels;
this->keys = FunctionBar_FKeys;
this->events = FunctionBar_FEvents;
assert((!functions) || this->size == 10);
}
return this;
}
void FunctionBar_delete(Object* cast) {
FunctionBar* this = (FunctionBar*) cast;
if (!this->staticData) {
for (int i = 0; i < this->size; i++) {
free(this->functions[i]);
free(this->keys[i]);
}
free(this->functions);
free(this->keys);
free(this->events);
}
free(this);
}
void FunctionBar_setLabel(FunctionBar* this, int event, char* text) {
assert(!this->staticData);
for (int i = 0; i < this->size; i++) {
if (this->events[i] == event) {
free(this->functions[i]);
this->functions[i] = String_copy(text);
break;
}
}
}
void FunctionBar_draw(FunctionBar* this, char* buffer) {
FunctionBar_drawAttr(this, buffer, CRT_colors[FUNCTION_BAR]);
}
void FunctionBar_drawAttr(FunctionBar* this, char* buffer, int attr) {
attrset(CRT_colors[FUNCTION_BAR]);
mvhline(LINES-1, 0, ' ', COLS);
int x = 0;
for (int i = 0; i < this->size; i++) {
attrset(CRT_colors[FUNCTION_KEY]);
mvaddstr(LINES-1, x, this->keys[i]);
x += strlen(this->keys[i]);
attrset(CRT_colors[FUNCTION_BAR]);
mvaddstr(LINES-1, x, this->functions[i]);
x += strlen(this->functions[i]);
}
if (buffer != NULL) {
attrset(attr);
mvaddstr(LINES-1, x, buffer);
}
attrset(CRT_colors[RESET_COLOR]);
}
int FunctionBar_synthesizeEvent(FunctionBar* this, int pos) {
int x = 0;
for (int i = 0; i < this->size; i++) {
x += strlen(this->keys[i]);
x += strlen(this->functions[i]);
if (pos < x) {
return this->events[i];
}
}
return ERR;
}

47
FunctionBar.h Normal file
View File

@ -0,0 +1,47 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_FunctionBar
#define HEADER_FunctionBar
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "Object.h"
#include "CRT.h"
#include "debug.h"
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <curses.h>
typedef struct FunctionBar_ {
Object super;
int size;
char** functions;
char** keys;
int* events;
bool staticData;
} FunctionBar;
extern char* FUNCTIONBAR_CLASS;
FunctionBar* FunctionBar_new(int size, char** functions, char** keys, int* events);
void FunctionBar_delete(Object* this);
void FunctionBar_draw(FunctionBar* this, char* buffer);
void FunctionBar_setLabel(FunctionBar* this, int event, char* text);
void FunctionBar_drawAttr(FunctionBar* this, char* buffer, int attr);
int FunctionBar_synthesizeEvent(FunctionBar* this, int pos);
#endif

140
Hashtable.c Normal file
View File

@ -0,0 +1,140 @@
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "Hashtable.h"
#include <stdlib.h>
#include <stdbool.h>
#include "debug.h"
/*{
typedef struct Hashtable_ Hashtable;
typedef void(*Hashtable_PairFunction)(int, void*, void*);
typedef int(*Hashtable_HashAlgorithm)(Hashtable*, int);
typedef struct HashtableItem {
int key;
void* value;
struct HashtableItem* next;
} HashtableItem;
struct Hashtable_ {
int size;
HashtableItem** buckets;
int items;
Hashtable_HashAlgorithm hashAlgorithm;
bool owner;
};
}*/
HashtableItem* HashtableItem_new(int key, void* value) {
HashtableItem* this;
this = (HashtableItem*) malloc(sizeof(HashtableItem));
this->key = key;
this->value = value;
this->next = NULL;
return this;
}
Hashtable* Hashtable_new(int size, bool owner) {
Hashtable* this;
this = (Hashtable*) malloc(sizeof(Hashtable));
this->size = size;
this->buckets = (HashtableItem**) calloc(sizeof(HashtableItem*), size);
this->hashAlgorithm = Hashtable_hashAlgorithm;
this->owner = owner;
return this;
}
int Hashtable_hashAlgorithm(Hashtable* this, int key) {
return (key % this->size);
}
void Hashtable_delete(Hashtable* this) {
for (int i = 0; i < this->size; i++) {
HashtableItem* walk = this->buckets[i];
while (walk != NULL) {
if (this->owner)
free(walk->value);
HashtableItem* savedWalk = walk;
walk = savedWalk->next;
free(savedWalk);
}
}
free(this->buckets);
free(this);
}
inline int Hashtable_size(Hashtable* this) {
return this->items;
}
void Hashtable_put(Hashtable* this, int key, void* value) {
int index = this->hashAlgorithm(this, key);
HashtableItem** bucketPtr = &(this->buckets[index]);
while (true)
if (*bucketPtr == NULL) {
*bucketPtr = HashtableItem_new(key, value);
this->items++;
break;
} else if ((*bucketPtr)->key == key) {
if (this->owner)
free((*bucketPtr)->value);
(*bucketPtr)->value = value;
break;
} else
bucketPtr = &((*bucketPtr)->next);
}
void* Hashtable_remove(Hashtable* this, int key) {
int index = this->hashAlgorithm(this, key);
HashtableItem** bucketPtr = &(this->buckets[index]);
while (true)
if (*bucketPtr == NULL) {
return NULL;
break;
} else if ((*bucketPtr)->key == key) {
void* savedValue = (*bucketPtr)->value;
HashtableItem* savedNext = (*bucketPtr)->next;
free(*bucketPtr);
(*bucketPtr) = savedNext;
this->items--;
if (this->owner) {
free(savedValue);
return NULL;
} else {
return savedValue;
}
} else
bucketPtr = &((*bucketPtr)->next);
}
inline void* Hashtable_get(Hashtable* this, int key) {
int index = this->hashAlgorithm(this, key);
HashtableItem* bucketPtr = this->buckets[index];
while (true)
if (bucketPtr == NULL) {
return NULL;
} else if (bucketPtr->key == key) {
return bucketPtr->value;
} else
bucketPtr = bucketPtr->next;
}
void Hashtable_foreach(Hashtable* this, Hashtable_PairFunction f, void* userData) {
for (int i = 0; i < this->size; i++) {
HashtableItem* walk = this->buckets[i];
while (walk != NULL) {
f(walk->key, walk->value, userData);
walk = walk->next;
}
}
}

55
Hashtable.h Normal file
View File

@ -0,0 +1,55 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_Hashtable
#define HEADER_Hashtable
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include <stdlib.h>
#include <stdbool.h>
#include "debug.h"
typedef struct Hashtable_ Hashtable;
typedef void(*Hashtable_PairFunction)(int, void*, void*);
typedef int(*Hashtable_HashAlgorithm)(Hashtable*, int);
typedef struct HashtableItem {
int key;
void* value;
struct HashtableItem* next;
} HashtableItem;
struct Hashtable_ {
int size;
HashtableItem** buckets;
int items;
Hashtable_HashAlgorithm hashAlgorithm;
bool owner;
};
HashtableItem* HashtableItem_new(int key, void* value);
Hashtable* Hashtable_new(int size, bool owner);
int Hashtable_hashAlgorithm(Hashtable* this, int key);
void Hashtable_delete(Hashtable* this);
inline int Hashtable_size(Hashtable* this);
void Hashtable_put(Hashtable* this, int key, void* value);
void* Hashtable_remove(Hashtable* this, int key);
inline void* Hashtable_get(Hashtable* this, int key);
void Hashtable_foreach(Hashtable* this, Hashtable_PairFunction f, void* userData);
#endif

177
Header.c Normal file
View File

@ -0,0 +1,177 @@
/*
htop - Header.c
(C) 2004,2005 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "Header.h"
#include "CPUMeter.h"
#include "MemoryMeter.h"
#include "SwapMeter.h"
#include "LoadMeter.h"
#include "LoadAverageMeter.h"
#include "UptimeMeter.h"
#include "ClockMeter.h"
#include "TasksMeter.h"
#include "debug.h"
#include <assert.h>
/*{
typedef enum HeaderSide_ {
LEFT_HEADER,
RIGHT_HEADER
} HeaderSide;
typedef struct Header_ {
TypedVector* leftMeters;
TypedVector* rightMeters;
ProcessList* pl;
bool margin;
int height;
int pad;
} Header;
}*/
#ifndef MAX
#define MAX(a,b) ((a)>(b)?(a):(b))
#endif
Header* Header_new(ProcessList* pl) {
Header* this = malloc(sizeof(Header));
this->leftMeters = TypedVector_new(METER_CLASS, true, DEFAULT_SIZE);
this->rightMeters = TypedVector_new(METER_CLASS, true, DEFAULT_SIZE);
this->margin = true;
this->pl = pl;
return this;
}
void Header_delete(Header* this) {
TypedVector_delete(this->leftMeters);
TypedVector_delete(this->rightMeters);
free(this);
}
void Header_createMeter(Header* this, char* name, HeaderSide side) {
TypedVector* meters = side == LEFT_HEADER
? this->leftMeters
: this->rightMeters;
if (String_eq(name, "Swap")) {
TypedVector_add(meters, SwapMeter_new(this->pl));
} else if (String_eq(name, "Memory")) {
TypedVector_add(meters, MemoryMeter_new(this->pl));
} else if (String_eq(name, "Clock")) {
TypedVector_add(meters, ClockMeter_new(this->pl));
} else if (String_eq(name, "Load")) {
TypedVector_add(meters, LoadMeter_new(this->pl));
} else if (String_eq(name, "LoadAverage")) {
TypedVector_add(meters, LoadAverageMeter_new(this->pl));
} else if (String_eq(name, "Uptime")) {
TypedVector_add(meters, UptimeMeter_new(this->pl));
} else if (String_eq(name, "Tasks")) {
TypedVector_add(meters, TasksMeter_new(this->pl));
} else if (String_startsWith(name, "CPUAverage")) {
TypedVector_add(meters, CPUMeter_new(this->pl, 0));
} else if (String_startsWith(name, "CPU")) {
int num;
int ok = sscanf(name, "CPU(%d)", &num);
if (ok)
TypedVector_add(meters, CPUMeter_new(this->pl, num));
}
}
void Header_setMode(Header* this, int i, MeterMode mode, HeaderSide side) {
TypedVector* meters = side == LEFT_HEADER
? this->leftMeters
: this->rightMeters;
Meter* meter = (Meter*) TypedVector_get(meters, i);
Meter_setMode(meter, mode);
}
Meter* Header_getMeter(Header* this, int i, HeaderSide side) {
TypedVector* meters = side == LEFT_HEADER
? this->leftMeters
: this->rightMeters;
return (Meter*) TypedVector_get(meters, i);
}
int Header_size(Header* this, HeaderSide side) {
TypedVector* meters = side == LEFT_HEADER
? this->leftMeters
: this->rightMeters;
return TypedVector_size(meters);
}
char* Header_readMeterName(Header* this, int i, HeaderSide side) {
TypedVector* meters = side == LEFT_HEADER
? this->leftMeters
: this->rightMeters;
Meter* meter = (Meter*) TypedVector_get(meters, i);
return meter->name;
}
MeterMode Header_readMeterMode(Header* this, int i, HeaderSide side) {
TypedVector* meters = side == LEFT_HEADER
? this->leftMeters
: this->rightMeters;
Meter* meter = (Meter*) TypedVector_get(meters, i);
return meter->mode;
}
void Header_defaultMeters(Header* this) {
for (int i = 1; i <= this->pl->processorCount; i++) {
TypedVector_add(this->leftMeters, CPUMeter_new(this->pl, i));
}
TypedVector_add(this->leftMeters, MemoryMeter_new(this->pl));
TypedVector_add(this->leftMeters, SwapMeter_new(this->pl));
TypedVector_add(this->rightMeters, TasksMeter_new(this->pl));
TypedVector_add(this->rightMeters, LoadAverageMeter_new(this->pl));
TypedVector_add(this->rightMeters, UptimeMeter_new(this->pl));
}
void Header_draw(Header* this) {
int height = this->height;
int pad = this->pad;
attrset(CRT_colors[RESET_COLOR]);
for (int y = 0; y < height; y++) {
mvhline(y, 0, ' ', COLS);
}
for (int y = (pad / 2), i = 0; i < TypedVector_size(this->leftMeters); i++) {
Meter* meter = (Meter*) TypedVector_get(this->leftMeters, i);
meter->draw(meter, pad, y, COLS / 2 - (pad * 2 - 1) - 1);
y += meter->h;
}
for (int y = (pad / 2), i = 0; i < TypedVector_size(this->rightMeters); i++) {
Meter* meter = (Meter*) TypedVector_get(this->rightMeters, i);
meter->draw(meter, COLS / 2 + pad, y, COLS / 2 - (pad * 2 - 1) - 1);
y += meter->h;
}
}
int Header_calculateHeight(Header* this) {
int pad = this->margin ? 2 : 0;
int leftHeight = pad;
int rightHeight = pad;
for (int i = 0; i < TypedVector_size(this->leftMeters); i++) {
Meter* meter = (Meter*) TypedVector_get(this->leftMeters, i);
leftHeight += meter->h;
}
for (int i = 0; i < TypedVector_size(this->rightMeters); i++) {
Meter* meter = (Meter*) TypedVector_get(this->rightMeters, i);
rightHeight += meter->h;
}
this->pad = pad;
this->height = MAX(leftHeight, rightHeight);
return this->height;
}

62
Header.h Normal file
View File

@ -0,0 +1,62 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_Header
#define HEADER_Header
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "CPUMeter.h"
#include "MemoryMeter.h"
#include "SwapMeter.h"
#include "LoadMeter.h"
#include "LoadAverageMeter.h"
#include "UptimeMeter.h"
#include "ClockMeter.h"
#include "TasksMeter.h"
#include "debug.h"
#include <assert.h>
typedef enum HeaderSide_ {
LEFT_HEADER,
RIGHT_HEADER
} HeaderSide;
typedef struct Header_ {
TypedVector* leftMeters;
TypedVector* rightMeters;
ProcessList* pl;
bool margin;
int height;
int pad;
} Header;
Header* Header_new(ProcessList* pl);
void Header_delete(Header* this);
void Header_createMeter(Header* this, char* name, HeaderSide side);
void Header_setMode(Header* this, int i, MeterMode mode, HeaderSide side);
Meter* Header_getMeter(Header* this, int i, HeaderSide side);
int Header_size(Header* this, HeaderSide side);
char* Header_readMeterName(Header* this, int i, HeaderSide side);
MeterMode Header_readMeterMode(Header* this, int i, HeaderSide side);
void Header_defaultMeters(Header* this);
void Header_draw(Header* this);
int Header_calculateHeight(Header* this);
#endif

229
INSTALL Normal file
View File

@ -0,0 +1,229 @@
Copyright (C) 1994, 1995, 1996, 1999, 2000, 2001, 2002 Free Software
Foundation, Inc.
This file is free documentation; the Free Software Foundation gives
unlimited permission to copy, distribute and modify it.
Basic Installation
==================
These are generic installation instructions.
The `configure' shell script attempts to guess correct values for
various system-dependent variables used during compilation. It uses
those values to create a `Makefile' in each directory of the package.
It may also create one or more `.h' files containing system-dependent
definitions. Finally, it creates a shell script `config.status' that
you can run in the future to recreate the current configuration, and a
file `config.log' containing compiler output (useful mainly for
debugging `configure').
It can also use an optional file (typically called `config.cache'
and enabled with `--cache-file=config.cache' or simply `-C') that saves
the results of its tests to speed up reconfiguring. (Caching is
disabled by default to prevent problems with accidental use of stale
cache files.)
If you need to do unusual things to compile the package, please try
to figure out how `configure' could check whether to do them, and mail
diffs or instructions to the address given in the `README' so they can
be considered for the next release. If you are using the cache, and at
some point `config.cache' contains results you don't want to keep, you
may remove or edit it.
The file `configure.ac' (or `configure.in') is used to create
`configure' by a program called `autoconf'. You only need
`configure.ac' if you want to change it or regenerate `configure' using
a newer version of `autoconf'.
The simplest way to compile this package is:
1. `cd' to the directory containing the package's source code and type
`./configure' to configure the package for your system. If you're
using `csh' on an old version of System V, you might need to type
`sh ./configure' instead to prevent `csh' from trying to execute
`configure' itself.
Running `configure' takes awhile. While running, it prints some
messages telling which features it is checking for.
2. Type `make' to compile the package.
3. Optionally, type `make check' to run any self-tests that come with
the package.
4. Type `make install' to install the programs and any data files and
documentation.
5. You can remove the program binaries and object files from the
source code directory by typing `make clean'. To also remove the
files that `configure' created (so you can compile the package for
a different kind of computer), type `make distclean'. There is
also a `make maintainer-clean' target, but that is intended mainly
for the package's developers. If you use it, you may have to get
all sorts of other programs in order to regenerate files that came
with the distribution.
Compilers and Options
=====================
Some systems require unusual options for compilation or linking that
the `configure' script does not know about. Run `./configure --help'
for details on some of the pertinent environment variables.
You can give `configure' initial values for configuration parameters
by setting variables in the command line or in the environment. Here
is an example:
./configure CC=c89 CFLAGS=-O2 LIBS=-lposix
*Note Defining Variables::, for more details.
Compiling For Multiple Architectures
====================================
You can compile the package for more than one kind of computer at the
same time, by placing the object files for each architecture in their
own directory. To do this, you must use a version of `make' that
supports the `VPATH' variable, such as GNU `make'. `cd' to the
directory where you want the object files and executables to go and run
the `configure' script. `configure' automatically checks for the
source code in the directory that `configure' is in and in `..'.
If you have to use a `make' that does not support the `VPATH'
variable, you have to compile the package for one architecture at a
time in the source code directory. After you have installed the
package for one architecture, use `make distclean' before reconfiguring
for another architecture.
Installation Names
==================
By default, `make install' will install the package's files in
`/usr/local/bin', `/usr/local/man', etc. You can specify an
installation prefix other than `/usr/local' by giving `configure' the
option `--prefix=PATH'.
You can specify separate installation prefixes for
architecture-specific files and architecture-independent files. If you
give `configure' the option `--exec-prefix=PATH', the package will use
PATH as the prefix for installing programs and libraries.
Documentation and other data files will still use the regular prefix.
In addition, if you use an unusual directory layout you can give
options like `--bindir=PATH' to specify different values for particular
kinds of files. Run `configure --help' for a list of the directories
you can set and what kinds of files go in them.
If the package supports it, you can cause programs to be installed
with an extra prefix or suffix on their names by giving `configure' the
option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'.
Optional Features
=================
Some packages pay attention to `--enable-FEATURE' options to
`configure', where FEATURE indicates an optional part of the package.
They may also pay attention to `--with-PACKAGE' options, where PACKAGE
is something like `gnu-as' or `x' (for the X Window System). The
`README' should mention any `--enable-' and `--with-' options that the
package recognizes.
For packages that use the X Window System, `configure' can usually
find the X include and library files automatically, but if it doesn't,
you can use the `configure' options `--x-includes=DIR' and
`--x-libraries=DIR' to specify their locations.
Specifying the System Type
==========================
There may be some features `configure' cannot figure out
automatically, but needs to determine by the type of machine the package
will run on. Usually, assuming the package is built to be run on the
_same_ architectures, `configure' can figure that out, but if it prints
a message saying it cannot guess the machine type, give it the
`--build=TYPE' option. TYPE can either be a short name for the system
type, such as `sun4', or a canonical name which has the form:
CPU-COMPANY-SYSTEM
where SYSTEM can have one of these forms:
OS KERNEL-OS
See the file `config.sub' for the possible values of each field. If
`config.sub' isn't included in this package, then this package doesn't
need to know the machine type.
If you are _building_ compiler tools for cross-compiling, you should
use the `--target=TYPE' option to select the type of system they will
produce code for.
If you want to _use_ a cross compiler, that generates code for a
platform different from the build platform, you should specify the
"host" platform (i.e., that on which the generated programs will
eventually be run) with `--host=TYPE'.
Sharing Defaults
================
If you want to set default values for `configure' scripts to share,
you can create a site shell script called `config.site' that gives
default values for variables like `CC', `cache_file', and `prefix'.
`configure' looks for `PREFIX/share/config.site' if it exists, then
`PREFIX/etc/config.site' if it exists. Or, you can set the
`CONFIG_SITE' environment variable to the location of the site script.
A warning: not all `configure' scripts look for a site script.
Defining Variables
==================
Variables not defined in a site shell script can be set in the
environment passed to `configure'. However, some packages may run
configure again during the build, and the customized values of these
variables may be lost. In order to avoid this problem, you should set
them in the `configure' command line, using `VAR=value'. For example:
./configure CC=/usr/local2/bin/gcc
will cause the specified gcc to be used as the C compiler (unless it is
overridden in the site shell script).
`configure' Invocation
======================
`configure' recognizes the following options to control how it
operates.
`--help'
`-h'
Print a summary of the options to `configure', and exit.
`--version'
`-V'
Print the version of Autoconf used to generate the `configure'
script, and exit.
`--cache-file=FILE'
Enable the cache: use and save the results of the tests in FILE,
traditionally `config.cache'. FILE defaults to `/dev/null' to
disable caching.
`--config-cache'
`-C'
Alias for `--cache-file=config.cache'.
`--quiet'
`--silent'
`-q'
Do not print messages saying which checks are being made. To
suppress all normal output, redirect it to `/dev/null' (any error
messages will still be shown).
`--srcdir=DIR'
Look for the package's source code in directory DIR. Usually
`configure' can determine that directory automatically.
`configure' also accepts some other, not widely useful, options. Run
`configure --help' for more details.

353
ListBox.c Normal file
View File

@ -0,0 +1,353 @@
/*
htop - ListBox.c
(C) 2004,2005 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "Object.h"
#include "ListBox.h"
#include "TypedVector.h"
#include "CRT.h"
#include "RichString.h"
#include <math.h>
#include <stdbool.h>
#include "debug.h"
#include <assert.h>
#include <curses.h>
//#link curses
/*{
typedef struct ListBox_ ListBox;
typedef enum HandlerResult_ {
HANDLED,
IGNORED,
BREAK_LOOP
} HandlerResult;
typedef HandlerResult(*ListBox_EventHandler)(ListBox*, int);
struct ListBox_ {
Object super;
int x, y, w, h;
WINDOW* window;
TypedVector* items;
int selected;
int scrollV, scrollH;
int oldSelected;
bool needsRedraw;
RichString header;
ListBox_EventHandler eventHandler;
};
extern char* LISTBOX_CLASS;
}*/
#ifndef MIN
#define MIN(a,b) ((a)<(b)?(a):(b))
#endif
#ifndef MAX
#define MAX(a,b) ((a)>(b)?(a):(b))
#endif
/* private property */
char* LISTBOX_CLASS = "ListBox";
ListBox* ListBox_new(int x, int y, int w, int h, char* type, bool owner) {
ListBox* this;
this = malloc(sizeof(ListBox));
ListBox_init(this, x, y, w, h, type, owner);
return this;
}
void ListBox_delete(Object* cast) {
ListBox* this = (ListBox*)cast;
ListBox_done(this);
free(this);
}
void ListBox_init(ListBox* this, int x, int y, int w, int h, char* type, bool owner) {
Object* super = (Object*) this;
super->class = LISTBOX_CLASS;
super->delete = ListBox_delete;
this->x = x;
this->y = y;
this->w = w;
this->h = h;
this->eventHandler = NULL;
this->items = TypedVector_new(type, owner, DEFAULT_SIZE);
this->scrollV = 0;
this->scrollH = 0;
this->selected = 0;
this->oldSelected = 0;
this->needsRedraw = true;
this->header.len = 0;
}
void ListBox_done(ListBox* this) {
assert (this != NULL);
RichString_delete(this->header);
TypedVector_delete(this->items);
}
inline void ListBox_setRichHeader(ListBox* this, RichString header) {
assert (this != NULL);
if (this->header.len > 0) {
RichString_delete(this->header);
}
this->header = header;
this->needsRedraw = true;
}
inline void ListBox_setHeader(ListBox* this, char* header) {
ListBox_setRichHeader(this, RichString_quickString(CRT_colors[PANEL_HEADER_FOCUS], header));
}
void ListBox_setEventHandler(ListBox* this, ListBox_EventHandler eh) {
this->eventHandler = eh;
}
void ListBox_move(ListBox* this, int x, int y) {
assert (this != NULL);
this->x = x;
this->y = y;
this->needsRedraw = true;
}
void ListBox_resize(ListBox* this, int w, int h) {
assert (this != NULL);
if (this->header.len > 0)
h--;
this->w = w;
this->h = h;
this->needsRedraw = true;
}
void ListBox_prune(ListBox* this) {
assert (this != NULL);
TypedVector_prune(this->items);
this->scrollV = 0;
this->selected = 0;
this->oldSelected = 0;
this->needsRedraw = true;
}
void ListBox_add(ListBox* this, Object* o) {
assert (this != NULL);
TypedVector_add(this->items, o);
this->needsRedraw = true;
}
void ListBox_insert(ListBox* this, int i, Object* o) {
assert (this != NULL);
TypedVector_insert(this->items, i, o);
this->needsRedraw = true;
}
void ListBox_set(ListBox* this, int i, Object* o) {
assert (this != NULL);
TypedVector_set(this->items, i, o);
}
Object* ListBox_get(ListBox* this, int i) {
assert (this != NULL);
return TypedVector_get(this->items, i);
}
Object* ListBox_remove(ListBox* this, int i) {
assert (this != NULL);
this->needsRedraw = true;
Object* removed = TypedVector_remove(this->items, i);
if (this->selected > 0 && this->selected >= TypedVector_size(this->items))
this->selected--;
return removed;
}
Object* ListBox_getSelected(ListBox* this) {
assert (this != NULL);
return TypedVector_get(this->items, this->selected);
}
void ListBox_moveSelectedUp(ListBox* this) {
assert (this != NULL);
TypedVector_moveUp(this->items, this->selected);
if (this->selected > 0)
this->selected--;
}
void ListBox_moveSelectedDown(ListBox* this) {
assert (this != NULL);
TypedVector_moveDown(this->items, this->selected);
if (this->selected + 1 < TypedVector_size(this->items))
this->selected++;
}
int ListBox_getSelectedIndex(ListBox* this) {
assert (this != NULL);
return this->selected;
}
int ListBox_getSize(ListBox* this) {
assert (this != NULL);
return TypedVector_size(this->items);
}
void ListBox_setSelected(ListBox* this, int selected) {
assert (this != NULL);
selected = MAX(0, MIN(TypedVector_size(this->items) - 1, selected));
this->selected = selected;
}
void ListBox_draw(ListBox* this, bool focus) {
assert (this != NULL);
int first, last;
int itemCount = TypedVector_size(this->items);
int scrollH = this->scrollH;
int y = this->y; int x = this->x;
first = this->scrollV;
if (this->h > itemCount) {
last = this->scrollV + itemCount;
move(y + last, x + 0);
} else {
last = MIN(itemCount, this->scrollV + this->h);
}
if (this->selected < first) {
first = this->selected;
this->scrollV = first;
this->needsRedraw = true;
}
if (this->selected >= last) {
last = MIN(itemCount, this->selected + 1);
first = MAX(0, last - this->h);
this->scrollV = first;
this->needsRedraw = true;
}
assert(first >= 0);
assert(last <= itemCount);
if (this->header.len > 0) {
int attr = focus
? CRT_colors[PANEL_HEADER_FOCUS]
: CRT_colors[PANEL_HEADER_UNFOCUS];
attrset(attr);
mvhline(y, x, ' ', this->w);
if (scrollH < this->header.len) {
mvaddchnstr(y, x, this->header.chstr + scrollH,
MIN(this->header.len - scrollH, this->w));
}
attrset(CRT_colors[RESET_COLOR]);
y++;
}
int highlight = focus
? CRT_colors[PANEL_HIGHLIGHT_FOCUS]
: CRT_colors[PANEL_HIGHLIGHT_UNFOCUS];
if (this->needsRedraw) {
for(int i = first, j = 0; j < this->h && i < last; i++, j++) {
Object* itemObj = TypedVector_get(this->items, i);
RichString itemRef = RichString_new();
itemObj->display(itemObj, &itemRef);
int amt = MIN(itemRef.len - scrollH, this->w);
if (i == this->selected) {
attrset(highlight);
RichString_setAttr(&itemRef, highlight);
mvhline(y + j, x+0, ' ', this->w);
if (amt > 0)
mvaddchnstr(y+j, x+0, itemRef.chstr + scrollH, amt);
attrset(CRT_colors[RESET_COLOR]);
} else {
mvhline(y+j, x+0, ' ', this->w);
if (amt > 0)
mvaddchnstr(y+j, x+0, itemRef.chstr + scrollH, amt);
}
}
for (int i = y + (last - first); i < y + this->h; i++)
mvhline(i, x+0, ' ', this->w);
this->needsRedraw = false;
} else {
Object* oldObj = TypedVector_get(this->items, this->oldSelected);
RichString oldRef = RichString_new();
oldObj->display(oldObj, &oldRef);
Object* newObj = TypedVector_get(this->items, this->selected);
RichString newRef = RichString_new();
newObj->display(newObj, &newRef);
mvhline(y+ this->oldSelected - this->scrollV, x+0, ' ', this->w);
if (scrollH < oldRef.len)
mvaddchnstr(y+ this->oldSelected - this->scrollV, x+0, oldRef.chstr + this->scrollH, MIN(oldRef.len - scrollH, this->w));
attrset(highlight);
mvhline(y+this->selected - this->scrollV, x+0, ' ', this->w);
RichString_setAttr(&newRef, highlight);
if (scrollH < newRef.len)
mvaddchnstr(y+this->selected - this->scrollV, x+0, newRef.chstr + this->scrollH, MIN(newRef.len - scrollH, this->w));
attrset(CRT_colors[RESET_COLOR]);
}
this->oldSelected = this->selected;
move(0, 0);
}
void ListBox_onKey(ListBox* this, int key) {
assert (this != NULL);
switch (key) {
case KEY_DOWN:
if (this->selected + 1 < TypedVector_size(this->items))
this->selected++;
break;
case KEY_UP:
if (this->selected > 0)
this->selected--;
break;
case KEY_LEFT:
if (this->scrollH > 0) {
this->scrollH -= 5;
this->needsRedraw = true;
}
break;
case KEY_RIGHT:
this->scrollH += 5;
this->needsRedraw = true;
break;
case KEY_PPAGE:
this->selected -= this->h;
if (this->selected < 0)
this->selected = 0;
break;
case KEY_NPAGE:
this->selected += this->h;
int size = TypedVector_size(this->items);
if (this->selected >= size)
this->selected = size - 1;
break;
case KEY_HOME:
this->selected = 0;
break;
case KEY_END:
this->selected = TypedVector_size(this->items) - 1;
break;
}
}

101
ListBox.h Normal file
View File

@ -0,0 +1,101 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_ListBox
#define HEADER_ListBox
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "Object.h"
#include "TypedVector.h"
#include "CRT.h"
#include "RichString.h"
#include <math.h>
#include <sys/param.h>
#include <stdbool.h>
#include "debug.h"
#include <assert.h>
#include <curses.h>
//#link curses
typedef struct ListBox_ ListBox;
typedef enum HandlerResult_ {
HANDLED,
IGNORED,
BREAK_LOOP
} HandlerResult;
typedef HandlerResult(*ListBox_EventHandler)(ListBox*, int);
struct ListBox_ {
Object super;
int x, y, w, h;
WINDOW* window;
TypedVector* items;
int selected;
int scrollV, scrollH;
int oldSelected;
bool needsRedraw;
RichString header;
ListBox_EventHandler eventHandler;
};
extern char* LISTBOX_CLASS;
ListBox* ListBox_new(int x, int y, int w, int h, char* type, bool owner);
void ListBox_delete(Object* cast);
void ListBox_init(ListBox* this, int x, int y, int w, int h, char* type, bool owner);
void ListBox_done(ListBox* this);
void ListBox_setEventHandler(ListBox* this, ListBox_EventHandler eh);
void ListBox_setRichHeader(ListBox* this, RichString header);
void ListBox_setHeader(ListBox* this, char* header);
void ListBox_move(ListBox* this, int x, int y);
void ListBox_resize(ListBox* this, int w, int h);
void ListBox_prune(ListBox* this);
void ListBox_add(ListBox* this, Object* o);
void ListBox_insert(ListBox* this, int i, Object* o);
void ListBox_set(ListBox* this, int i, Object* o);
Object* ListBox_get(ListBox* this, int i);
Object* ListBox_remove(ListBox* this, int i);
Object* ListBox_getSelected(ListBox* this);
void ListBox_moveSelectedUp(ListBox* this);
void ListBox_moveSelectedDown(ListBox* this);
int ListBox_getSelectedIndex(ListBox* this);
int ListBox_getSize(ListBox* this);
void ListBox_setSelected(ListBox* this, int selected);
void ListBox_draw(ListBox* this, bool focus);
void ListBox_onKey(ListBox* this, int key);
#endif

72
ListItem.c Normal file
View File

@ -0,0 +1,72 @@
/*
htop - ListItem.c
(C) 2004,2005 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "ListItem.h"
#include "String.h"
#include "Object.h"
#include "RichString.h"
#include <string.h>
#include "debug.h"
/*{
typedef struct ListItem_ {
Object super;
char* value;
int key;
} ListItem;
extern char* LISTITEM_CLASS;
}*/
/* private property */
char* LISTITEM_CLASS = "ListItem";
ListItem* ListItem_new(char* value, int key) {
ListItem* this = malloc(sizeof(ListItem));
((Object*)this)->class = LISTITEM_CLASS;
((Object*)this)->display = ListItem_display;
((Object*)this)->delete = ListItem_delete;
((Object*)this)->compare = ListItem_compare;
this->value = String_copy(value);
this->key = key;
return this;
}
void ListItem_append(ListItem* this, char* text) {
char* buf = malloc(strlen(this->value) + strlen(text) + 1);
sprintf(buf, "%s%s", this->value, text);
free(this->value);
this->value = buf;
}
void ListItem_delete(Object* cast) {
ListItem* this = (ListItem*)cast;
free(this->value);
free(this);
}
void ListItem_display(Object* cast, RichString* out) {
ListItem* this = (ListItem*)cast;
assert (this != NULL);
int len = strlen(this->value)+1;
char buffer[len+1];
snprintf(buffer, len, "%s", this->value);
RichString_write(out, CRT_colors[DEFAULT_COLOR], buffer);
}
const char* ListItem_getRef(ListItem* this) {
return this->value;
}
int ListItem_compare(const Object* cast1, const Object* cast2) {
ListItem* obj1 = (ListItem*) cast1;
ListItem* obj2 = (ListItem*) cast2;
return strcmp(obj1->value, obj2->value);
}

39
ListItem.h Normal file
View File

@ -0,0 +1,39 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_ListItem
#define HEADER_ListItem
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "String.h"
#include "Object.h"
#include "RichString.h"
#include <string.h>
#include "debug.h"
typedef struct ListItem_ {
Object super;
char* value;
int key;
} ListItem;
extern char* LISTITEM_CLASS;
ListItem* ListItem_new(char* value, int key);
void ListItem_delete(Object* cast);
void ListItem_display(Object* cast, RichString* out);
void ListItem_append(ListItem* this, char* text);
const char* ListItem_getRef(ListItem* this);
int ListItem_compare(const Object*, const Object*);
#endif

71
LoadAverageMeter.c Normal file
View File

@ -0,0 +1,71 @@
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "LoadAverageMeter.h"
#include "Meter.h"
#include "ProcessList.h"
#include <curses.h>
#include "debug.h"
/*{
typedef struct LoadAverageMeter_ LoadAverageMeter;
struct LoadAverageMeter_ {
Meter super;
ProcessList* pl;
};
}*/
/* private property */
void LoadAverageMeter_scan(double* one, double* five, double* fifteen);
LoadAverageMeter* LoadAverageMeter_new() {
LoadAverageMeter* this = malloc(sizeof(LoadAverageMeter));
Meter_init((Meter*)this, String_copy("LoadAverage"), String_copy("Load average: "), 3);
((Meter*)this)->attributes[0] = LOAD_AVERAGE_FIFTEEN;
((Meter*)this)->attributes[1] = LOAD_AVERAGE_FIVE;
((Meter*)this)->attributes[2] = LOAD_AVERAGE_ONE;
((Object*)this)->display = LoadAverageMeter_display;
((Meter*)this)->setValues = LoadAverageMeter_setValues;
Meter_setMode((Meter*)this, TEXT);
LoadAverageMeter_scan(&((Meter*)this)->values[0], &((Meter*)this)->values[1], &((Meter*)this)->values[2]);
((Meter*)this)->total = 100.0;
return this;
}
/* private */
void LoadAverageMeter_scan(double* one, double* five, double* fifteen) {
int activeProcs, totalProcs, lastProc;
FILE *fd = fopen(PROCDIR "/loadavg", "r");
int read = fscanf(fd, "%lf %lf %lf %d/%d %d", one, five, fifteen,
&activeProcs, &totalProcs, &lastProc);
(void) read;
assert(read == 6);
fclose(fd);
}
void LoadAverageMeter_setValues(Meter* cast) {
LoadAverageMeter_scan(&cast->values[2], &cast->values[1], &cast->values[0]);
snprintf(cast->displayBuffer.c, 25, "%.2f/%.2f/%.2f", cast->values[2], cast->values[1], cast->values[0]);
}
void LoadAverageMeter_display(Object* cast, RichString* out) {
Meter* this = (Meter*)cast;
char buffer[20];
RichString_prune(out);
sprintf(buffer, "%.2f ", this->values[2]);
RichString_append(out, CRT_colors[LOAD_AVERAGE_ONE], buffer);
sprintf(buffer, "%.2f ", this->values[1]);
RichString_append(out, CRT_colors[LOAD_AVERAGE_FIVE], buffer);
sprintf(buffer, "%.2f ", this->values[0]);
RichString_append(out, CRT_colors[LOAD_AVERAGE_FIFTEEN], buffer);
}

37
LoadAverageMeter.h Normal file
View File

@ -0,0 +1,37 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_LoadAverageMeter
#define HEADER_LoadAverageMeter
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "Meter.h"
#include "ProcessList.h"
#include <curses.h>
#include "debug.h"
typedef struct LoadAverageMeter_ LoadAverageMeter;
struct LoadAverageMeter_ {
Meter super;
ProcessList* pl;
};
LoadAverageMeter* LoadAverageMeter_new();
void LoadAverageMeter_setValues(Meter* cast);
void LoadAverageMeter_display(Object* cast, RichString* out);
#endif

63
LoadMeter.c Normal file
View File

@ -0,0 +1,63 @@
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "LoadMeter.h"
#include "Meter.h"
#include "ProcessList.h"
#include "debug.h"
/*{
typedef struct LoadMeter_ LoadMeter;
struct LoadMeter_ {
Meter super;
ProcessList* pl;
};
}*/
LoadMeter* LoadMeter_new() {
LoadMeter* this = malloc(sizeof(LoadMeter));
Meter_init((Meter*)this, String_copy("Load"), String_copy("Load: "), 1);
((Meter*)this)->attributes[0] = LOAD;
((Meter*)this)->setValues = LoadMeter_setValues;
((Object*)this)->display = LoadMeter_display;
Meter_setMode((Meter*)this, GRAPH);
((Meter*)this)->total = 1.0;
return this;
}
/* private */
void LoadMeter_scan(double* one, double* five, double* fifteen) {
int activeProcs, totalProcs, lastProc;
FILE *fd = fopen(PROCDIR "/loadavg", "r");
int read = fscanf(fd, "%lf %lf %lf %d/%d %d", one, five, fifteen,
&activeProcs, &totalProcs, &lastProc);
(void) read;
assert(read == 6);
fclose(fd);
}
void LoadMeter_setValues(Meter* cast) {
double five, fifteen;
LoadMeter_scan(&cast->values[0], &five, &fifteen);
if (cast->values[0] > cast->total) {
cast->total = cast->values[0];
}
snprintf(cast->displayBuffer.c, 7, "%.2f", cast->values[0]);
}
void LoadMeter_display(Object* cast, RichString* out) {
LoadMeter* this = (LoadMeter*)cast;
char buffer[20];
RichString_prune(out);
sprintf(buffer, "%.2f ", ((Meter*)this)->values[0]);
RichString_append(out, CRT_colors[LOAD], buffer);
}

34
LoadMeter.h Normal file
View File

@ -0,0 +1,34 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_LoadMeter
#define HEADER_LoadMeter
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "Meter.h"
#include "ProcessList.h"
#include "debug.h"
typedef struct LoadMeter_ LoadMeter;
struct LoadMeter_ {
Meter super;
ProcessList* pl;
};
LoadMeter* LoadMeter_new();
void LoadMeter_setValues(Meter* cast);
void LoadMeter_display(Object* cast, RichString* out);
#endif

29
Makefile.am Normal file
View File

@ -0,0 +1,29 @@
bin_PROGRAMS = htop
dist_man_MANS = htop.1
EXTRA_DIST = $(dist_man_MANS) htop.desktop htop.png scripts/MakeHeader.py
applicationsdir = $(datadir)/applications
applications_DATA = htop.desktop
pixmapdir = $(datadir)/pixmaps
pixmap_DATA = htop.png
AM_CFLAGS = -pedantic -Wall -std=c99
AM_CPPFLAGS = -DSYSCONFDIR=\"$(sysconfdir)\"
htop_SOURCES = AvailableMetersListBox.c CategoriesListBox.c ClockMeter.c \
CPUMeter.c CRT.c DebugMemory.c DisplayOptionsListBox.c FunctionBar.c \
Hashtable.c Header.c htop.c ListBox.c ListItem.c LoadAverageMeter.c \
LoadMeter.c MemoryMeter.c Meter.c MetersListBox.c Object.c Process.c \
ProcessList.c RichString.c ScreenManager.c Settings.c SignalItem.c \
SignalsListBox.c String.c SwapMeter.c TasksMeter.c TypedVector.c \
UptimeMeter.c UsersTable.c AvailableMetersListBox.h CategoriesListBox.h \
ClockMeter.h config.h CPUMeter.h CRT.h debug.h DebugMemory.h \
DisplayOptionsListBox.h FunctionBar.h Hashtable.h Header.h htop.h ListBox.h \
ListItem.h LoadAverageMeter.h LoadMeter.h MemoryMeter.h Meter.h \
MetersListBox.h Object.h Process.h ProcessList.h RichString.h ScreenManager.h \
Settings.h SignalItem.h SignalsListBox.h String.h SwapMeter.h TasksMeter.h \
TypedVector.h UptimeMeter.h UsersTable.h CheckItem.c CheckItem.h \
ColorsListBox.c ColorsListBox.h TraceScreen.c TraceScreen.h \
AvailableColumnsListBox.c AvailableColumnsListBox.h ColumnsListBox.c \
ColumnsListBox.h

90
MemoryMeter.c Normal file
View File

@ -0,0 +1,90 @@
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "MemoryMeter.h"
#include "Meter.h"
#include "ProcessList.h"
#include <stdlib.h>
#include <curses.h>
#include <string.h>
#include <math.h>
#include <sys/param.h>
#include "debug.h"
#include <assert.h>
/*{
typedef struct MemoryMeter_ MemoryMeter;
struct MemoryMeter_ {
Meter super;
ProcessList* pl;
char* wideFormat;
int wideLimit;
};
}*/
MemoryMeter* MemoryMeter_new(ProcessList* pl) {
MemoryMeter* this = malloc(sizeof(MemoryMeter));
Meter_init((Meter*)this, String_copy("Memory"), String_copy("Mem"), 3);
((Meter*)this)->attributes[0] = MEMORY_USED;
((Meter*)this)->attributes[1] = MEMORY_BUFFERS;
((Meter*)this)->attributes[2] = MEMORY_CACHE;
((Meter*)this)->setValues = MemoryMeter_setValues;
((Object*)this)->display = MemoryMeter_display;
this->pl = pl;
Meter_setMode((Meter*)this, BAR);
this->wideFormat = "%6ldk ";
this->wideLimit = 22 + 8 * 4;
return this;
}
void MemoryMeter_setValues(Meter* cast) {
MemoryMeter* this = (MemoryMeter*)cast;
double totalMem = (double)this->pl->totalMem;
long int usedMem = this->pl->usedMem;
long int buffersMem = this->pl->buffersMem;
long int cachedMem = this->pl->cachedMem;
usedMem -= buffersMem + cachedMem;
cast->total = totalMem;
cast->values[0] = usedMem;
cast->values[1] = buffersMem;
cast->values[2] = cachedMem;
snprintf(cast->displayBuffer.c, 14, "%ld/%ldMB", usedMem / 1024, this->pl->totalMem / 1024);
}
void MemoryMeter_display(Object* cast, RichString* out) {
char buffer[50];
MemoryMeter* this = (MemoryMeter*)cast;
Meter* meter = (Meter*)cast;
int div = 1024; char* format = "%ldM ";
if (meter->w > this->wideLimit) {
div = 1; format = this->wideFormat;
}
long int totalMem = meter->total / div;
long int usedMem = meter->values[0] / div;
long int buffersMem = meter->values[1] / div;
long int cachedMem = meter->values[2] / div;
RichString_prune(out);
RichString_append(out, CRT_colors[METER_TEXT], ":");
sprintf(buffer, format, totalMem);
RichString_append(out, CRT_colors[METER_VALUE], buffer);
sprintf(buffer, format, usedMem);
RichString_append(out, CRT_colors[METER_TEXT], "used:");
RichString_append(out, CRT_colors[MEMORY_USED], buffer);
sprintf(buffer, format, buffersMem);
RichString_append(out, CRT_colors[METER_TEXT], "buffers:");
RichString_append(out, CRT_colors[MEMORY_BUFFERS], buffer);
sprintf(buffer, format, cachedMem);
RichString_append(out, CRT_colors[METER_TEXT], "cache:");
RichString_append(out, CRT_colors[MEMORY_CACHE], buffer);
}

42
MemoryMeter.h Normal file
View File

@ -0,0 +1,42 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_MemoryMeter
#define HEADER_MemoryMeter
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "Meter.h"
#include "ProcessList.h"
#include <stdlib.h>
#include <curses.h>
#include <string.h>
#include <math.h>
#include <sys/param.h>
#include "debug.h"
#include <assert.h>
typedef struct MemoryMeter_ MemoryMeter;
struct MemoryMeter_ {
Meter super;
ProcessList* pl;
char* wideFormat;
int wideLimit;
};
MemoryMeter* MemoryMeter_new(ProcessList* pl);
void MemoryMeter_setValues(Meter* cast);
void MemoryMeter_display(Object* cast, RichString* out);
#endif

350
Meter.c Normal file
View File

@ -0,0 +1,350 @@
/*
htop - Meter.c
(C) 2004,2005 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "Meter.h"
#include "Object.h"
#include "CRT.h"
#include "ListItem.h"
#include "String.h"
#include <stdlib.h>
#include <curses.h>
#include <string.h>
#include <math.h>
#include "debug.h"
#include <assert.h>
#define METER_BARBUFFER_LEN 128
#define METER_GRAPHBUFFER_LEN 128
/*{
typedef struct Meter_ Meter;
typedef void(*Meter_SetValues)(Meter*);
typedef void(*Meter_Draw)(Meter*, int, int, int);
typedef enum MeterMode_ {
UNSET,
BAR,
TEXT,
GRAPH,
LED,
LAST_METERMODE
} MeterMode;
struct Meter_ {
Object super;
int h;
int w;
Meter_Draw draw;
Meter_SetValues setValues;
int items;
int* attributes;
double* values;
double total;
char* caption;
char* name;
union {
RichString* rs;
char* c;
double* graph;
} displayBuffer;
MeterMode mode;
};
extern char* METER_CLASS;
}*/
#ifndef MIN
#define MIN(a,b) ((a)<(b)?(a):(b))
#endif
/* private property */
char* METER_CLASS = "Meter";
/* private */
char* Meter_ledDigits[3][10] = {
{ " __ "," "," __ "," __ "," "," __ "," __ "," __ "," __ "," __ "},
{ "| |"," |"," __|"," __|","|__|","|__ ","|__ "," |","|__|","|__|"},
{ "|__|"," |","|__ "," __|"," |"," __|","|__|"," |","|__|"," __|"},
};
/* private property */
char Meter_barCharacters[] = "|#*@$%&";
/* private property */
static RichString Meter_stringBuffer;
Meter* Meter_new(char* name, char* caption, int items) {
Meter* this = malloc(sizeof(Meter));
Meter_init(this, name, caption, items);
return this;
}
void Meter_init(Meter* this, char* name, char* caption, int items) {
((Object*)this)->delete = Meter_delete;
((Object*)this)->class = METER_CLASS;
this->items = items;
this->name = name;
this->caption = caption;
this->attributes = malloc(sizeof(int) * items);
this->values = malloc(sizeof(double) * items);
this->displayBuffer.c = NULL;
this->mode = UNSET;
this->h = 0;
}
void Meter_delete(Object* cast) {
Meter* this = (Meter*) cast;
assert (this != NULL);
Meter_done(this);
free(this);
}
/* private */
void Meter_freeBuffer(Meter* this) {
switch (this->mode) {
case BAR: {
free(this->displayBuffer.c);
break;
}
case GRAPH: {
free(this->displayBuffer.graph);
break;
}
default: {
}
}
this->h = 0;
}
void Meter_done(Meter* this) {
free(this->caption);
free(this->attributes);
free(this->values);
free(this->name);
Meter_freeBuffer(this);
}
/* private */
void Meter_drawBar(Meter* this, int x, int y, int w) {
w -= 2;
attrset(CRT_colors[METER_TEXT]);
mvaddstr(y, x, this->caption);
int captionLen = strlen(this->caption);
x += captionLen;
w -= captionLen;
attrset(CRT_colors[BAR_BORDER]);
mvaddch(y, x, '[');
mvaddch(y, x + w, ']');
w--;
x++;
char bar[w];
this->setValues(this);
int blockSizes[10];
for (int i = 0; i < w; i++)
bar[i] = ' ';
sprintf(bar + (w-strlen(this->displayBuffer.c)), "%s", this->displayBuffer.c);
// First draw in the bar[] buffer...
double total = 0.0;
int offset = 0;
for (int i = 0; i < this->items; i++) {
this->values[i] = MAX(this->values[i], 0);
this->values[i] = MIN(this->values[i], this->total);
double value = this->values[i];
if (value > 0) {
blockSizes[i] = ceil((value/this->total) * w);
} else {
blockSizes[i] = 0;
}
int nextOffset = offset + blockSizes[i];
// (Control against invalid values)
nextOffset = MAX(nextOffset, 0);
nextOffset = MIN(nextOffset, w);
for (int j = offset; j < nextOffset; j++)
if (bar[j] == ' ') {
if (CRT_colorScheme == COLORSCHEME_MONOCHROME) {
bar[j] = Meter_barCharacters[i];
} else {
bar[j] = '|';
}
}
offset = nextOffset;
total += this->values[i];
}
// ...then print the buffer.
offset = 0;
for (int i = 0; i < this->items; i++) {
attrset(CRT_colors[this->attributes[i]]);
mvaddnstr(y, x + offset, bar + offset, blockSizes[i]);
offset += blockSizes[i];
offset = MAX(offset, 0);
offset = MIN(offset, w);
}
if (offset < w) {
attrset(CRT_colors[BAR_SHADOW]);
mvaddnstr(y, x + offset, bar + offset, w - offset);
}
move(y, x + w + 1);
attrset(CRT_colors[RESET_COLOR]);
}
/* private */
void Meter_drawText(Meter* this, int x, int y, int w) {
this->setValues(this);
this->w = w;
attrset(CRT_colors[METER_TEXT]);
mvaddstr(y, x, this->caption);
int captionLen = strlen(this->caption);
w -= captionLen;
x += captionLen;
((Object*)this)->display((Object*)this, this->displayBuffer.rs);
mvhline(y, x, ' ', CRT_colors[DEFAULT_COLOR]);
attrset(CRT_colors[RESET_COLOR]);
mvaddchstr(y, x, this->displayBuffer.rs->chstr);
}
/* private */
void Meter_drawDigit(int x, int y, int n) {
for (int i = 0; i < 3; i++) {
mvaddstr(y+i, x, Meter_ledDigits[i][n]);
}
}
/* private */
void Meter_drawLed(Meter* this, int x, int y, int w) {
this->setValues(this);
((Object*)this)->display((Object*)this, this->displayBuffer.rs);
attrset(CRT_colors[LED_COLOR]);
mvaddstr(y+2, x, this->caption);
int xx = x + strlen(this->caption);
for (int i = 0; i < this->displayBuffer.rs->len; i++) {
char c = this->displayBuffer.rs->chstr[i];
if (c >= '0' && c <= '9') {
Meter_drawDigit(xx, y, c-48);
xx += 4;
} else {
mvaddch(y+2, xx, c);
xx += 1;
}
}
attrset(CRT_colors[RESET_COLOR]);
}
#define DrawDot(a,y,c) do { \
attrset(a); \
mvaddstr(y, x+k, c); \
} while(0)
/* private */
void Meter_drawGraph(Meter* this, int x, int y, int w) {
for (int i = 0; i < METER_GRAPHBUFFER_LEN - 1; i++) {
this->displayBuffer.graph[i] = this->displayBuffer.graph[i+1];
}
this->setValues(this);
double value = 0.0;
for (int i = 0; i < this->items; i++)
value += this->values[i] / this->total;
this->displayBuffer.graph[METER_GRAPHBUFFER_LEN - 1] = value;
for (int i = METER_GRAPHBUFFER_LEN - w, k = 0; i < METER_GRAPHBUFFER_LEN; i++, k++) {
double value = this->displayBuffer.graph[i];
DrawDot( CRT_colors[DEFAULT_COLOR], y, " " );
DrawDot( CRT_colors[DEFAULT_COLOR], y+1, " " );
DrawDot( CRT_colors[DEFAULT_COLOR], y+2, " " );
if (value >= 1.00) DrawDot( CRT_colors[GRAPH_1], y, "^" );
else if (value >= 0.95) DrawDot( CRT_colors[GRAPH_1], y, "`" );
else if (value >= 0.90) DrawDot( CRT_colors[GRAPH_1], y, "'" );
else if (value >= 0.85) DrawDot( CRT_colors[GRAPH_2], y, "-" );
else if (value >= 0.80) DrawDot( CRT_colors[GRAPH_2], y, "." );
else if (value >= 0.75) DrawDot( CRT_colors[GRAPH_2], y, "," );
else if (value >= 0.70) DrawDot( CRT_colors[GRAPH_3], y, "_" );
else if (value >= 0.65) DrawDot( CRT_colors[GRAPH_3], y+1, "~" );
else if (value >= 0.60) DrawDot( CRT_colors[GRAPH_3], y+1, "`" );
else if (value >= 0.55) DrawDot( CRT_colors[GRAPH_4], y+1, "'" );
else if (value >= 0.50) DrawDot( CRT_colors[GRAPH_4], y+1, "-" );
else if (value >= 0.45) DrawDot( CRT_colors[GRAPH_4], y+1, "." );
else if (value >= 0.40) DrawDot( CRT_colors[GRAPH_5], y+1, "," );
else if (value >= 0.35) DrawDot( CRT_colors[GRAPH_5], y+1, "_" );
else if (value >= 0.30) DrawDot( CRT_colors[GRAPH_6], y+2, "~" );
else if (value >= 0.25) DrawDot( CRT_colors[GRAPH_7], y+2, "`" );
else if (value >= 0.20) DrawDot( CRT_colors[GRAPH_7], y+2, "'" );
else if (value >= 0.15) DrawDot( CRT_colors[GRAPH_7], y+2, "-" );
else if (value >= 0.10) DrawDot( CRT_colors[GRAPH_8], y+2, "." );
else if (value >= 0.05) DrawDot( CRT_colors[GRAPH_8], y+2, "," );
else DrawDot( CRT_colors[GRAPH_9], y+2, "_" );
}
attrset(CRT_colors[RESET_COLOR]);
}
void Meter_setMode(Meter* this, MeterMode mode) {
Meter_freeBuffer(this);
switch (mode) {
case UNSET: {
// fallthrough to a sane default.
mode = TEXT;
}
case TEXT: {
this->draw = Meter_drawText;
this->displayBuffer.rs = & Meter_stringBuffer;
this->h = 1;
break;
}
case LED: {
this->draw = Meter_drawLed;
this->displayBuffer.rs = & Meter_stringBuffer;
this->h = 3;
break;
}
case BAR: {
this->draw = Meter_drawBar;
this->displayBuffer.c = malloc(METER_BARBUFFER_LEN);
this->h = 1;
break;
}
case GRAPH: {
this->draw = Meter_drawGraph;
this->displayBuffer.c = calloc(METER_GRAPHBUFFER_LEN, sizeof(double));
this->h = 3;
break;
}
default: {
assert(false);
}
}
this->mode = mode;
}
ListItem* Meter_toListItem(Meter* this) {
char buffer[50]; char* mode = NULL;
switch (this->mode) {
case BAR: mode = "Bar"; break;
case LED: mode = "LED"; break;
case TEXT: mode = "Text"; break;
case GRAPH: mode = "Graph"; break;
default: {
assert(false);
}
}
sprintf(buffer, "%s [%s]", this->name, mode);
return ListItem_new(buffer, 0);
}

94
Meter.h Normal file
View File

@ -0,0 +1,94 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_Meter
#define HEADER_Meter
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "Object.h"
#include "CRT.h"
#include "ListItem.h"
#include "String.h"
#include <stdlib.h>
#include <curses.h>
#include <string.h>
#include <math.h>
#include <sys/param.h>
#include "debug.h"
#include <assert.h>
#define METER_BARBUFFER_LEN 128
#define METER_GRAPHBUFFER_LEN 128
typedef struct Meter_ Meter;
typedef void(*Meter_SetValues)(Meter*);
typedef void(*Meter_Draw)(Meter*, int, int, int);
typedef enum MeterMode_ {
UNSET,
BAR,
TEXT,
GRAPH,
LED,
LAST_METERMODE
} MeterMode;
struct Meter_ {
Object super;
int h;
int w;
Meter_Draw draw;
Meter_SetValues setValues;
int items;
int* attributes;
double* values;
double total;
char* caption;
char* name;
union {
RichString* rs;
char* c;
double* graph;
} displayBuffer;
MeterMode mode;
};
extern char* METER_CLASS;
Meter* Meter_new(char* name, char* caption, int items);
void Meter_init(Meter* this, char* name, char* caption, int items);
void Meter_delete(Object* cast);
void Meter_done(Meter* this);
#define DrawDot(a,y,c) do { \
attrset(a); \
mvaddstr(y, x+k, c); \
} while(0)
void Meter_setMode(Meter* this, MeterMode mode);
ListItem* Meter_toListItem(Meter* this);
#endif

106
MetersListBox.c Normal file
View File

@ -0,0 +1,106 @@
#include "MetersListBox.h"
#include "ListBox.h"
#include "Settings.h"
#include "ScreenManager.h"
#include "debug.h"
#include <assert.h>
/*{
typedef struct MetersListBox_ {
ListBox super;
Settings* settings;
TypedVector* meters;
ScreenManager* scr;
} MetersListBox;
}*/
MetersListBox* MetersListBox_new(Settings* settings, char* header, TypedVector* meters, ScreenManager* scr) {
MetersListBox* this = (MetersListBox*) malloc(sizeof(MetersListBox));
ListBox* super = (ListBox*) this;
ListBox_init(super, 1, 1, 1, 1, LISTITEM_CLASS, true);
((Object*)this)->delete = MetersListBox_delete;
this->settings = settings;
this->meters = meters;
this->scr = scr;
super->eventHandler = MetersListBox_EventHandler;
ListBox_setHeader(super, header);
for (int i = 0; i < TypedVector_size(meters); i++) {
Meter* meter = (Meter*) TypedVector_get(meters, i);
ListBox_add(super, (Object*) Meter_toListItem(meter));
}
return this;
}
void MetersListBox_delete(Object* object) {
ListBox* super = (ListBox*) object;
MetersListBox* this = (MetersListBox*) object;
ListBox_done(super);
free(this);
}
HandlerResult MetersListBox_EventHandler(ListBox* super, int ch) {
MetersListBox* this = (MetersListBox*) super;
int selected = ListBox_getSelectedIndex(super);
HandlerResult result = IGNORED;
switch(ch) {
case 0x0a:
case 0x0d:
case KEY_ENTER:
case KEY_F(4):
case 't':
{
Meter* meter = (Meter*) TypedVector_get(this->meters, selected);
MeterMode mode = meter->mode + 1;
if (mode == LAST_METERMODE)
mode = 1; // skip mode 0, "unset"
Meter_setMode(meter, mode);
ListBox_set(super, selected, (Object*) Meter_toListItem(meter));
result = HANDLED;
break;
}
case KEY_F(7):
case '[':
case '-':
{
TypedVector_moveUp(this->meters, selected);
ListBox_moveSelectedUp(super);
result = HANDLED;
break;
}
case KEY_F(8):
case ']':
case '+':
{
TypedVector_moveDown(this->meters, selected);
ListBox_moveSelectedDown(super);
result = HANDLED;
break;
}
case KEY_F(9):
case KEY_DC:
{
if (selected < TypedVector_size(this->meters)) {
TypedVector_remove(this->meters, selected);
ListBox_remove(super, selected);
}
result = HANDLED;
break;
}
}
if (result == HANDLED) {
Header* header = this->settings->header;
Header_calculateHeight(header);
Header_draw(header);
ScreenManager_resize(this->scr, this->scr->x1, header->height, this->scr->x2, this->scr->y2);
}
return result;
}

30
MetersListBox.h Normal file
View File

@ -0,0 +1,30 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_MetersListBox
#define HEADER_MetersListBox
#include "ListBox.h"
#include "Settings.h"
#include "ScreenManager.h"
#include "debug.h"
#include <assert.h>
typedef struct MetersListBox_ {
ListBox super;
Settings* settings;
TypedVector* meters;
ScreenManager* scr;
} MetersListBox;
MetersListBox* MetersListBox_new(Settings* settings, char* header, TypedVector* meters, ScreenManager* scr);
void MetersListBox_delete(Object* object);
HandlerResult MetersListBox_EventHandler(ListBox* super, int ch);
#endif

5
NEWS Normal file
View File

@ -0,0 +1,5 @@
See the ChangeLog for news of the past.
See the TODO list for news of the future.
Run the program for news of the present.

60
Object.c Normal file
View File

@ -0,0 +1,60 @@
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "Object.h"
#include "RichString.h"
#include "CRT.h"
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include "debug.h"
/*{
typedef struct Object_ Object;
typedef void(*Object_Display)(Object*, RichString*);
typedef int(*Object_Compare)(const Object*, const Object*);
typedef void(*Object_Delete)(Object*);
struct Object_ {
char* class;
Object_Display display;
Object_Compare compare;
Object_Delete delete;
};
}*/
/* private property */
char* OBJECT_CLASS = "Object";
void Object_new() {
Object* this;
this = malloc(sizeof(Object));
this->class = OBJECT_CLASS;
this->display = Object_display;
this->compare = Object_compare;
this->delete = Object_delete;
}
bool Object_instanceOf(Object* this, char* class) {
return this->class == class;
}
void Object_delete(Object* this) {
free(this);
}
void Object_display(Object* this, RichString* out) {
char objAddress[50];
sprintf(objAddress, "%s @ %p", this->class, (void*) this);
RichString_write(out, CRT_colors[DEFAULT_COLOR], objAddress);
}
int Object_compare(const Object* this, const Object* o) {
return (this - o);
}

44
Object.h Normal file
View File

@ -0,0 +1,44 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_Object
#define HEADER_Object
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "RichString.h"
#include "CRT.h"
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include "debug.h"
typedef struct Object_ Object;
typedef void(*Object_Display)(Object*, RichString*);
typedef int(*Object_Compare)(const Object*, const Object*);
typedef void(*Object_Delete)(Object*);
struct Object_ {
char* class;
Object_Display display;
Object_Compare compare;
Object_Delete delete;
};
void Object_new();
bool Object_instanceOf(Object* this, char* class);
void Object_delete(Object* this);
void Object_display(Object* this, RichString* out);
int Object_compare(const Object* this, const Object* o);
#endif

427
Process.c Normal file
View File

@ -0,0 +1,427 @@
/*
htop - Process.c
(C) 2004,2005 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#define _GNU_SOURCE
#include "ProcessList.h"
#include "Object.h"
#include "CRT.h"
#include "String.h"
#include "Process.h"
#include "debug.h"
#include <stdio.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <stdbool.h>
#include <pwd.h>
// This works only with glibc 2.1+. On earlier versions
// the behavior is similar to have a hardcoded page size.
#define PAGE_SIZE ( sysconf(_SC_PAGESIZE) / 1024 )
#define PROCESS_COMM_LEN 300
#define PROCESS_USER_LEN 10
/*{
typedef enum ProcessField_ {
PID = 1, COMM, STATE, PPID, PGRP, SESSION, TTY_NR, TPGID, FLAGS, MINFLT, CMINFLT, MAJFLT, CMAJFLT, UTIME,
STIME, CUTIME, CSTIME, PRIORITY, NICE, ITREALVALUE, STARTTIME, VSIZE, RSS, RLIM, STARTCODE, ENDCODE,
STARTSTACK, KSTKESP, KSTKEIP, SIGNAL, BLOCKED, SSIGIGNORE, SIGCATCH, WCHAN, NSWAP, CNSWAP, EXIT_SIGNAL,
PROCESSOR, M_SIZE, M_RESIDENT, M_SHARE, M_TRS, M_DRS, M_LRS, M_DT, ST_UID, PERCENT_CPU, PERCENT_MEM,
USER, TIME, LAST_PROCESSFIELD
} ProcessField;
struct ProcessList_;
typedef struct Process_ {
Object super;
struct ProcessList_ *pl;
bool updated;
int pid;
char* comm;
int indent;
char state;
bool tag;
int ppid;
int pgrp;
int session;
int tty_nr;
int tpgid;
unsigned long int flags;
unsigned long int minflt;
unsigned long int cminflt;
unsigned long int majflt;
unsigned long int cmajflt;
unsigned long int utime;
unsigned long int stime;
long int cutime;
long int cstime;
long int priority;
long int nice;
long int itrealvalue;
unsigned long int starttime;
unsigned long int vsize;
long int rss;
unsigned long int rlim;
unsigned long int startcode;
unsigned long int endcode;
unsigned long int startstack;
unsigned long int kstkesp;
unsigned long int kstkeip;
unsigned long int signal;
unsigned long int blocked;
unsigned long int sigignore;
unsigned long int sigcatch;
unsigned long int wchan;
unsigned long int nswap;
unsigned long int cnswap;
int exit_signal;
int processor;
int m_size;
int m_resident;
int m_share;
int m_trs;
int m_drs;
int m_lrs;
int m_dt;
uid_t st_uid;
float percent_cpu;
float percent_mem;
char user[PROCESS_USER_LEN + 1];
} Process;
extern char* PROCESS_CLASS;
extern char* Process_fieldNames[];
}*/
/* private property */
char* PROCESS_CLASS = "Process";
/* private property */
char *Process_fieldNames[] = { "", "PID", "Command", "STATE", "PPID", "PGRP", "SESSION", "TTY_NR", "TPGID", "FLAGS", "MINFLT", "CMINFLT", "MAJFLT", "CMAJFLT", "UTIME", "STIME", "CUTIME", "CSTIME", "PRIORITY", "NICE", "ITREALVALUE", "STARTTIME", "VSIZE", "RSS", "RLIM", "STARTCODE", "ENDCODE", "STARTSTACK", "KSTKESP", "KSTKEIP", "SIGNAL", "BLOCKED", "SIGIGNORE", "SIGCATCH", "WCHAN", "NSWAP", "CNSWAP", "EXIT_SIGNAL", "PROCESSOR", "M_SIZE", "M_RESIDENT", "M_SHARE", "M_TRS", "M_DRS", "M_LRS", "M_DT", "ST_UID", "PERCENT_CPU", "PERCENT_MEM", "USER", "TIME", "*** report bug! ***"};
Process* Process_new(struct ProcessList_ *pl) {
Process* this = malloc(sizeof(Process));
((Object*)this)->class = PROCESS_CLASS;
((Object*)this)->display = Process_display;
((Object*)this)->compare = Process_compare;
((Object*)this)->delete = Process_delete;
this->pl = pl;
this->tag = false;
this->updated = false;
this->utime = 0;
this->stime = 0;
this->comm = NULL;
return this;
}
Process* Process_clone(Process* this) {
Process* clone = malloc(sizeof(Process));
memcpy(clone, this, sizeof(Process));
return clone;
}
void Process_delete(Object* cast) {
Process* this = (Process*) cast;
if (this->comm) free(this->comm);
assert (this != NULL);
free(this);
}
void Process_display(Object* cast, RichString* out) {
Process* this = (Process*) cast;
ProcessField* fields = this->pl->fields;
RichString_prune(out);
for (int i = 0; fields[i]; i++)
Process_writeField(this, out, fields[i]);
if (this->pl->shadowOtherUsers && this->st_uid != getuid())
RichString_setAttr(out, CRT_colors[PROCESS_SHADOW]);
if (this->tag == true)
RichString_setAttr(out, CRT_colors[PROCESS_TAG]);
assert(out->len > 0);
}
void Process_toggleTag(Process* this) {
this->tag = this->tag == true ? false : true;
}
void Process_setPriority(Process* this, int priority) {
int old_prio = getpriority(PRIO_PROCESS, this->pid);
int err = setpriority(PRIO_PROCESS, this->pid, priority);
if (err == 0 && old_prio != getpriority(PRIO_PROCESS, this->pid)) {
this->nice = priority;
}
}
void Process_sendSignal(Process* this, int signal) {
kill(this->pid, signal);
}
#define ONE_K 1024
#define ONE_M (ONE_K * ONE_K)
#define ONE_G (ONE_M * ONE_K)
/* private */
void Process_printLargeNumber(Process* this, RichString *str, unsigned int number) {
char buffer[11];
int len;
if(number >= (1000 * ONE_M)) {
len = snprintf(buffer, 10, "%4.2fG ", (float)number / ONE_M);
RichString_appendn(str, CRT_colors[LARGE_NUMBER], buffer, len);
} else if(number >= (100000)) {
len = snprintf(buffer, 10, "%4dM ", number / ONE_K);
int attr = this->pl->highlightMegabytes
? CRT_colors[PROCESS_MEGABYTES]
: CRT_colors[PROCESS];
RichString_appendn(str, attr, buffer, len);
} else if (this->pl->highlightMegabytes && number >= 1000) {
len = snprintf(buffer, 10, "%2d", number/1000);
RichString_appendn(str, CRT_colors[PROCESS_MEGABYTES], buffer, len);
number %= 1000;
len = snprintf(buffer, 10, "%03d ", number);
RichString_appendn(str, CRT_colors[PROCESS], buffer, len);
} else {
len = snprintf(buffer, 10, "%5d ", number);
RichString_appendn(str, CRT_colors[PROCESS], buffer, len);
}
}
/* private property */
double jiffy = 0.0;
/* private */
static void Process_printTime(RichString* str, unsigned long t) {
if(jiffy == 0.0) jiffy = sysconf(_SC_CLK_TCK);
double jiffytime = 1.0 / jiffy;
double realTime = t * jiffytime;
int iRealTime = (int) realTime;
int hours = iRealTime / 3600;
int minutes = (iRealTime / 60) % 60;
int seconds = iRealTime % 60;
int hundredths = (realTime - iRealTime) * 100;
char buffer[11];
if (hours) {
snprintf(buffer, 10, "%2dh", hours);
RichString_append(str, CRT_colors[LARGE_NUMBER], buffer);
snprintf(buffer, 10, "%02d:%02d ", minutes, seconds);
} else {
snprintf(buffer, 10, "%2d:%02d.%02d ", minutes, seconds, hundredths);
}
RichString_append(str, CRT_colors[DEFAULT_COLOR], buffer);
}
/* private */
static void Process_printTTY(RichString* str, int tty_nr) {
unsigned char minor = tty_nr;
unsigned char major = tty_nr >> 8;
char* buffer[11];
}
inline static void Process_writeCommand(Process* this, int attr, RichString* str) {
if (this->pl->highlightBaseName) {
char* firstSpace = strchr(this->comm, ' ');
if (firstSpace) {
char* slash = firstSpace;
while (slash > this->comm && *slash != '/')
slash--;
if (slash > this->comm) {
slash++;
RichString_appendn(str, attr, this->comm, slash - this->comm);
}
RichString_appendn(str, CRT_colors[PROCESS_BASENAME], slash, firstSpace - slash);
RichString_append(str, attr, firstSpace);
} else {
RichString_append(str, CRT_colors[PROCESS_BASENAME], this->comm);
}
} else {
RichString_append(str, attr, this->comm);
}
}
void Process_writeField(Process* this, RichString* str, ProcessField field) {
char buffer[PROCESS_COMM_LEN];
int attr = CRT_colors[DEFAULT_COLOR];
int n = PROCESS_COMM_LEN;
switch (field) {
case PID: snprintf(buffer, n, "%5d ", this->pid); break;
case PPID: snprintf(buffer, n, "%5d ", this->ppid); break;
case PGRP: snprintf(buffer, n, "%5d ", this->pgrp); break;
case SESSION: snprintf(buffer, n, "%5d ", this->session); break;
case TTY_NR: snprintf(buffer, n, "%5d ", this->tty_nr); break;
case TPGID: snprintf(buffer, n, "%5d ", this->tpgid); break;
case PROCESSOR: snprintf(buffer, n, "%3d ", this->processor+1); break;
case COMM: {
if (!this->pl->treeView || this->indent == 0) {
Process_writeCommand(this, attr, str);
return;
} else {
char* buf = buffer;
int maxIndent = 0;
for (int i = 0; i < 32; i++)
if (this->indent & (1 << i))
maxIndent = i+1;
for (int i = 0; i < maxIndent - 1; i++) {
if (this->indent & (1 << i))
snprintf(buf, n, " | ");
else
snprintf(buf, n, " ");
buf += 4;
n -= 4;
}
if (this->pl->direction == 1)
snprintf(buf, n, " `- ");
else
snprintf(buf, n, " ,- ");
RichString_append(str, CRT_colors[PROCESS_TREE], buffer);
Process_writeCommand(this, attr, str);
return;
}
}
case STATE: {
snprintf(buffer, n, "%c ", this->state);
attr = this->state == 'R'
? CRT_colors[PROCESS_R_STATE]
: attr;
break;
}
case PRIORITY: {
if(this->priority == -100)
snprintf(buffer, n, " RT ");
else
snprintf(buffer, n, "%3ld ", this->priority);
break;
}
case NICE: {
snprintf(buffer, n, "%3ld ", this->nice);
attr = this->nice < 0 ? CRT_colors[PROCESS_HIGH_PRIORITY]
: this->nice > 0 ? CRT_colors[PROCESS_LOW_PRIORITY]
: attr;
break;
}
case M_SIZE: Process_printLargeNumber(this, str, this->m_size * PAGE_SIZE); return;
case M_RESIDENT: Process_printLargeNumber(this, str, this->m_resident * PAGE_SIZE); return;
case M_SHARE: Process_printLargeNumber(this, str, this->m_share * PAGE_SIZE); return;
case ST_UID: snprintf(buffer, n, "%4d ", this->st_uid); break;
case USER: {
if (getuid() != this->st_uid)
attr = CRT_colors[PROCESS_SHADOW];
snprintf(buffer, n, "%-8s ", this->user);
if (buffer[8] != '\0') {
buffer[8] = ' ';
buffer[9] = '\0';
}
break;
}
case UTIME: Process_printTime(str, this->utime); return;
case STIME: Process_printTime(str, this->stime); return;
case CUTIME: Process_printTime(str, this->cutime); return;
case CSTIME: Process_printTime(str, this->cstime); return;
case TIME: Process_printTime(str, this->utime + this->stime); return;
case PERCENT_CPU: {
if (this->percent_cpu > 99.9) {
snprintf(buffer, n, "100. ");
} else {
snprintf(buffer, n, "%4.1f ", this->percent_cpu);
}
break;
}
case PERCENT_MEM: {
if (this->percent_mem > 99.9) {
snprintf(buffer, n, "100. ");
} else {
snprintf(buffer, n, "%4.1f ", this->percent_mem);
}
break;
}
default:
snprintf(buffer, n, "- ");
}
RichString_append(str, attr, buffer);
return;
}
int Process_compare(const Object* v1, const Object* v2) {
Process* p1 = (Process*)v1;
Process* p2 = (Process*)v2;
int direction = p1->pl->direction;
switch (p1->pl->sortKey) {
case PID:
return (p2->pid - p1->pid) * direction;
case PPID:
return (p2->ppid - p1->ppid) * direction;
case USER:
return strcmp(p2->user, p1->user) * direction;
case PRIORITY:
return (p2->priority - p1->priority) * direction;
case STATE:
return (p2->state - p1->state) * direction;
case NICE:
return (p2->nice - p1->nice) * direction;
case M_SIZE:
return (p1->m_size - p2->m_size) * direction;
case M_RESIDENT:
return (p1->m_resident - p2->m_resident) * direction;
case M_SHARE:
return (p1->m_share - p2->m_share) * direction;
case PERCENT_CPU:
return (p1->percent_cpu < p2->percent_cpu ? -1 : 1) * direction;
case PERCENT_MEM:
return (p1->percent_mem < p2->percent_mem ? -1 : 1) * direction;
case UTIME:
return (p1->utime - p2->utime) * direction;
case STIME:
return (p1->stime - p2->stime) * direction;
case TIME:
return ((p1->utime+p1->stime) - (p2->utime+p2->stime)) * direction;
case COMM:
return strcmp(p2->comm, p1->comm) * direction;
default:
return (p2->pid - p1->pid) * direction;
}
}
char* Process_printField(ProcessField field) {
switch (field) {
case PID: return " PID ";
case PPID: return " PPID ";
case PGRP: return " PGRP ";
case SESSION: return " SESN ";
case TTY_NR: return " TTY ";
case TPGID: return " TGID ";
case COMM: return "Command ";
case STATE: return "S ";
case PRIORITY: return "PRI ";
case NICE: return " NI ";
case M_SIZE: return " VIRT ";
case M_RESIDENT: return " RES ";
case M_SHARE: return " SHR ";
case ST_UID: return " UID ";
case USER: return "USER ";
case UTIME: return " UTIME+ ";
case STIME: return " STIME+ ";
case TIME: return " TIME+ ";
case PERCENT_CPU: return "CPU% ";
case PERCENT_MEM: return "MEM% ";
case PROCESSOR: return "CPU ";
default: return "- ";
}
}

140
Process.h Normal file
View File

@ -0,0 +1,140 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_Process
#define HEADER_Process
/*
htop - Process.h
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#define _GNU_SOURCE
#include "ProcessList.h"
#include "Object.h"
#include "CRT.h"
#include "String.h"
#include "debug.h"
#include <stdio.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <stdbool.h>
#include <pwd.h>
// This works only with glibc 2.1+. On earlier versions
// the behavior is similar to have a hardcoded page size.
#define PAGE_SIZE ( sysconf(_SC_PAGESIZE) / 1024 )
#define PROCESS_COMM_LEN 300
#define PROCESS_USER_LEN 10
typedef enum ProcessField_ {
PID = 1, COMM, STATE, PPID, PGRP, SESSION, TTY_NR, TPGID, FLAGS, MINFLT, CMINFLT, MAJFLT, CMAJFLT, UTIME,
STIME, CUTIME, CSTIME, PRIORITY, NICE, ITREALVALUE, STARTTIME, VSIZE, RSS, RLIM, STARTCODE, ENDCODE,
STARTSTACK, KSTKESP, KSTKEIP, SIGNAL, BLOCKED, SSIGIGNORE, SIGCATCH, WCHAN, NSWAP, CNSWAP, EXIT_SIGNAL,
PROCESSOR, M_SIZE, M_RESIDENT, M_SHARE, M_TRS, M_DRS, M_LRS, M_DT, ST_UID, PERCENT_CPU, PERCENT_MEM,
USER, TIME, LAST_PROCESSFIELD
} ProcessField;
struct ProcessList_;
typedef struct Process_ {
Object super;
struct ProcessList_ *pl;
bool updated;
int pid;
char* comm;
int indent;
char state;
bool tag;
int ppid;
int pgrp;
int session;
int tty_nr;
int tpgid;
unsigned long int flags;
unsigned long int minflt;
unsigned long int cminflt;
unsigned long int majflt;
unsigned long int cmajflt;
unsigned long int utime;
unsigned long int stime;
long int cutime;
long int cstime;
long int priority;
long int nice;
long int itrealvalue;
unsigned long int starttime;
unsigned long int vsize;
long int rss;
unsigned long int rlim;
unsigned long int startcode;
unsigned long int endcode;
unsigned long int startstack;
unsigned long int kstkesp;
unsigned long int kstkeip;
unsigned long int signal;
unsigned long int blocked;
unsigned long int sigignore;
unsigned long int sigcatch;
unsigned long int wchan;
unsigned long int nswap;
unsigned long int cnswap;
int exit_signal;
int processor;
int m_size;
int m_resident;
int m_share;
int m_trs;
int m_drs;
int m_lrs;
int m_dt;
uid_t st_uid;
float percent_cpu;
float percent_mem;
char user[PROCESS_USER_LEN + 1];
} Process;
extern char* PROCESS_CLASS;
extern char* Process_fieldNames[];
Process* Process_new(struct ProcessList_ *pl);
Process* Process_clone(Process* this);
void Process_delete(Object* cast);
void Process_display(Object* cast, RichString* out);
void Process_toggleTag(Process* this);
void Process_setPriority(Process* this, int priority);
void Process_sendSignal(Process* this, int signal);
#define ONE_K 1024
#define ONE_M (ONE_K * ONE_K)
#define ONE_G (ONE_M * ONE_K)
void Process_writeField(Process* this, RichString* str, ProcessField field);
int Process_compare(const Object* v1, const Object* v2);
char* Process_printField(ProcessField field);
#endif

589
ProcessList.c Normal file
View File

@ -0,0 +1,589 @@
/*
htop - ProcessList.c
(C) 2004,2005 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "ProcessList.h"
#include "Process.h"
#include "TypedVector.h"
#include "UsersTable.h"
#include "Hashtable.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <stdbool.h>
#include <sys/utsname.h>
#include "debug.h"
#include <assert.h>
/*{
#ifndef PROCDIR
#define PROCDIR "/proc"
#endif
#ifndef PROCSTATFILE
#define PROCSTATFILE "/proc/stat"
#endif
#ifndef PROCMEMINFOFILE
#define PROCMEMINFOFILE "/proc/meminfo"
#endif
#ifndef MAX_NAME
#define MAX_NAME 128;
#endif
}*/
/*{
typedef struct ProcessList_ {
TypedVector* processes;
TypedVector* processes2;
Hashtable* processTable;
Process* prototype;
UsersTable* usersTable;
int processorCount;
int totalTasks;
int runningTasks;
long int* totalTime;
long int* userTime;
long int* systemTime;
long int* idleTime;
long int* niceTime;
long int* totalPeriod;
long int* userPeriod;
long int* systemPeriod;
long int* idlePeriod;
long int* nicePeriod;
long int totalMem;
long int usedMem;
long int freeMem;
long int sharedMem;
long int buffersMem;
long int cachedMem;
long int totalSwap;
long int usedSwap;
long int freeSwap;
ProcessField* fields;
ProcessField sortKey;
int direction;
bool hideThreads;
bool shadowOtherUsers;
bool hideKernelThreads;
bool hideUserlandThreads;
bool treeView;
bool highlightBaseName;
bool highlightMegabytes;
} ProcessList;
}*/
/* private property */
ProcessField defaultHeaders[] = { PID, USER, PRIORITY, NICE, M_SIZE, M_RESIDENT, M_SHARE, STATE, PERCENT_CPU, PERCENT_MEM, TIME, COMM, LAST_PROCESSFIELD, 0 };
ProcessList* ProcessList_new(UsersTable* usersTable) {
ProcessList* this;
this = malloc(sizeof(ProcessList));
this->processes = TypedVector_new(PROCESS_CLASS, true, DEFAULT_SIZE);
this->processTable = Hashtable_new(20, false);
this->prototype = Process_new(this);
this->usersTable = usersTable;
/* tree-view auxiliary buffers */
this->processes2 = TypedVector_new(PROCESS_CLASS, true, DEFAULT_SIZE);
FILE* status = fopen(PROCSTATFILE, "r");
assert(status != NULL);
char buffer[256];
int procs = -1;
do {
procs++;
fgets(buffer, 255, status);
} while (String_startsWith(buffer, "cpu"));
fclose(status);
this->processorCount = procs - 1;
this->totalTime = calloc(procs, sizeof(long int));
this->userTime = calloc(procs, sizeof(long int));
this->systemTime = calloc(procs, sizeof(long int));
this->niceTime = calloc(procs, sizeof(long int));
this->idleTime = calloc(procs, sizeof(long int));
this->totalPeriod = calloc(procs, sizeof(long int));
this->userPeriod = calloc(procs, sizeof(long int));
this->systemPeriod = calloc(procs, sizeof(long int));
this->nicePeriod = calloc(procs, sizeof(long int));
this->idlePeriod = calloc(procs, sizeof(long int));
for (int i = 0; i < procs; i++) {
this->totalTime[i] = 1;
this->totalPeriod[i] = 1;
}
this->fields = calloc(sizeof(ProcessField), LAST_PROCESSFIELD+1);
// TODO: turn 'fields' into a TypedVector,
// (and ProcessFields into proper objects).
for (int i = 0; defaultHeaders[i]; i++) {
this->fields[i] = defaultHeaders[i];
}
this->sortKey = PERCENT_CPU;
this->direction = 1;
this->hideThreads = false;
this->shadowOtherUsers = false;
this->hideKernelThreads = false;
this->hideUserlandThreads = false;
this->treeView = false;
this->highlightBaseName = false;
this->highlightMegabytes = false;
return this;
}
void ProcessList_delete(ProcessList* this) {
Hashtable_delete(this->processTable);
TypedVector_delete(this->processes);
TypedVector_delete(this->processes2);
Process_delete((Object*)this->prototype);
free(this->totalTime);
free(this->userTime);
free(this->systemTime);
free(this->niceTime);
free(this->idleTime);
free(this->totalPeriod);
free(this->userPeriod);
free(this->systemPeriod);
free(this->nicePeriod);
free(this->idlePeriod);
free(this->fields);
free(this);
}
void ProcessList_invertSortOrder(ProcessList* this) {
if (this->direction == 1)
this->direction = -1;
else
this->direction = 1;
}
RichString ProcessList_printHeader(ProcessList* this) {
RichString out = RichString_new();
ProcessField* fields = this->fields;
for (int i = 0; fields[i]; i++) {
char* field = Process_printField(fields[i]);
if (this->sortKey == fields[i])
RichString_append(&out, CRT_colors[PANEL_HIGHLIGHT_FOCUS], field);
else
RichString_append(&out, CRT_colors[PANEL_HEADER_FOCUS], field);
}
return out;
}
void ProcessList_prune(ProcessList* this) {
TypedVector_prune(this->processes);
}
void ProcessList_add(ProcessList* this, Process* p) {
TypedVector_add(this->processes, p);
Hashtable_put(this->processTable, p->pid, p);
}
void ProcessList_remove(ProcessList* this, Process* p) {
Hashtable_remove(this->processTable, p->pid);
ProcessField pf = this->sortKey;
this->sortKey = PID;
int index = TypedVector_indexOf(this->processes, p);
TypedVector_remove(this->processes, index);
this->sortKey = pf;
}
Process* ProcessList_get(ProcessList* this, int index) {
return (Process*) (TypedVector_get(this->processes, index));
}
int ProcessList_size(ProcessList* this) {
return (TypedVector_size(this->processes));
}
/* private */
void ProcessList_buildTree(ProcessList* this, int pid, int level, int indent, int direction) {
TypedVector* children = TypedVector_new(PROCESS_CLASS, false, DEFAULT_SIZE);
for (int i = 0; i < TypedVector_size(this->processes); i++) {
Process* process = (Process*) (TypedVector_get(this->processes, i));
if (process->ppid == pid) {
Process* process = (Process*) (TypedVector_take(this->processes, i));
TypedVector_add(children, process);
i--;
}
}
int size = TypedVector_size(children);
for (int i = 0; i < size; i++) {
Process* process = (Process*) (TypedVector_get(children, i));
if (direction == 1)
TypedVector_add(this->processes2, process);
else
TypedVector_insert(this->processes2, 0, process);
int nextIndent = indent;
if (i < size - 1)
nextIndent = indent | (1 << level);
ProcessList_buildTree(this, process->pid, level+1, nextIndent, direction);
process->indent = indent | (1 << level);
}
TypedVector_delete(children);
}
void ProcessList_sort(ProcessList* this) {
if (!this->treeView) {
TypedVector_sort(this->processes);
} else {
int direction = this->direction;
int sortKey = this->sortKey;
this->sortKey = PID;
this->direction = 1;
TypedVector_sort(this->processes);
this->sortKey = sortKey;
this->direction = direction;
Process* init = (Process*) (TypedVector_take(this->processes, 0));
assert(init->pid == 1);
init->indent = 0;
TypedVector_add(this->processes2, init);
ProcessList_buildTree(this, init->pid, 0, 0, direction);
TypedVector* t = this->processes;
this->processes = this->processes2;
this->processes2 = t;
}
}
/* private */
int ProcessList_readStatFile(Process *proc, FILE *f, char *command) {
#define MAX_READ 8192
static char buf[MAX_READ];
long int zero;
int size = fread(buf, 1, MAX_READ, f);
if(!size) return 0;
proc->pid = atoi(buf);
char *location = strchr(buf, ' ');
if(!location) return 0;
location += 2;
char *end = strrchr(location, ')');
if(!end) return 0;
int commsize = end - location;
memcpy(command, location, commsize);
command[commsize] = '\0';
location = end + 2;
int num = sscanf(location,
"%c %d %d %d %d %d %lu %lu %lu %lu "
"%lu %lu %lu %ld %ld %ld %ld %ld %ld "
"%lu %lu %ld %lu %lu %lu %lu %lu "
"%lu %lu %lu %lu %lu %lu %lu %lu "
"%d %d",
&proc->state, &proc->ppid, &proc->pgrp, &proc->session, &proc->tty_nr,
&proc->tpgid, &proc->flags, &proc->minflt, &proc->cminflt, &proc->majflt,
&proc->cmajflt, &proc->utime, &proc->stime, &proc->cutime, &proc->cstime,
&proc->priority, &proc->nice, &zero, &proc->itrealvalue,
&proc->starttime, &proc->vsize, &proc->rss, &proc->rlim,
&proc->startcode, &proc->endcode, &proc->startstack, &proc->kstkesp,
&proc->kstkeip, &proc->signal, &proc->blocked, &proc->sigignore,
&proc->sigcatch, &proc->wchan, &proc->nswap, &proc->cnswap,
&proc->exit_signal, &proc->processor);
// This assert is always valid on 2.4, but reportedly not always valid on 2.6.
// TODO: Check if the semantics of this field has changed.
// assert(zero == 0);
if(num != 37) return 0;
return 1;
}
bool ProcessList_readStatusFile(Process* proc, char* dirname, char* name) {
char statusfilename[MAX_NAME+1];
statusfilename[MAX_NAME] = '\0';
snprintf(statusfilename, MAX_NAME, "%s/%s/status", dirname, name);
FILE* status = fopen(statusfilename, "r");
bool success = false;
if (status) {
char buffer[1024];
buffer[1023] = '\0';
while (!feof(status)) {
char* ok = fgets(buffer, 1023, status);
if (!ok)
break;
if (String_startsWith(buffer, "Uid:")) {
int uid1, uid2, uid3, uid4;
// TODO: handle other uid's.
int ok = sscanf(buffer, "Uid:\t%d\t%d\t%d\t%d\n", &uid1, &uid2, &uid3, &uid4);
if (ok >= 1) {
proc->st_uid = uid1;
success = true;
}
break;
}
}
fclose(status);
}
if (!success) {
snprintf(statusfilename, MAX_NAME, "%s/%s/stat", dirname, name);
struct stat sstat;
int statok = stat(statusfilename, &sstat);
if (statok == -1)
return false;
proc->st_uid = sstat.st_uid;
}
return success;
}
void ProcessList_processEntries(ProcessList* this, char* dirname, int parent, float period) {
DIR* dir;
struct dirent* entry;
Process* prototype = this->prototype;
dir = opendir(dirname);
assert(dir != NULL);
while ((entry = readdir(dir)) != NULL) {
char* name = entry->d_name;
int pid;
// filename is a number: process directory
pid = atoi(name);
// The RedHat kernel hides threads with a dot.
// I believe this is non-standard.
bool isThread = false;
if ((!this->hideThreads) && pid == 0 && name[0] == '.') {
char* tname = name + 1;
pid = atoi(tname);
if (pid > 0)
isThread = true;
}
if (pid > 0 && pid != parent) {
if (!this->hideUserlandThreads) {
char subdirname[MAX_NAME+1];
snprintf(subdirname, MAX_NAME, "%s/%s/task", dirname, name);
if (access(subdirname, X_OK) == 0) {
ProcessList_processEntries(this, subdirname, pid, period);
}
}
FILE* status;
char statusfilename[MAX_NAME+1];
char command[PROCESS_COMM_LEN + 1];
Process* process;
Process* existingProcess = (Process*) Hashtable_get(this->processTable, pid);
if (!existingProcess) {
process = Process_clone(prototype);
process->pid = pid;
ProcessList_add(this, process);
if (! ProcessList_readStatusFile(process, dirname, name))
goto errorReadingProcess;
} else {
process = existingProcess;
}
process->updated = true;
char* username = UsersTable_getRef(this->usersTable, process->st_uid);
if (username) {
strncpy(process->user, username, PROCESS_USER_LEN);
} else {
snprintf(process->user, PROCESS_USER_LEN, "%d", process->st_uid);
}
int lasttimes = (process->utime + process->stime);
snprintf(statusfilename, MAX_NAME, "%s/%s/stat", dirname, name);
status = fopen(statusfilename, "r");
if (status == NULL)
goto errorReadingProcess;
int success = ProcessList_readStatFile(process, status, command);
fclose(status);
if(!success) {
goto errorReadingProcess;
}
process->percent_cpu = (process->utime + process->stime - lasttimes) /
period * 100.0;
if(!existingProcess) {
snprintf(statusfilename, MAX_NAME, "%s/%s/cmdline", dirname, name);
status = fopen(statusfilename, "r");
if (!status) {
goto errorReadingProcess;
}
int amtRead = fread(command, 1, PROCESS_COMM_LEN - 1, status);
if (amtRead > 0) {
for (int i = 0; i < amtRead; i++)
if (command[i] == '\0' || command[i] == '\n')
command[i] = ' ';
command[amtRead] = '\0';
}
command[PROCESS_COMM_LEN] = '\0';
process->comm = String_copy(command);
fclose(status);
}
snprintf(statusfilename, MAX_NAME, "%s/%s/statm", dirname, name);
status = fopen(statusfilename, "r");
if(!status) {
goto errorReadingProcess;
}
int num = fscanf(status, "%d %d %d %d %d %d %d",
&process->m_size, &process->m_resident, &process->m_share,
&process->m_trs, &process->m_drs, &process->m_lrs,
&process->m_dt);
fclose(status);
if(num != 7)
goto errorReadingProcess;
process->percent_mem = process->m_resident /
(float)(this->usedMem - this->cachedMem - this->buffersMem) *
100.0;
this->totalTasks++;
if (process->state == 'R') {
this->runningTasks++;
}
if (this->hideKernelThreads && process->m_size == 0)
ProcessList_remove(this, process);
continue;
// Exception handler.
errorReadingProcess: {
ProcessList_remove(this, process);
}
}
}
closedir(dir);
}
void ProcessList_scan(ProcessList* this) {
long int usertime, nicetime, systemtime, idletime, totaltime;
long int swapFree;
FILE* status;
char buffer[128];
status = fopen(PROCMEMINFOFILE, "r");
assert(status != NULL);
while (!feof(status)) {
fgets(buffer, 128, status);
switch (buffer[0]) {
case 'M':
if (String_startsWith(buffer, "MemTotal:"))
sscanf(buffer, "MemTotal: %ld kB", &this->totalMem);
else if (String_startsWith(buffer, "MemFree:"))
sscanf(buffer, "MemFree: %ld kB", &this->freeMem);
else if (String_startsWith(buffer, "MemShared:"))
sscanf(buffer, "MemShared: %ld kB", &this->sharedMem);
break;
case 'B':
if (String_startsWith(buffer, "Buffers:"))
sscanf(buffer, "Buffers: %ld kB", &this->buffersMem);
break;
case 'C':
if (String_startsWith(buffer, "Cached:"))
sscanf(buffer, "Cached: %ld kB", &this->cachedMem);
break;
case 'S':
if (String_startsWith(buffer, "SwapTotal:"))
sscanf(buffer, "SwapTotal: %ld kB", &this->totalSwap);
if (String_startsWith(buffer, "SwapFree:"))
sscanf(buffer, "SwapFree: %ld kB", &swapFree);
break;
}
}
this->usedMem = this->totalMem - this->freeMem;
this->usedSwap = this->totalSwap - swapFree;
fclose(status);
status = fopen(PROCSTATFILE, "r");
assert(status != NULL);
for (int i = 0; i <= this->processorCount; i++) {
char buffer[256];
int cpuid;
long int ioWait, irq, softIrq, steal;
ioWait = irq = softIrq = steal = 0;
// Dependending on your kernel version,
// 5, 7 or 8 of these fields will be set.
// The rest will remain at zero.
fgets(buffer, 255, status);
if (i == 0)
sscanf(buffer, "cpu %ld %ld %ld %ld %ld %ld %ld %ld\n", &usertime, &nicetime, &systemtime, &idletime, &ioWait, &irq, &softIrq, &steal);
else {
sscanf(buffer, "cpu%d %ld %ld %ld %ld %ld %ld %ld %ld\n", &cpuid, &usertime, &nicetime, &systemtime, &idletime, &ioWait, &irq, &softIrq, &steal);
assert(cpuid == i - 1);
}
// Fields existing on kernels >= 2.6
// (and RHEL's patched kernel 2.4...)
systemtime += ioWait + irq + softIrq + steal;
totaltime = usertime + nicetime + systemtime + idletime;
assert (usertime >= this->userTime[i]);
assert (nicetime >= this->niceTime[i]);
assert (systemtime >= this->systemTime[i]);
assert (idletime >= this->idleTime[i]);
assert (totaltime >= this->totalTime[i]);
this->userPeriod[i] = usertime - this->userTime[i];
this->nicePeriod[i] = nicetime - this->niceTime[i];
this->systemPeriod[i] = systemtime - this->systemTime[i];
this->idlePeriod[i] = idletime - this->idleTime[i];
this->totalPeriod[i] = totaltime - this->totalTime[i];
this->userTime[i] = usertime;
this->niceTime[i] = nicetime;
this->systemTime[i] = systemtime;
this->idleTime[i] = idletime;
this->totalTime[i] = totaltime;
}
float period = (float)this->totalPeriod[0] / this->processorCount;
fclose(status);
// mark all process as "dirty"
for (int i = 0; i < TypedVector_size(this->processes); i++) {
Process* p = (Process*) TypedVector_get(this->processes, i);
p->updated = false;
}
this->totalTasks = 0;
this->runningTasks = 0;
signal(11, ProcessList_dontCrash);
ProcessList_processEntries(this, PROCDIR, 0, period);
signal(11, SIG_DFL);
for (int i = TypedVector_size(this->processes) - 1; i >= 0; i--) {
Process* p = (Process*) TypedVector_get(this->processes, i);
if (p->updated == false)
ProcessList_remove(this, p);
else
p->updated = false;
}
}
void ProcessList_dontCrash(int signal) {
// This ugly hack was added because I suspect some
// crashes were caused by contents of /proc vanishing
// away while we read them.
}

124
ProcessList.h Normal file
View File

@ -0,0 +1,124 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_ProcessList
#define HEADER_ProcessList
/*
htop - ProcessList.h
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "Process.h"
#include "TypedVector.h"
#include "UsersTable.h"
#include "Hashtable.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <stdbool.h>
#include <sys/utsname.h>
#include "debug.h"
#include <assert.h>
#ifndef PROCDIR
#define PROCDIR "/proc"
#endif
#ifndef PROCSTATFILE
#define PROCSTATFILE "/proc/stat"
#endif
#ifndef PROCMEMINFOFILE
#define PROCMEMINFOFILE "/proc/meminfo"
#endif
#ifndef MAX_NAME
#define MAX_NAME 128
#endif
typedef struct ProcessList_ {
TypedVector* processes;
TypedVector* processes2;
Hashtable* processTable;
Process* prototype;
UsersTable* usersTable;
int processorCount;
int totalTasks;
int runningTasks;
long int* totalTime;
long int* userTime;
long int* systemTime;
long int* idleTime;
long int* niceTime;
long int* totalPeriod;
long int* userPeriod;
long int* systemPeriod;
long int* idlePeriod;
long int* nicePeriod;
long int totalMem;
long int usedMem;
long int freeMem;
long int sharedMem;
long int buffersMem;
long int cachedMem;
long int totalSwap;
long int usedSwap;
long int freeSwap;
int kernelMajor;
int kernelMiddle;
int kernelMinor;
int kernelTiny;
ProcessField* fields;
ProcessField sortKey;
int direction;
bool hideThreads;
bool shadowOtherUsers;
bool hideKernelThreads;
bool hideUserlandThreads;
bool treeView;
bool highlightBaseName;
bool highlightMegabytes;
} ProcessList;
ProcessList* ProcessList_new(UsersTable* usersTable);
void ProcessList_delete(ProcessList* this);
void ProcessList_invertSortOrder(ProcessList* this);
RichString ProcessList_printHeader(ProcessList* this);
void ProcessList_prune(ProcessList* this);
void ProcessList_add(ProcessList* this, Process* p);
void ProcessList_remove(ProcessList* this, Process* p);
Process* ProcessList_get(ProcessList* this, int index);
int ProcessList_size(ProcessList* this);
void ProcessList_sort(ProcessList* this);
void ProcessList_scan(ProcessList* this);
void ProcessList_dontCrash(int signal);
#endif

48
README Normal file
View File

@ -0,0 +1,48 @@
htop
by Hisham Muhammad <loderunner@users.sourceforge.net>
May, 2004 - February, 2006
Introduction
~~~~~~~~~~~~
This is htop, an interactive process viewer.
It requires ncurses. Tested with Linux 2.4 and 2.6.
Note that, while, htop is Linux specific -- it is based
on the Linux /proc filesystem -- it is also reported to work
with FreeBSD systems featuring a Linux-compatible /proc.
This software has evolved considerably during the last months,
and is reasonably complete, but there is still room for
improvement. Read the TODO file to see what's known to be missing.
Comparison between 'htop' and 'top'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* In 'htop' you can scroll the list vertically and horizontally
to see all processes and full command lines.
* In 'top' you are subject to a delay for each unassigned
key you press (especially annoying when multi-key escape
sequences are triggered by accident).
* 'htop' starts faster ('top' seems to collect data for a while
before displaying anything).
* In 'htop' you don't need to type the process number to
kill a process, in 'top' you do.
* In 'htop' you don't need to type the process number or
the priority value to renice a process, in 'top' you do.
* In 'htop' you can kill multiple processes at once.
* 'top' is older, hence, more tested.
Compilation instructions
~~~~~~~~~~~~~~~~~~~~~~~~
This program is distributed as a standard autotools-based package.
See the INSTALL file for detailed instructions, but you are
probably used to the common "configure/make/make install" routine.
See the manual page (man htop) or the on-line help ('F1' or 'h'
inside htop) for a list of supported key commands.
if not all keys work check your curses configuration.

83
RichString.c Normal file
View File

@ -0,0 +1,83 @@
#include "RichString.h"
#include <stdlib.h>
#include <string.h>
#include <curses.h>
#include "debug.h"
#include <assert.h>
#define RICHSTRING_MAXLEN 300
/*{
typedef struct RichString_ {
int len;
chtype chstr[RICHSTRING_MAXLEN+1];
} RichString;
}*/
#ifndef MIN
#define MIN(a,b) ((a)<(b)?(a):(b))
#endif
/* private property */
WINDOW* workArea = NULL;
RichString RichString_new() {
RichString this;
this.len = 0;
return this;
}
void RichString_delete(RichString this) {
}
void RichString_prune(RichString* this) {
this->len = 0;
}
void RichString_write(RichString* this, int attrs, char* data) {
this->len = 0;
RichString_append(this, attrs, data);
}
inline void RichString_append(RichString* this, int attrs, char* data) {
RichString_appendn(this, attrs, data, strlen(data));
}
inline void RichString_appendn(RichString* this, int attrs, char* data, int len) {
if (!workArea) {
workArea = newpad(1, RICHSTRING_MAXLEN);
}
assert(workArea);
wattrset(workArea, attrs);
int maxToWrite = (RICHSTRING_MAXLEN - 1) - this->len;
int wrote = MIN(maxToWrite, len);
mvwaddnstr(workArea, 0, 0, data, maxToWrite);
int oldstrlen = this->len;
this->len += wrote;
mvwinchnstr(workArea, 0, 0, this->chstr + oldstrlen, wrote);
wattroff(workArea, attrs);
}
void RichString_setAttr(RichString *this, int attrs) {
for (int i = 0; i < this->len; i++) {
char c = this->chstr[i];
this->chstr[i] = c | attrs;
}
}
void RichString_applyAttr(RichString *this, int attrs) {
for (int i = 0; i < this->len - 1; i++) {
this->chstr[i] |= attrs;
}
}
RichString RichString_quickString(int attrs, char* data) {
RichString str = RichString_new();
RichString_write(&str, attrs, data);
return str;
}

43
RichString.h Normal file
View File

@ -0,0 +1,43 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_RichString
#define HEADER_RichString
#include <stdlib.h>
#include <string.h>
#include <curses.h>
#include <sys/param.h>
#include "debug.h"
#include <assert.h>
#define RICHSTRING_MAXLEN 300
typedef struct RichString_ {
int len;
chtype chstr[RICHSTRING_MAXLEN+1];
} RichString;
RichString RichString_new();
void RichString_delete(RichString this);
void RichString_prune(RichString* this);
void RichString_write(RichString* this, int attrs, char* data);
inline void RichString_append(RichString* this, int attrs, char* data);
inline void RichString_appendn(RichString* this, int attrs, char* data, int len);
void RichString_setAttr(RichString *this, int attrs);
void RichString_applyAttr(RichString *this, int attrs);
RichString RichString_quickString(int attrs, char* data);
#endif

225
ScreenManager.c Normal file
View File

@ -0,0 +1,225 @@
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "ScreenManager.h"
#include "ListBox.h"
#include "Object.h"
#include "TypedVector.h"
#include "FunctionBar.h"
#include "debug.h"
#include <assert.h>
#include <stdbool.h>
/*{
typedef enum Orientation_ {
VERTICAL,
HORIZONTAL
} Orientation;
typedef struct ScreenManager_ {
int x1;
int y1;
int x2;
int y2;
Orientation orientation;
TypedVector* items;
TypedVector* fuBars;
int itemCount;
FunctionBar* fuBar;
bool owner;
} ScreenManager;
}*/
ScreenManager* ScreenManager_new(int x1, int y1, int x2, int y2, Orientation orientation, bool owner) {
ScreenManager* this;
this = malloc(sizeof(ScreenManager));
this->x1 = x1;
this->y1 = y1;
this->x2 = x2;
this->y2 = y2;
this->fuBar = NULL;
this->orientation = orientation;
this->items = TypedVector_new(LISTBOX_CLASS, owner, DEFAULT_SIZE);
this->fuBars = TypedVector_new(FUNCTIONBAR_CLASS, true, DEFAULT_SIZE);
this->itemCount = 0;
this->owner = owner;
return this;
}
void ScreenManager_delete(ScreenManager* this) {
TypedVector_delete(this->items);
TypedVector_delete(this->fuBars);
free(this);
}
inline int ScreenManager_size(ScreenManager* this) {
return this->itemCount;
}
void ScreenManager_add(ScreenManager* this, ListBox* item, FunctionBar* fuBar, int size) {
if (this->orientation == HORIZONTAL) {
int lastX = 0;
if (this->itemCount > 0) {
ListBox* last = (ListBox*) TypedVector_get(this->items, this->itemCount - 1);
lastX = last->x + last->w + 1;
}
if (size > 0) {
ListBox_resize(item, size, LINES-this->y1+this->y2);
} else {
ListBox_resize(item, COLS-this->x1+this->x2-lastX, LINES-this->y1+this->y2);
}
ListBox_move(item, lastX, this->y1);
}
// TODO: VERTICAL
TypedVector_add(this->items, item);
if (fuBar)
TypedVector_add(this->fuBars, fuBar);
else
TypedVector_add(this->fuBars, FunctionBar_new(0, NULL, NULL, NULL));
if (!this->fuBar && fuBar) this->fuBar = fuBar;
item->needsRedraw = true;
this->itemCount++;
}
ListBox* ScreenManager_remove(ScreenManager* this, int index) {
assert(this->itemCount > index);
ListBox* lb = (ListBox*) TypedVector_remove(this->items, index);
TypedVector_remove(this->fuBars, index);
this->fuBar = NULL;
this->itemCount--;
return lb;
}
void ScreenManager_setFunctionBar(ScreenManager* this, FunctionBar* fuBar) {
if (this->owner && this->fuBar)
FunctionBar_delete((Object*)this->fuBar);
this->fuBar = fuBar;
}
void ScreenManager_resize(ScreenManager* this, int x1, int y1, int x2, int y2) {
this->x1 = x1;
this->y1 = y1;
this->x2 = x2;
this->y2 = y2;
int items = this->itemCount;
int lastX = 0;
for (int i = 0; i < items - 1; i++) {
ListBox* lb = (ListBox*) TypedVector_get(this->items, i);
ListBox_resize(lb, lb->w, LINES-y1+y2);
ListBox_move(lb, lastX, y1);
lastX = lb->x + lb->w + 1;
}
ListBox* lb = (ListBox*) TypedVector_get(this->items, items-1);
ListBox_resize(lb, COLS-x1+x2-lastX, LINES-y1+y2);
ListBox_move(lb, lastX, y1);
}
void ScreenManager_run(ScreenManager* this, ListBox** lastFocus, int* lastKey) {
bool quit = false;
int focus = 0;
ListBox* lbFocus = (ListBox*) TypedVector_get(this->items, focus);
if (this->fuBar)
FunctionBar_draw(this->fuBar, NULL);
int ch;
while (!quit) {
int items = this->itemCount;
for (int i = 0; i < items; i++) {
ListBox* lb = (ListBox*) TypedVector_get(this->items, i);
ListBox_draw(lb, i == focus);
if (i < items) {
if (this->orientation == HORIZONTAL) {
mvvline(lb->y, lb->x+lb->w, ' ', lb->h+1);
}
}
}
FunctionBar* bar = (FunctionBar*) TypedVector_get(this->fuBars, focus);
if (bar)
this->fuBar = bar;
if (this->fuBar)
FunctionBar_draw(this->fuBar, NULL);
ch = getch();
bool loop = false;
if (ch == KEY_MOUSE) {
MEVENT mevent;
int ok = getmouse(&mevent);
if (ok == OK) {
if (mevent.y == LINES - 1) {
ch = FunctionBar_synthesizeEvent(this->fuBar, mevent.x);
} else {
for (int i = 0; i < this->itemCount; i++) {
ListBox* lb = (ListBox*) TypedVector_get(this->items, i);
if (mevent.x > lb->x && mevent.x <= lb->x+lb->w &&
mevent.y > lb->y && mevent.y <= lb->y+lb->h) {
focus = i;
lbFocus = lb;
ListBox_setSelected(lb, mevent.y - lb->y + lb->scrollV - 1);
loop = true;
break;
}
}
}
}
}
if (loop) continue;
if (lbFocus->eventHandler) {
HandlerResult result = lbFocus->eventHandler(lbFocus, ch);
if (result == HANDLED) {
continue;
} else if (result == BREAK_LOOP) {
quit = true;
continue;
}
}
switch (ch) {
case ERR:
continue;
case KEY_RESIZE:
{
ScreenManager_resize(this, this->x1, this->y1, this->x2, this->y2);
continue;
}
case KEY_LEFT:
tryLeft:
if (focus > 0)
focus--;
lbFocus = (ListBox*) TypedVector_get(this->items, focus);
if (ListBox_getSize(lbFocus) == 0 && focus > 0)
goto tryLeft;
break;
case KEY_RIGHT:
case 9:
tryRight:
if (focus < this->itemCount - 1)
focus++;
lbFocus = (ListBox*) TypedVector_get(this->items, focus);
if (ListBox_getSize(lbFocus) == 0 && focus < this->itemCount - 1)
goto tryRight;
break;
case KEY_F(10):
case 'q':
case 27:
quit = true;
continue;
default:
ListBox_onKey(lbFocus, ch);
break;
}
}
*lastFocus = lbFocus;
*lastKey = ch;
}

58
ScreenManager.h Normal file
View File

@ -0,0 +1,58 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_ScreenManager
#define HEADER_ScreenManager
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "ListBox.h"
#include "Object.h"
#include "TypedVector.h"
#include "FunctionBar.h"
#include "debug.h"
#include <assert.h>
#include <stdbool.h>
typedef enum Orientation_ {
VERTICAL,
HORIZONTAL
} Orientation;
typedef struct ScreenManager_ {
int x1;
int y1;
int x2;
int y2;
Orientation orientation;
TypedVector* items;
int itemCount;
FunctionBar* fuBar;
TypedVector* fuBars;
bool owner;
} ScreenManager;
ScreenManager* ScreenManager_new(int x1, int y1, int x2, int y2, Orientation orientation, bool owner);
void ScreenManager_delete(ScreenManager* this);
inline int ScreenManager_size(ScreenManager* this);
void ScreenManager_add(ScreenManager* this, ListBox* item, FunctionBar* fuBar, int size);
ListBox* ScreenManager_remove(ScreenManager* this, int index);
void ScreenManager_setFunctionBar(ScreenManager* this, FunctionBar* fuBar);
void ScreenManager_resize(ScreenManager* this, int x1, int y1, int x2, int y2);
void ScreenManager_run(ScreenManager* this, ListBox** lastFocus, int* lastKey);
#endif

217
Settings.c Normal file
View File

@ -0,0 +1,217 @@
/*
htop - Settings.c
(C) 2004,2005 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "Settings.h"
#include "String.h"
#include "ProcessList.h"
#include "Header.h"
#include "debug.h"
#define DEFAULT_DELAY 15
/*{
typedef struct Settings_ {
char* userSettings;
ProcessList* pl;
Header* header;
int colorScheme;
bool changed;
int delay;
} Settings;
}*/
Settings* Settings_new(ProcessList* pl, Header* header) {
Settings* this = malloc(sizeof(Settings));
this->pl = pl;
this->header = header;
char* home;
home = getenv("HOME_ETC");
if (!home) home = getenv("HOME");
if (!home) home = "";
this->userSettings = String_cat(home, "/.htoprc");
this->colorScheme = 0;
this->changed = false;
this->delay = DEFAULT_DELAY;
bool ok = Settings_read(this, this->userSettings);
if (!ok) {
this->changed = true;
// TODO: how to get SYSCONFDIR correctly through Autoconf?
char* systemSettings = String_cat(SYSCONFDIR, "/htoprc");
ok = Settings_read(this, systemSettings);
free(systemSettings);
if (!ok) {
Header_defaultMeters(this->header);
pl->hideKernelThreads = true;
pl->highlightMegabytes = true;
}
}
return this;
}
void Settings_delete(Settings* this) {
free(this->userSettings);
free(this);
}
/* private */
void Settings_readMeters(Settings* this, char* line, HeaderSide side) {
char* trim = String_trim(line);
char** ids = String_split(trim, ' ');
free(trim);
int i;
for (i = 0; ids[i] != NULL; i++) {
Header_createMeter(this->header, ids[i], side);
}
String_freeArray(ids);
}
/* private */
void Settings_readMeterModes(Settings* this, char* line, HeaderSide side) {
char* trim = String_trim(line);
char** ids = String_split(trim, ' ');
free(trim);
int i;
for (i = 0; ids[i] != NULL; i++) {
int mode = atoi(ids[i]);
Header_setMode(this->header, i, mode, side);
}
String_freeArray(ids);
}
bool Settings_read(Settings* this, char* fileName) {
// TODO: implement File object and make
// file I/O object-oriented.
FILE* fd;
fd = fopen(fileName, "r");
if (fd == NULL) {
return false;
}
const int maxLine = 512;
char buffer[maxLine];
bool readMeters = false;
while (!feof(fd)) {
buffer[0] = '\0';
fgets(buffer, maxLine, fd);
char** option = String_split(buffer, '=');
if (String_eq(option[0], "fields")) {
char* trim = String_trim(option[1]);
char** ids = String_split(trim, ' ');
free(trim);
int i, j;
for (j = 0, i = 0; i < LAST_PROCESSFIELD && ids[i] != NULL; i++) {
// This "+1" is for compatibility with the older enum format.
int id = atoi(ids[i]) + 1;
if (id > 0 && id < LAST_PROCESSFIELD) {
this->pl->fields[j] = id;
j++;
}
}
this->pl->fields[j] = (ProcessField) NULL;
String_freeArray(ids);
} else if (String_eq(option[0], "sort_key")) {
// This "+1" is for compatibility with the older enum format.
this->pl->sortKey = atoi(option[1]) + 1;
} else if (String_eq(option[0], "sort_direction")) {
this->pl->direction = atoi(option[1]);
} else if (String_eq(option[0], "tree_view")) {
this->pl->treeView = atoi(option[1]);
} else if (String_eq(option[0], "hide_threads")) {
this->pl->hideThreads = atoi(option[1]);
} else if (String_eq(option[0], "hide_kernel_threads")) {
this->pl->hideKernelThreads = atoi(option[1]);
} else if (String_eq(option[0], "hide_userland_threads")) {
this->pl->hideUserlandThreads = atoi(option[1]);
} else if (String_eq(option[0], "shadow_other_users")) {
this->pl->shadowOtherUsers = atoi(option[1]);
} else if (String_eq(option[0], "highlight_base_name")) {
this->pl->highlightBaseName = atoi(option[1]);
} else if (String_eq(option[0], "highlight_megabytes")) {
this->pl->highlightMegabytes = atoi(option[1]);
} else if (String_eq(option[0], "header_margin")) {
this->header->margin = atoi(option[1]);
} else if (String_eq(option[0], "delay")) {
this->delay = atoi(option[1]);
} else if (String_eq(option[0], "color_scheme")) {
this->colorScheme = atoi(option[1]);
if (this->colorScheme < 0) this->colorScheme = 0;
if (this->colorScheme > 5) this->colorScheme = 5;
} else if (String_eq(option[0], "left_meters")) {
Settings_readMeters(this, option[1], LEFT_HEADER);
readMeters = true;
} else if (String_eq(option[0], "right_meters")) {
Settings_readMeters(this, option[1], RIGHT_HEADER);
readMeters = true;
} else if (String_eq(option[0], "left_meter_modes")) {
Settings_readMeterModes(this, option[1], LEFT_HEADER);
readMeters = true;
} else if (String_eq(option[0], "right_meter_modes")) {
Settings_readMeterModes(this, option[1], RIGHT_HEADER);
readMeters = true;
}
String_freeArray(option);
}
fclose(fd);
if (!readMeters) {
Header_defaultMeters(this->header);
}
return true;
}
bool Settings_write(Settings* this) {
// TODO: implement File object and make
// file I/O object-oriented.
FILE* fd;
fd = fopen(this->userSettings, "w");
if (fd == NULL) {
return false;
}
fprintf(fd, "# Beware! This file is rewritten every time htop exits.\n");
fprintf(fd, "# The parser is also very primitive, and not human-friendly.\n");
fprintf(fd, "# (I know, it's in the todo list).\n");
fprintf(fd, "fields=");
for (int i = 0; this->pl->fields[i]; i++) {
// This "-1" is for compatibility with the older enum format.
fprintf(fd, "%d ", (int) this->pl->fields[i]-1);
}
fprintf(fd, "\n");
// This "-1" is for compatibility with the older enum format.
fprintf(fd, "sort_key=%d\n", (int) this->pl->sortKey-1);
fprintf(fd, "sort_direction=%d\n", (int) this->pl->direction);
fprintf(fd, "hide_threads=%d\n", (int) this->pl->hideThreads);
fprintf(fd, "hide_kernel_threads=%d\n", (int) this->pl->hideKernelThreads);
fprintf(fd, "hide_userland_threads=%d\n", (int) this->pl->hideUserlandThreads);
fprintf(fd, "shadow_other_users=%d\n", (int) this->pl->shadowOtherUsers);
fprintf(fd, "highlight_base_name=%d\n", (int) this->pl->highlightBaseName);
fprintf(fd, "highlight_megabytes=%d\n", (int) this->pl->highlightMegabytes);
fprintf(fd, "tree_view=%d\n", (int) this->pl->treeView);
fprintf(fd, "header_margin=%d\n", (int) this->header->margin);
fprintf(fd, "color_scheme=%d\n", (int) this->colorScheme);
fprintf(fd, "delay=%d\n", (int) this->delay);
fprintf(fd, "left_meters=");
for (int i = 0; i < Header_size(this->header, LEFT_HEADER); i++) {
fprintf(fd, "%s ", Header_readMeterName(this->header, i, LEFT_HEADER));
}
fprintf(fd, "\n");
fprintf(fd, "left_meter_modes=");
for (int i = 0; i < Header_size(this->header, LEFT_HEADER); i++)
fprintf(fd, "%d ", Header_readMeterMode(this->header, i, LEFT_HEADER));
fprintf(fd, "\n");
fprintf(fd, "right_meters=");
for (int i = 0; i < Header_size(this->header, RIGHT_HEADER); i++)
fprintf(fd, "%s ", Header_readMeterName(this->header, i, RIGHT_HEADER));
fprintf(fd, "\n");
fprintf(fd, "right_meter_modes=");
for (int i = 0; i < Header_size(this->header, RIGHT_HEADER); i++)
fprintf(fd, "%d ", Header_readMeterMode(this->header, i, RIGHT_HEADER));
fprintf(fd, "\n");
fclose(fd);
return true;
}

39
Settings.h Normal file
View File

@ -0,0 +1,39 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_Settings
#define HEADER_Settings
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "String.h"
#include "ProcessList.h"
#include "Header.h"
#include "debug.h"
typedef struct Settings_ {
char* userSettings;
ProcessList* pl;
Header* header;
int colorScheme;
int delay;
bool changed;
} Settings;
Settings* Settings_new(ProcessList* pl, Header* header);
void Settings_delete(Settings* this);
bool Settings_read(Settings* this, char* fileName);
bool Settings_write(Settings* this);
#endif

99
SignalItem.c Normal file
View File

@ -0,0 +1,99 @@
/*
htop - SignalItem.c
(C) 2004,2005 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "SignalItem.h"
#include "String.h"
#include "Object.h"
#include "RichString.h"
#include <string.h>
#include "debug.h"
#define SIGNAL_COUNT 34
/*{
typedef struct Signal_ {
Object super;
char* name;
int number;
} Signal;
extern char* SIGNAL_CLASS;
}*/
/* private property */
char* SIGNAL_CLASS = "Signal";
Signal* Signal_new(char* name, int number) {
Signal* this = malloc(sizeof(Signal));
((Object*)this)->class = SIGNAL_CLASS;
((Object*)this)->display = Signal_display;
((Object*)this)->delete = Signal_delete;
this->name = name;
this->number = number;
return this;
}
void Signal_delete(Object* cast) {
Signal* this = (Signal*)cast;
assert (this != NULL);
// names are string constants, so we're not deleting them.
free(this);
}
void Signal_display(Object* cast, RichString* out) {
Signal* this = (Signal*)cast;
assert (this != NULL);
char buffer[31];
snprintf(buffer, 30, "%2d %s", this->number, this->name);
RichString_write(out, CRT_colors[DEFAULT_COLOR], buffer);
}
int Signal_getSignalCount() {
return SIGNAL_COUNT;
}
Signal** Signal_getSignalTable() {
Signal** signals = malloc(sizeof(Signal*) * SIGNAL_COUNT);
signals[0] = Signal_new("Cancel", 0);
signals[1] = Signal_new("SIGHUP", 1);
signals[2] = Signal_new("SIGINT", 2);
signals[3] = Signal_new("SIGQUIT", 3);
signals[4] = Signal_new("SIGILL", 4);
signals[5] = Signal_new("SIGTRAP", 5);
signals[6] = Signal_new("SIGABRT", 6);
signals[7] = Signal_new("SIGIOT", 6);
signals[8] = Signal_new("SIGBUS", 7);
signals[9] = Signal_new("SIGFPE", 8);
signals[10] = Signal_new("SIGKILL", 9);
signals[11] = Signal_new("SIGUSR1", 10);
signals[12] = Signal_new("SIGSEGV", 11);
signals[13] = Signal_new("SIGUSR2", 12);
signals[14] = Signal_new("SIGPIPE", 13);
signals[15] = Signal_new("SIGALRM", 14);
signals[16] = Signal_new("SIGTERM", 15);
signals[17] = Signal_new("SIGSTKFLT", 16);
signals[18] = Signal_new("SIGCHLD", 17);
signals[19] = Signal_new("SIGCONT", 18);
signals[20] = Signal_new("SIGSTOP", 19);
signals[21] = Signal_new("SIGTSTP", 20);
signals[22] = Signal_new("SIGTTIN", 21);
signals[23] = Signal_new("SIGTTOU", 22);
signals[24] = Signal_new("SIGURG", 23);
signals[25] = Signal_new("SIGXCPU", 24);
signals[26] = Signal_new("SIGXFSZ", 25);
signals[27] = Signal_new("SIGVTALRM", 26);
signals[28] = Signal_new("SIGPROF", 27);
signals[29] = Signal_new("SIGWINCH", 28);
signals[30] = Signal_new("SIGIO", 29);
signals[31] = Signal_new("SIGPOLL", 29);
signals[32] = Signal_new("SIGPWR", 30);
signals[33] = Signal_new("SIGSYS", 31);
return signals;
}

41
SignalItem.h Normal file
View File

@ -0,0 +1,41 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_Signal
#define HEADER_Signal
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "String.h"
#include "Object.h"
#include "RichString.h"
#include <string.h>
#include "debug.h"
#define SIGNAL_COUNT 34
typedef struct Signal_ {
Object super;
char* name;
int number;
} Signal;
extern char* SIGNAL_CLASS;
Signal* Signal_new(char* name, int number);
void Signal_delete(Object* cast);
void Signal_display(Object* cast, RichString* out);
int Signal_getSignalCount();
Signal** Signal_getSignalTable();
#endif

77
SignalsListBox.c Normal file
View File

@ -0,0 +1,77 @@
#include "SignalsListBox.h"
#include "ListBox.h"
#include "SignalItem.h"
#include "RichString.h"
#include "debug.h"
#include <assert.h>
#include <ctype.h>
/*{
typedef struct SignalsListBox_ {
ListBox super;
int state;
Signal** signals;
} SignalsListBox;
}*/
SignalsListBox* SignalsListBox_new(int x, int y, int w, int h) {
SignalsListBox* this = (SignalsListBox*) malloc(sizeof(SignalsListBox));
ListBox* super = (ListBox*) this;
ListBox_init(super, x, y, w, h, SIGNAL_CLASS, true);
((Object*)this)->delete = SignalsListBox_delete;
this->signals = Signal_getSignalTable();
super->eventHandler = SignalsListBox_EventHandler;
int sigCount = Signal_getSignalCount();
for(int i = 0; i < sigCount; i++)
ListBox_set(super, i, (Object*) this->signals[i]);
SignalsListBox_reset(this);
return this;
}
void SignalsListBox_delete(Object* object) {
ListBox* super = (ListBox*) object;
SignalsListBox* this = (SignalsListBox*) object;
ListBox_done(super);
free(this->signals);
free(this);
}
void SignalsListBox_reset(SignalsListBox* this) {
ListBox* super = (ListBox*) this;
ListBox_setHeader(super, "Send signal:");
ListBox_setSelected(super, 16); // 16th item is SIGTERM
this->state = 0;
}
HandlerResult SignalsListBox_EventHandler(ListBox* super, int ch) {
SignalsListBox* this = (SignalsListBox*) super;
int size = ListBox_getSize(super);
if (ch <= 255 && isdigit(ch)) {
int signal = ch-48 + this->state;
for (int i = 0; i < size; i++)
if (((Signal*) ListBox_get(super, i))->number == signal) {
ListBox_setSelected(super, i);
break;
}
this->state = signal * 10;
if (this->state > 100)
this->state = 0;
return HANDLED;
} else {
this->state = 0;
}
if (ch == 13) {
return BREAK_LOOP;
}
return IGNORED;
}

32
SignalsListBox.h Normal file
View File

@ -0,0 +1,32 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_SignalsListBox
#define HEADER_SignalsListBox
#include "ListBox.h"
#include "SignalItem.h"
#include "RichString.h"
#include "debug.h"
#include <assert.h>
#include <ctype.h>
typedef struct SignalsListBox_ {
ListBox super;
int state;
Signal** signals;
} SignalsListBox;
SignalsListBox* SignalsListBox_new(int x, int y, int w, int h);
void SignalsListBox_delete(Object* object);
void SignalsListBox_reset(SignalsListBox* this);
HandlerResult SignalsListBox_EventHandler(ListBox* super, int ch);
#endif

160
String.c Normal file
View File

@ -0,0 +1,160 @@
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#define _GNU_SOURCE
#include "String.h"
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <stdio.h>
#include "debug.h"
inline void String_delete(char* s) {
free(s);
}
inline char* String_copy(char* orig) {
return strdup(orig);
}
char* String_cat(char* s1, char* s2) {
int l1 = strlen(s1);
int l2 = strlen(s2);
char* out = malloc(l1 + l2 + 1);
strncpy(out, s1, l1);
strncpy(out+l1, s2, l2+1);
return out;
}
char* String_trim(char* in) {
while (in[0] == ' ' || in[0] == '\t' || in[0] == '\n') {
in++;
}
int len = strlen(in);
while (len > 0 && (in[len-1] == ' ' || in[len-1] == '\t' || in[len-1] == '\n')) {
len--;
}
char* out = malloc(len+1);
strncpy(out, in, len);
out[len] = '\0';
return out;
}
char* String_copyUpTo(char* orig, char upTo) {
int len;
int origLen = strlen(orig);
char* at = strchr(orig, upTo);
if (at != NULL)
len = at - orig;
else
len = origLen;
char* copy = (char*) malloc(len+1);
strncpy(copy, orig, len);
copy[len] = '\0';
return copy;
}
char* String_sub(char* orig, int from, int to) {
char* copy;
int len;
len = strlen(orig);
if (to > len)
to = len;
if (from > len)
to = len;
len = to-from+1;
copy = (char*) malloc(len+1);
strncpy(copy, orig+from, len);
copy[len] = '\0';
return copy;
}
void String_println(char* s) {
printf("%s\n", s);
}
void String_print(char* s) {
printf("%s", s);
}
void String_printInt(int i) {
printf("%i", i);
}
void String_printPointer(void* p) {
printf("%p", p);
}
inline int String_eq(char* s1, char* s2) {
if (s1 == NULL || s2 == NULL) {
if (s1 == NULL && s2 == NULL)
return 1;
else
return 0;
}
return (strcmp(s1, s2) == 0);
}
inline int String_startsWith(char* s, char* match) {
return (strstr(s, match) == s);
}
char** String_split(char* s, char sep) {
const int rate = 10;
char** out = (char**) malloc(sizeof(char*) * rate);
int ctr = 0;
int blocks = rate;
char* where;
while ((where = strchr(s, sep)) != NULL) {
int size = where - s;
char* token = (char*) malloc(size + 1);
strncpy(token, s, size);
token[size] = '\0';
out[ctr] = token;
ctr++;
if (ctr == blocks) {
blocks += rate;
out = (char**) realloc(out, sizeof(char*) * blocks);
}
s += size + 1;
}
if (s[0] != '\0') {
int size = strlen(s);
char* token = (char*) malloc(size + 1);
strncpy(token, s, size + 1);
out[ctr] = token;
ctr++;
}
out = realloc(out, sizeof(char*) * (ctr + 1));
out[ctr] = NULL;
return out;
}
void String_freeArray(char** s) {
for (int i = 0; s[i] != NULL; i++) {
free(s[i]);
}
free(s);
}
int String_startsWith_i(char* s, char* match) {
return (strncasecmp(s, match, strlen(match)) == 0);
}
int String_contains_i(char* s, char* match) {
int lens = strlen(s);
int lenmatch = strlen(match);
for (int i = 0; i < lens-lenmatch; i++) {
if (strncasecmp(s, match, strlen(match)) == 0)
return 1;
s++;
}
return 0;
}

52
String.h Normal file
View File

@ -0,0 +1,52 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_String
#define HEADER_String
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#define _GNU_SOURCE
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <stdio.h>
#include "debug.h"
inline void String_delete(char* s);
inline char* String_copy(char* orig);
char* String_cat(char* s1, char* s2);
char* String_trim(char* in);
char* String_copyUpTo(char* orig, char upTo);
char* String_sub(char* orig, int from, int to);
void String_println(char* s);
void String_print(char* s);
void String_printInt(int i);
void String_printPointer(void* p);
inline int String_eq(char* s1, char* s2);
inline int String_startsWith(char* s, char* match);
char** String_split(char* s, char sep);
void String_freeArray(char** s);
int String_startsWith_i(char* s, char* match);
int String_contains_i(char* s, char* match);
#endif

65
SwapMeter.c Normal file
View File

@ -0,0 +1,65 @@
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "SwapMeter.h"
#include "Meter.h"
#include "ProcessList.h"
#include <stdlib.h>
#include <curses.h>
#include <string.h>
#include <math.h>
#include <sys/param.h>
#include "debug.h"
#include <assert.h>
/*{
typedef struct SwapMeter_ SwapMeter;
struct SwapMeter_ {
Meter super;
ProcessList* pl;
};
}*/
SwapMeter* SwapMeter_new(ProcessList* pl) {
SwapMeter* this = malloc(sizeof(SwapMeter));
Meter_init((Meter*)this, String_copy("Swap"), String_copy("Swp"), 1);
((Meter*)this)->attributes[0] = SWAP;
((Meter*)this)->setValues = SwapMeter_setValues;
((Object*)this)->display = SwapMeter_display;
this->pl = pl;
Meter_setMode((Meter*)this, BAR);
return this;
}
void SwapMeter_setValues(Meter* cast) {
SwapMeter* this = (SwapMeter*)cast;
double totalSwap = (double)this->pl->totalSwap;
long int usedSwap = this->pl->usedSwap;
cast->total = totalSwap;
cast->values[0] = usedSwap;
snprintf(cast->displayBuffer.c, 14, "%ld/%ldMB", usedSwap / 1024, this->pl->totalSwap / 1024);
}
void SwapMeter_display(Object* cast, RichString* out) {
char buffer[50];
Meter* meter = (Meter*)cast;
long int swap = (long int) meter->values[0];
RichString_prune(out);
RichString_append(out, CRT_colors[METER_TEXT], ":");
sprintf(buffer, "%ldM ", (long int) meter->total / 1024);
RichString_append(out, CRT_colors[METER_VALUE], buffer);
sprintf(buffer, "%ldk", swap);
RichString_append(out, CRT_colors[METER_TEXT], "used:");
RichString_append(out, CRT_colors[METER_VALUE], buffer);
}

40
SwapMeter.h Normal file
View File

@ -0,0 +1,40 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_SwapMeter
#define HEADER_SwapMeter
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "Meter.h"
#include "ProcessList.h"
#include <stdlib.h>
#include <curses.h>
#include <string.h>
#include <math.h>
#include <sys/param.h>
#include "debug.h"
#include <assert.h>
typedef struct SwapMeter_ SwapMeter;
struct SwapMeter_ {
Meter super;
ProcessList* pl;
};
SwapMeter* SwapMeter_new(ProcessList* pl);
void SwapMeter_setValues(Meter* cast);
void SwapMeter_display(Object* cast, RichString* out);
#endif

56
TasksMeter.c Normal file
View File

@ -0,0 +1,56 @@
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "TasksMeter.h"
#include "Meter.h"
#include "ProcessList.h"
#include "CRT.h"
#include "debug.h"
/*{
typedef struct TasksMeter_ TasksMeter;
struct TasksMeter_ {
Meter super;
ProcessList* pl;
};
}*/
TasksMeter* TasksMeter_new(ProcessList* pl) {
TasksMeter* this = malloc(sizeof(TasksMeter));
Meter_init((Meter*)this, String_copy("Tasks"), String_copy("Tasks: "), 1);
((Meter*)this)->attributes[0] = TASKS_RUNNING;
((Object*)this)->display = TasksMeter_display;
((Meter*)this)->setValues = TasksMeter_setValues;
this->pl = pl;
Meter_setMode((Meter*)this, TEXT);
return this;
}
void TasksMeter_setValues(Meter* cast) {
TasksMeter* this = (TasksMeter*)cast;
cast->total = this->pl->totalTasks;
cast->values[0] = this->pl->runningTasks;
snprintf(cast->displayBuffer.c, 20, "%d/%d", (int) cast->values[0], (int) cast->total);
}
void TasksMeter_display(Object* cast, RichString* out) {
Meter* this = (Meter*)cast;
RichString_prune(out);
char buffer[20];
sprintf(buffer, "%d", (int)this->total);
RichString_append(out, CRT_colors[METER_VALUE], buffer);
RichString_append(out, CRT_colors[METER_TEXT], " total, ");
sprintf(buffer, "%d", (int)this->values[0]);
RichString_append(out, CRT_colors[TASKS_RUNNING], buffer);
RichString_append(out, CRT_colors[METER_TEXT], " running");
}

35
TasksMeter.h Normal file
View File

@ -0,0 +1,35 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_TasksMeter
#define HEADER_TasksMeter
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "Meter.h"
#include "ProcessList.h"
#include "CRT.h"
#include "debug.h"
typedef struct TasksMeter_ TasksMeter;
struct TasksMeter_ {
Meter super;
ProcessList* pl;
};
TasksMeter* TasksMeter_new(ProcessList* pl);
void TasksMeter_setValues(Meter* cast);
void TasksMeter_display(Object* cast, RichString* out);
#endif

164
TraceScreen.c Normal file
View File

@ -0,0 +1,164 @@
/*
htop - TraceScreen.c
(C) 2005 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <stdbool.h>
#include <unistd.h>
#include <fcntl.h>
#include "TraceScreen.h"
#include "ProcessList.h"
#include "Process.h"
#include "ListItem.h"
/*{
typedef struct TraceScreen_ {
Process* process;
ListBox* display;
FunctionBar* bar;
bool tracing;
} TraceScreen;
}*/
/* private property */
static char* tbFunctions[3] = {"AutoScroll ", "Stop Tracing ", "Done "};
/* private property */
static char* tbKeys[3] = {"F4", "F5", "Esc"};
/* private property */
static int tbEvents[3] = {KEY_F(4), KEY_F(5), 27};
TraceScreen* TraceScreen_new(Process* process) {
TraceScreen* this = (TraceScreen*) malloc(sizeof(TraceScreen));
this->process = process;
this->display = ListBox_new(0, 1, COLS, LINES-2, LISTITEM_CLASS, true);
this->bar = FunctionBar_new(3, tbFunctions, tbKeys, tbEvents);
this->tracing = true;
return this;
}
void TraceScreen_delete(TraceScreen* this) {
ListBox_delete((Object*)this->display);
FunctionBar_delete((Object*)this->bar);
free(this);
}
void TraceScreen_draw(TraceScreen* this) {
attrset(CRT_colors[PANEL_HEADER_FOCUS]);
mvhline(0, 0, ' ', COLS);
mvprintw(0, 0, "Trace of process %d - %s", this->process->pid, this->process->comm);
attrset(CRT_colors[DEFAULT_COLOR]);
FunctionBar_draw(this->bar, NULL);
}
void TraceScreen_run(TraceScreen* this) {
// if (this->process->pid == getpid()) return;
char buffer[1001];
int fdpair[2];
int err = pipe(fdpair);
if (err == -1) return;
int child = fork();
if (child == -1) return;
if (child == 0) {
dup2(fdpair[1], STDERR_FILENO);
fcntl(fdpair[1], F_SETFL, O_NONBLOCK);
sprintf(buffer, "%d", this->process->pid);
execlp("strace", "strace", "-p", buffer, NULL);
exit(1);
}
fcntl(fdpair[0], F_SETFL, O_NONBLOCK);
FILE* strace = fdopen(fdpair[0], "r");
ListBox* lb = this->display;
int fd_strace = fileno(strace);
TraceScreen_draw(this);
CRT_disableDelay();
bool contLine = false;
bool follow = false;
bool looping = true;
while (looping) {
fd_set fds;
FD_ZERO(&fds);
FD_SET(fd_strace, &fds);
struct timeval tv;
tv.tv_sec = 0; tv.tv_usec = 500;
int ready = select(fd_strace+1, &fds, NULL, NULL, &tv);
int nread = 0;
if (ready > 0)
nread = fread(buffer, 1, 1000, strace);
if (nread && this->tracing) {
char* line = buffer;
buffer[nread] = '\0';
for (int i = 0; i < nread; i++) {
if (buffer[i] == '\n') {
buffer[i] = '\0';
if (contLine) {
ListItem_append((ListItem*)ListBox_get(lb,
ListBox_getSize(lb)-1), line);
contLine = false;
} else {
ListBox_add(lb, (Object*) ListItem_new(line, 0));
}
line = buffer+i+1;
}
}
if (line < buffer+nread) {
ListBox_add(lb, (Object*) ListItem_new(line, 0));
buffer[nread] = '\0';
contLine = true;
}
if (follow)
ListBox_setSelected(lb, ListBox_getSize(lb)-1);
ListBox_draw(lb, true);
}
int ch = getch();
if (ch == KEY_MOUSE) {
MEVENT mevent;
int ok = getmouse(&mevent);
if (ok == OK)
if (mevent.y >= lb->y && mevent.y < LINES - 1) {
ListBox_setSelected(lb, mevent.y - lb->y + lb->scrollV);
follow = false;
ch = 0;
} if (mevent.y == LINES - 1)
ch = FunctionBar_synthesizeEvent(this->bar, mevent.x);
}
switch(ch) {
case ERR:
continue;
case KEY_F(5):
this->tracing = !this->tracing;
FunctionBar_setLabel(this->bar, KEY_F(5), this->tracing?"Stop Tracing ":"Resume Tracing ");
TraceScreen_draw(this);
break;
case 'f':
case KEY_F(4):
follow = !follow;
if (follow)
ListBox_setSelected(lb, ListBox_getSize(lb)-1);
break;
case 'q':
case 27:
looping = false;
break;
case KEY_RESIZE:
ListBox_resize(lb, COLS, LINES-2);
TraceScreen_draw(this);
break;
default:
follow = false;
ListBox_onKey(lb, ch);
}
ListBox_draw(lb, true);
}
kill(child, SIGTERM);
fclose(strace);
}

37
TraceScreen.h Normal file
View File

@ -0,0 +1,37 @@
/*
htop - TraceScreen.h
(C) 2005 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#ifndef HEADER_TraceScreen
#define HEADER_TraceScreen
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <stdbool.h>
#include <unistd.h>
#include <fcntl.h>
#include "ProcessList.h"
#include "ListBox.h"
#include "FunctionBar.h"
typedef struct TraceScreen_ {
Process* process;
ListBox* display;
FunctionBar* bar;
bool tracing;
} TraceScreen;
TraceScreen* TraceScreen_new(Process* process);
void TraceScreen_delete(TraceScreen* this);
void TraceScreen_draw(TraceScreen* this);
void TraceScreen_run(TraceScreen* this);
#endif

257
TypedVector.c Normal file
View File

@ -0,0 +1,257 @@
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "TypedVector.h"
#include "Object.h"
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "debug.h"
#include <assert.h>
/*{
#ifndef DEFAULT_SIZE
#define DEFAULT_SIZE -1
#endif
typedef void(*TypedVector_procedure)(void*);
typedef struct TypedVector_ {
Object **array;
int arraySize;
int growthRate;
int items;
char* vectorType;
bool owner;
} TypedVector;
}*/
TypedVector* TypedVector_new(char* vectorType_, bool owner, int size) {
TypedVector* this;
if (size == DEFAULT_SIZE)
size = 10;
this = (TypedVector*) malloc(sizeof(TypedVector));
this->growthRate = size;
this->array = (Object**) calloc(size, sizeof(Object*));
this->arraySize = size;
this->items = 0;
this->vectorType = vectorType_;
this->owner = owner;
return this;
}
void TypedVector_delete(TypedVector* this) {
if (this->owner) {
for (int i = 0; i < this->items; i++)
if (this->array[i])
(this->array[i])->delete(this->array[i]);
}
free(this->array);
free(this);
}
/* private */
bool TypedVector_isConsistent(TypedVector* this) {
if (this->owner) {
for (int i = 0; i < this->items; i++)
if (this->array[i] && this->array[i]->class != this->vectorType)
return false;
return true;
} else {
return true;
}
}
void TypedVector_prune(TypedVector* this) {
assert(TypedVector_isConsistent(this));
int i;
for (i = 0; i < this->items; i++)
if (this->array[i]) {
if (this->owner)
(this->array[i])->delete(this->array[i]);
this->array[i] = NULL;
}
this->items = 0;
}
void TypedVector_sort(TypedVector* this) {
assert(TypedVector_isConsistent(this));
int i, j;
for (i = 1; i < this->items; i++) {
void* t = this->array[i];
for (j = i-1; j >= 0 && this->array[j]->compare(this->array[j], t) < 0; j--)
this->array[j+1] = this->array[j];
this->array[j+1] = t;
}
assert(TypedVector_isConsistent(this));
/*
for (int i = 0; i < this->items; i++) {
for (int j = i+1; j < this->items; j++) {
if (this->array[j]->compare(this->array[j], t) < 0) {
void* tmp = this->array[i];
this->array[i] = this->array[j];
this->array[j] = tmp;
}
}
}
*/
}
/* private */
void TypedVector_checkArraySize(TypedVector* this) {
assert(TypedVector_isConsistent(this));
if (this->items >= this->arraySize) {
int i;
i = this->arraySize;
this->arraySize = this->items + this->growthRate;
this->array = (Object**) realloc(this->array, sizeof(Object*) * this->arraySize);
for (; i < this->arraySize; i++)
this->array[i] = NULL;
}
assert(TypedVector_isConsistent(this));
}
void TypedVector_insert(TypedVector* this, int index, void* data_) {
assert(index >= 0);
assert(((Object*)data_)->class == this->vectorType);
Object* data = data_;
assert(TypedVector_isConsistent(this));
TypedVector_checkArraySize(this);
assert(this->array[this->items] == NULL);
for (int i = this->items; i >= index; i--) {
this->array[i+1] = this->array[i];
}
this->array[index] = data;
this->items++;
assert(TypedVector_isConsistent(this));
}
Object* TypedVector_take(TypedVector* this, int index) {
assert(index >= 0 && index < this->items);
assert(TypedVector_isConsistent(this));
Object* removed = this->array[index];
assert (removed != NULL);
this->items--;
for (int i = index; i < this->items; i++)
this->array[i] = this->array[i+1];
this->array[this->items] = NULL;
assert(TypedVector_isConsistent(this));
return removed;
}
Object* TypedVector_remove(TypedVector* this, int index) {
Object* removed = TypedVector_take(this, index);
if (this->owner) {
removed->delete(removed);
return NULL;
} else
return removed;
}
void TypedVector_moveUp(TypedVector* this, int index) {
assert(index >= 0 && index < this->items);
assert(TypedVector_isConsistent(this));
if (index == 0)
return;
Object* temp = this->array[index];
this->array[index] = this->array[index - 1];
this->array[index - 1] = temp;
}
void TypedVector_moveDown(TypedVector* this, int index) {
assert(index >= 0 && index < this->items);
assert(TypedVector_isConsistent(this));
if (index == this->items - 1)
return;
Object* temp = this->array[index];
this->array[index] = this->array[index + 1];
this->array[index + 1] = temp;
}
void TypedVector_set(TypedVector* this, int index, void* data_) {
assert(index >= 0);
assert(((Object*)data_)->class == this->vectorType);
Object* data = data_;
assert(TypedVector_isConsistent(this));
TypedVector_checkArraySize(this);
if (index >= this->items) {
this->items = index+1;
} else {
if (this->owner) {
Object* removed = this->array[index];
assert (removed != NULL);
if (this->owner) {
removed->delete(removed);
}
}
}
this->array[index] = data;
assert(TypedVector_isConsistent(this));
}
inline Object* TypedVector_get(TypedVector* this, int index) {
assert(index < this->items);
assert(TypedVector_isConsistent(this));
return this->array[index];
}
inline int TypedVector_size(TypedVector* this) {
assert(TypedVector_isConsistent(this));
return this->items;
}
void TypedVector_merge(TypedVector* this, TypedVector* v2) {
int i;
assert(TypedVector_isConsistent(this));
for (i = 0; i < v2->items; i++)
TypedVector_add(this, v2->array[i]);
v2->items = 0;
TypedVector_delete(v2);
assert(TypedVector_isConsistent(this));
}
void TypedVector_add(TypedVector* this, void* data_) {
assert(data_ && ((Object*)data_)->class == this->vectorType);
Object* data = data_;
assert(TypedVector_isConsistent(this));
TypedVector_set(this, this->items, data);
assert(TypedVector_isConsistent(this));
}
inline int TypedVector_indexOf(TypedVector* this, void* search_) {
assert(((Object*)search_)->class == this->vectorType);
Object* search = search_;
assert(TypedVector_isConsistent(this));
int i;
for (i = 0; i < this->items; i++) {
Object* o = (Object*)this->array[i];
if (o && o->compare(o, search) == 0)
return i;
}
return -1;
}
void TypedVector_foreach(TypedVector* this, TypedVector_procedure f) {
int i;
assert(TypedVector_isConsistent(this));
for (i = 0; i < this->items; i++)
f(this->array[i]);
assert(TypedVector_isConsistent(this));
}

69
TypedVector.h Normal file
View File

@ -0,0 +1,69 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_TypedVector
#define HEADER_TypedVector
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "Object.h"
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "debug.h"
#include <assert.h>
#ifndef DEFAULT_SIZE
#define DEFAULT_SIZE -1
#endif
typedef void(*TypedVector_procedure)(void*);
typedef struct TypedVector_ {
Object **array;
int arraySize;
int growthRate;
int items;
char* vectorType;
bool owner;
} TypedVector;
TypedVector* TypedVector_new(char* vectorType_, bool owner, int size);
void TypedVector_delete(TypedVector* this);
void TypedVector_prune(TypedVector* this);
void TypedVector_sort(TypedVector* this);
void TypedVector_insert(TypedVector* this, int index, void* data_);
Object* TypedVector_take(TypedVector* this, int index);
Object* TypedVector_remove(TypedVector* this, int index);
void TypedVector_moveUp(TypedVector* this, int index);
void TypedVector_moveDown(TypedVector* this, int index);
void TypedVector_set(TypedVector* this, int index, void* data_);
inline Object* TypedVector_get(TypedVector* this, int index);
inline int TypedVector_size(TypedVector* this);
void TypedVector_merge(TypedVector* this, TypedVector* v2);
void TypedVector_add(TypedVector* this, void* data_);
inline int TypedVector_indexOf(TypedVector* this, void* search_);
void TypedVector_foreach(TypedVector* this, TypedVector_procedure f);
#endif

77
UptimeMeter.c Normal file
View File

@ -0,0 +1,77 @@
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "UptimeMeter.h"
#include "Meter.h"
#include "ProcessList.h"
#include "CRT.h"
#include "debug.h"
/*{
typedef struct UptimeMeter_ UptimeMeter;
struct UptimeMeter_ {
Meter super;
ProcessList* pl;
int seconds;
int minutes;
int hours;
int days;
};
}*/
UptimeMeter* UptimeMeter_new() {
UptimeMeter* this = malloc(sizeof(UptimeMeter));
Meter_init((Meter*)this, String_copy("Uptime"), String_copy("Uptime: "), 1);
((Meter*)this)->attributes[0] = UPTIME;
((Object*)this)->display = UptimeMeter_display;
((Meter*)this)->setValues = UptimeMeter_setValues;
Meter_setMode((Meter*)this, TEXT);
((Meter*)this)->total = 100.0;
return this;
}
void UptimeMeter_setValues(Meter* cast) {
UptimeMeter* this = (UptimeMeter*)cast;
double uptime;
FILE* fd = fopen(PROCDIR "/uptime", "r");
fscanf(fd, "%lf", &uptime);
fclose(fd);
int totalseconds = (int) ceil(uptime);
this->seconds = totalseconds % 60;
this->minutes = (totalseconds-this->seconds) % 3600 / 60;
this->hours = (totalseconds-this->seconds-(this->minutes*60)) % 86400 / 3600;
this->days = (totalseconds-this->seconds-(this->minutes*60)-(this->hours*3600)) / 86400;
cast->values[0] = this->days;
if (this->days > cast->total) {
cast->total = this->days;
}
snprintf(cast->displayBuffer.c, 14, "%d", this->days);
}
void UptimeMeter_display(Object* cast, RichString* out) {
UptimeMeter* this = (UptimeMeter*)cast;
char buffer[20];
RichString_prune(out);
if (this->days > 100) {
sprintf(buffer, "%d days, ", this->days);
RichString_write(out, CRT_colors[LARGE_NUMBER], buffer);
} else if (this->days > 1) {
sprintf(buffer, "%d days, ", this->days);
RichString_write(out, CRT_colors[UPTIME], buffer);
} else if (this->days == 1) {
sprintf(buffer, "%d day, ", this->days);
RichString_write(out, CRT_colors[UPTIME], buffer);
}
sprintf(buffer, "%02d:%02d:%02d ", this->hours, this->minutes, this->seconds);
RichString_append(out, CRT_colors[UPTIME], buffer);
}

39
UptimeMeter.h Normal file
View File

@ -0,0 +1,39 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_UptimeMeter
#define HEADER_UptimeMeter
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "Meter.h"
#include "ProcessList.h"
#include "CRT.h"
#include "debug.h"
typedef struct UptimeMeter_ UptimeMeter;
struct UptimeMeter_ {
Meter super;
ProcessList* pl;
int seconds;
int minutes;
int hours;
int days;
};
UptimeMeter* UptimeMeter_new();
void UptimeMeter_setValues(Meter* cast);
void UptimeMeter_display(Object* cast, RichString* out);
#endif

56
UsersTable.c Normal file
View File

@ -0,0 +1,56 @@
/*
htop - UsersTable.c
(C) 2004,2005 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "UsersTable.h"
#include "Hashtable.h"
#include "String.h"
#include <stdio.h>
#include <strings.h>
#include <pwd.h>
#include <sys/types.h>
#include "debug.h"
#include <assert.h>
/*{
typedef struct UsersTable_ {
Hashtable* users;
} UsersTable;
}*/
UsersTable* UsersTable_new() {
UsersTable* this;
this = malloc(sizeof(UsersTable));
this->users = Hashtable_new(20, true);
return this;
}
void UsersTable_delete(UsersTable* this) {
Hashtable_delete(this->users);
free(this);
}
char* UsersTable_getRef(UsersTable* this, int uid) {
char* name = (char*) (Hashtable_get(this->users, uid));
if (name == NULL) {
struct passwd* userData = getpwuid(uid);
if (userData != NULL) {
name = String_copy(userData->pw_name);
Hashtable_put(this->users, uid, name);
}
}
return name;
}
inline int UsersTable_size(UsersTable* this) {
return (Hashtable_size(this->users));
}
inline void UsersTable_foreach(UsersTable* this, Hashtable_PairFunction f, void* userData) {
Hashtable_foreach(this->users, f, userData);
}

41
UsersTable.h Normal file
View File

@ -0,0 +1,41 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_UsersTable
#define HEADER_UsersTable
/*
htop
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "Hashtable.h"
#include "String.h"
#include <stdio.h>
#include <strings.h>
#include <pwd.h>
#include <sys/types.h>
#include "debug.h"
#include <assert.h>
#ifndef SYSCONFDIR
#define SYSCONFDIR "/etc"
#endif
typedef struct UsersTable_ {
Hashtable* users;
} UsersTable;
UsersTable* UsersTable_new();
void UsersTable_delete(UsersTable* this);
char* UsersTable_getRef(UsersTable* this, int uid);
inline int UsersTable_size(UsersTable* this);
void UsersTable_foreach(UsersTable*, Hashtable_PairFunction, void*);
#endif

6
autogen.sh Normal file
View File

@ -0,0 +1,6 @@
#!/bin/sh
aclocal
autoconf
autoheader
automake

54
configure.ac Normal file
View File

@ -0,0 +1,54 @@
# -*- Autoconf -*-
# Process this file with autoconf to produce a configure script.
AC_PREREQ(2.57)
AC_INIT([htop],[UNRELEASED-2006.01.12],[loderunner@users.sourceforge.net])
AM_INIT_AUTOMAKE
AC_CONFIG_SRCDIR([htop.c])
AC_CONFIG_HEADER([config.h])
# Checks for programs.
AC_PROG_CC
# Checks for libraries.
AC_CHECK_LIB([ncurses], [refresh])
AC_CHECK_LIB([m], [ceil])
# Checks for header files.
AC_HEADER_DIRENT
AC_HEADER_STDC
AC_CHECK_HEADERS([stdlib.h string.h strings.h sys/param.h sys/time.h unistd.h curses.h])
# Checks for typedefs, structures, and compiler characteristics.
AC_HEADER_STDBOOL
AC_C_CONST
AC_TYPE_PID_T
AC_TYPE_UID_T
# Checks for library functions.
AC_FUNC_CLOSEDIR_VOID
AC_FUNC_MALLOC
AC_FUNC_REALLOC
AC_TYPE_SIGNAL
AC_FUNC_STAT
AC_CHECK_FUNCS([memmove strncasecmp strstr strdup])
CFLAGS="${CFLAGS} -std=c99"
AC_MSG_CHECKING([whether gcc -std=c99 option works])
AC_TRY_COMPILE(AC_INCLUDES_DEFAULT, [char *a; a = strdup("foo"); int i = 0; i++; // C99],
AC_MSG_RESULT([yes]),
AC_MSG_ERROR([htop is written in C99. A newer version of gcc is required.]))
PROCDIR=/proc
AC_ARG_WITH(proc, [ --with-proc=DIR Location of a Linux-compatible proc filesystem (default=/proc).],
if test -n "$withval"; then
AC_DEFINE_UNQUOTED(PROCDIR, "$withval", [Path of proc filesystem])
fi,
AC_DEFINE(PROCDIR, "/proc", [Path of proc filesystem]))
AC_CHECK_FILE(/proc/stat,,AC_MSG_ERROR(Cannot find /proc/stat. Make sure you have a Linux-compatible /proc filesystem mounted. See the file README for help.))
AC_CHECK_FILE(/proc/meminfo,,AC_MSG_ERROR(Cannot find /proc/meminfo. Make sure you have a Linux-compatible /proc filesystem mounted. See the file README for help.))
AC_CONFIG_FILES([Makefile])
AC_OUTPUT

22
debug.h Normal file
View File

@ -0,0 +1,22 @@
#ifdef DEBUG
#include "DebugMemory.h"
#define calloc(a, b) DebugMemory_calloc(a, b, __FILE__, __LINE__);
#define malloc(x) DebugMemory_malloc(x, __FILE__, __LINE__);
#define realloc(x,s) DebugMemory_realloc(x, s, __FILE__, __LINE__);
#define strdup(x) DebugMemory_strdup(x, __FILE__, __LINE__);
#define free(x) DebugMemory_free(x, __FILE__, __LINE__);
#define debug_done() DebugMemory_report();
#endif
#ifndef DEBUG
#define NDEBUG
#define debug_done() sleep(0)
#endif

120
htop.1 Normal file
View File

@ -0,0 +1,120 @@
.TH "htop" "1" "0.6" "Bartosz Fenski <fenio@o2.pl>" "Utils"
.SH "NAME"
htop \- interactive process viewer
.SH "SYNTAX"
.LP
.B htop
.SH "DESCRIPTION"
.LP
This program is a free (GPL) ncurses-based process viewer.
.LP
It is similar to top, but allows to scroll the list vertically and
horizontally to see all processes and their full command lines.
.LP
Tasks related to processes (killing, renicing) can be done without
entering their PIDs.
.br
.SH "INTERACTIVE COMMANDS"
.LP
The following commands are supported:
.LP
.TP 5
.B Arrows, PgUP, PgDn, Home, End
Scroll process list.
.TP
.B Space
"Tag": mark a process. Commands that can operate on multiple processes,
like "kill", will then apply over the list of tagged processes, instead
of the currently highlighted one.
.TP
.B U
"Untag" all processes (remove all tags added with the Space key).
.TP
.B s
Trace process system calls: if strace(1) is installed, pressing this key
will attach it to the currently selected process, presenting a live
update of system calls issued by the process.
.TP
.B F1, h
Help screen
.TP
.B F2, S
Setup screen. There you can configure meters displayed on the top side
of the screen, as well as set various display options, choose among
color schemes and select the layout of the displayed columns.
.TP
.B F3, /
Incremental process search: type in part of a process command line and
the selection highlight will be moved to it. While in search mode,
pressing this key will cycle through matching occurrences.
.TP
.B F4, I
Invert sort order: if sort order is increasing, switch to decreasing,
and vice-versa.
.TP
.B F5, t
Tree view: organize processes by parenthood, and layout the relations
between them as a tree. Toggling the key will switch between tree and
your previously selected sort view. Selecting a sort view will exit
tree view.
.TP
.B F6, >
Select field for sorting. The sort field is indicated by a
highlight in the header.
.TP
.B F7, ], -
Increase selected process priority (subtract from 'nice' value).
This can be done by the superuser only.
.TP
.B F8, [, +
Decrease selected process priority (add to 'nice' value)
.TP
.B F9, k
"Kill" process: sends a signal which is selected in a menu, to one or a group
of processes. If processes were tagged, sends the signal to all tagged processes.
If none is tagged, sends to the currently selected process.
.TP
.B F10, q
Quit
.TP
.B u
Show only processes owned by a specified user.
.TP
.B M
Sort by memory usage (top compatibility key).
.TP
.B P
Sort by processor usage (top compatibility key).
.TP
.B T
Sort by time (top compatibility key).
.TP
.B F
"Follow" process: if the sort order causes the currently selected process
to move in the list, make the selection bar follow it. This is useful for
monitoring a process: this way, you can keep a process always visible on
screen. When a movement key is used, "follow" loses effect.
.TP
.B K
Hide kernel threads: prevent the threads belonging the kernel to be
displayed in the process list. (This is a toggle key.)
.TP
.B H
Hide user threads: on systems that represent them differently than ordinary
processes (such as recent NPTL-based systems), this can hide threads from
userspace processes in the process list. (This is a toggle key.)
.TP
.B Ctrl-L
Refresh: redraw screen and recalculate values.
.TP
.B Numbers
PID search: type in process ID and the selection highlight will be moved to it.
.PD
.SH "AUTHORS"
.LP
htop is developed by Hisham Muhammad <lode@gobolinux.org>.
.br
This man page was written by Bartosz Fenski <fenio@o2.pl> for the
Debian GNU/Linux distribution (but it may be used by others), and
updated by Hisham Muhammad.

663
htop.c Normal file
View File

@ -0,0 +1,663 @@
/*
htop - htop.c
(C) 2004,2005 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#define _GNU_SOURCE
#include <unistd.h>
#include <math.h>
#include <sys/param.h>
#include <ctype.h>
#include <stdbool.h>
#include "ProcessList.h"
#include "CRT.h"
#include "ListBox.h"
#include "UsersTable.h"
#include "SignalItem.h"
#include "RichString.h"
#include "Settings.h"
#include "ScreenManager.h"
#include "FunctionBar.h"
#include "ListItem.h"
#include "CategoriesListBox.h"
#include "SignalsListBox.h"
#include "TraceScreen.h"
#include "config.h"
#include "debug.h"
//#link m
#define INCSEARCH_MAX 40
/* private property */
char htop_barCharacters[] = "|#*@$%&";
void printVersionFlag() {
clear();
printf("htop " VERSION " - (C) 2004,2005 Hisham Muhammad.\n");
printf("Released under the GNU GPL.\n\n");
exit(0);
}
void printHelpFlag() {
clear();
printf("htop " VERSION " - (C) 2004,2005 Hisham Muhammad.\n");
printf("Released under the GNU GPL.\n\n");
printf("-d DELAY Delay between updates, in tenths of seconds\n\n");
printf("-u USERNAME Show only processes of a given user\n\n");
printf("Press F1 inside htop for online help.\n");
printf("See the man page for full information.\n\n");
exit(0);
}
void showHelp() {
clear();
attrset(CRT_colors[HELP_BOLD]);
mvaddstr(0, 0, "htop " VERSION " - (C) 2004-2006 Hisham Muhammad.");
mvaddstr(1, 0, "Released under the GNU GPL. See 'man' page for more info.");
attrset(CRT_colors[DEFAULT_COLOR]);
mvaddstr(3, 0, "CPU usage bar: ");
#define addattrstr(a,s) attrset(a);addstr(s)
addattrstr(CRT_colors[BAR_BORDER], "[");
addattrstr(CRT_colors[CPU_NICE], "low-priority"); addstr("/");
addattrstr(CRT_colors[CPU_NORMAL], "normal"); addstr("/");
addattrstr(CRT_colors[CPU_KERNEL], "kernel");
addattrstr(CRT_colors[BAR_SHADOW], " used%");
addattrstr(CRT_colors[BAR_BORDER], "]");
attrset(CRT_colors[DEFAULT_COLOR]);
mvaddstr(4, 0, "Memory bar: ");
addattrstr(CRT_colors[BAR_BORDER], "[");
addattrstr(CRT_colors[MEMORY_USED], "used"); addstr("/");
addattrstr(CRT_colors[MEMORY_BUFFERS], "buffers"); addstr("/");
addattrstr(CRT_colors[MEMORY_CACHE], "cache");
addattrstr(CRT_colors[BAR_SHADOW], " used/total");
addattrstr(CRT_colors[BAR_BORDER], "]");
attrset(CRT_colors[DEFAULT_COLOR]);
mvaddstr(5, 0, "Swap bar: ");
addattrstr(CRT_colors[BAR_BORDER], "[");
addattrstr(CRT_colors[SWAP], "used");
addattrstr(CRT_colors[BAR_SHADOW], " used/total");
addattrstr(CRT_colors[BAR_BORDER], "]");
attrset(CRT_colors[DEFAULT_COLOR]);
mvaddstr(6,0, "Type and layout of header meters is configurable in the setup screen.");
mvaddstr( 8, 0, " Arrows: scroll process list F5 t: tree view");
mvaddstr( 9, 0, " Digits: incremental PID search u: show processes of a single user");
mvaddstr(10, 0, " F3 /: incremental name search H: hide/show user threads");
mvaddstr(11, 0, " K: hide/show kernel threads");
mvaddstr(12, 0, " Space: tag processes F: cursor follows process");
mvaddstr(13, 0, " U: untag all processes");
mvaddstr(14, 0, " F9 k: kill process/tagged processes P: sort by CPU%");
mvaddstr(15, 0, " + [ F7: lower priority (+ nice) M: sort by MEM%");
mvaddstr(16, 0, " - ] F8: higher priority (root only) T: sort by TIME");
mvaddstr(17, 0, " F4 I: invert sort order");
mvaddstr(18, 0, " F2 S: setup F6 >: select sort column");
mvaddstr(19, 0, " F1 h: show this help screen");
mvaddstr(20, 0, " F10 q: quit s: trace syscalls with strace");
attrset(CRT_colors[HELP_BOLD]);
mvaddstr( 8, 0, " Arrows"); mvaddstr( 8,40, " F5 t");
mvaddstr( 9, 0, " Digits"); mvaddstr( 9,40, " u");
mvaddstr(10, 0, " F3 /"); mvaddstr(10,40, " H");
mvaddstr(11,40, " K");
mvaddstr(12, 0, " Space"); mvaddstr(12,40, " F");
mvaddstr(13, 0, " U");
mvaddstr(14, 0, " F9 k"); mvaddstr(14,40, " P");
mvaddstr(15, 0, " + [ F7"); mvaddstr(15,40, " M");
mvaddstr(16, 0, " - ] F8"); mvaddstr(16,40, " T");
mvaddstr(17,40, " F4 I");
mvaddstr(18, 0, " F2 S"); mvaddstr(18,40, " F6 >");
mvaddstr(19, 0, " F1 h");
mvaddstr(20, 0, " F10 q"); mvaddstr(20,40, " s");
attrset(CRT_colors[DEFAULT_COLOR]);
attrset(CRT_colors[HELP_BOLD]);
mvaddstr(23,0, "Press any key to return.");
attrset(CRT_colors[DEFAULT_COLOR]);
refresh();
CRT_readKey();
clear();
}
static void Setup_run(Settings* settings, int headerHeight) {
ScreenManager* scr = ScreenManager_new(0, headerHeight, 0, -1, HORIZONTAL, true);
CategoriesListBox* lbCategories = CategoriesListBox_new(settings, scr);
ScreenManager_add(scr, (ListBox*) lbCategories, NULL, 16);
CategoriesListBox_makeMetersPage(lbCategories);
ListBox* lbFocus;
int ch;
ScreenManager_run(scr, &lbFocus, &ch);
ScreenManager_delete(scr);
}
static bool changePriority(ListBox* lb, int delta) {
bool anyTagged = false;
for (int i = 0; i < ListBox_getSize(lb); i++) {
Process* p = (Process*) ListBox_get(lb, i);
if (p->tag) {
Process_setPriority(p, p->nice + delta);
anyTagged = true;
}
}
if (!anyTagged) {
Process* p = (Process*) ListBox_getSelected(lb);
Process_setPriority(p, p->nice + delta);
}
return anyTagged;
}
static HandlerResult pickWithEnter(ListBox* lb, int ch) {
if (ch == 13)
return BREAK_LOOP;
return IGNORED;
}
static Object* pickFromList(ListBox* lb, ListBox* list, int x, int y, char** keyLabels, FunctionBar* prevBar) {
char* fuKeys[2] = {"Enter", "Esc"};
int fuEvents[2] = {13, 27};
if (!lb->eventHandler)
ListBox_setEventHandler(list, pickWithEnter);
ScreenManager* scr = ScreenManager_new(0, y, 0, -1, HORIZONTAL, false);
ScreenManager_add(scr, list, FunctionBar_new(2, keyLabels, fuKeys, fuEvents), x - 1);
ScreenManager_add(scr, lb, NULL, -1);
ListBox* lbFocus;
int ch;
ScreenManager_run(scr, &lbFocus, &ch);
ScreenManager_delete(scr);
ListBox_move(lb, 0, y);
ListBox_resize(lb, COLS, LINES-y-1);
FunctionBar_draw(prevBar, NULL);
if (lbFocus == list && ch == 13) {
return ListBox_getSelected(list);
}
return NULL;
}
void addUserToList(int key, void* userCast, void* lbCast) {
char* user = (char*) userCast;
ListBox* lb = (ListBox*) lbCast;
ListBox_add(lb, (Object*) ListItem_new(user, key));
}
void setUserOnly(const char* userName, bool* userOnly, uid_t* userId) {
struct passwd* user = getpwnam(userName);
if (user) {
*userOnly = true;
*userId = user->pw_uid;
}
}
int main(int argc, char** argv) {
int delay = -1;
bool userOnly = false;
uid_t userId = 0;
if (argc > 0) {
if (String_eq(argv[1], "--help")) {
printHelpFlag();
} else if (String_eq(argv[1], "--version")) {
printVersionFlag();
} else if (String_eq(argv[1], "-d")) {
if (argc < 2) printHelpFlag();
sscanf(argv[2], "%d", &delay);
if (delay < 1) delay = 1;
if (delay > 100) delay = 100;
} else if (String_eq(argv[1], "-u")) {
if (argc < 2) printHelpFlag();
setUserOnly(argv[2], &userOnly, &userId);
}
}
ListBox* lb;
int quit = 0;
int refreshTimeout = 0;
int resetRefreshTimeout = 5;
bool doRefresh = true;
Settings* settings;
ListBox* lbk = NULL;
char incSearchBuffer[INCSEARCH_MAX];
int incSearchIndex = 0;
incSearchBuffer[0] = 0;
bool incSearchMode = false;
ProcessList* pl = NULL;
UsersTable* ut = UsersTable_new();
pl = ProcessList_new(ut);
Header* header = Header_new(pl);
settings = Settings_new(pl, header);
int headerHeight = Header_calculateHeight(header);
// FIXME: move delay code to settings
if (delay != -1)
settings->delay = delay;
CRT_init(settings->delay, settings->colorScheme);
lb = ListBox_new(0, headerHeight, COLS, LINES - headerHeight - 2, PROCESS_CLASS, false);
ListBox_setRichHeader(lb, ProcessList_printHeader(pl));
char* searchFunctions[3] = {"Next ", "Exit ", " Search: "};
char* searchKeys[3] = {"F3", "Esc", " "};
int searchEvents[3] = {KEY_F(3), 27, ERR};
FunctionBar* searchBar = FunctionBar_new(3, searchFunctions, searchKeys, searchEvents);
char* defaultFunctions[10] = {"Help ", "Setup ", "Search", "Invert", "Tree ",
"SortBy", "Nice -", "Nice +", "Kill ", "Quit "};
FunctionBar* defaultBar = FunctionBar_new(10, defaultFunctions, NULL, NULL);
ProcessList_scan(pl);
usleep(75000);
FunctionBar_draw(defaultBar, NULL);
int acc = 0;
bool follow = false;
struct timeval tv;
double newTime = 0.0;
double oldTime = 0.0;
bool recalculate;
int ch = 0;
int closeTimeout = 0;
while (!quit) {
gettimeofday(&tv, NULL);
newTime = ((double)tv.tv_sec * 10) + ((double)tv.tv_usec / 100000);
recalculate = (newTime - oldTime > CRT_delay);
if (recalculate)
oldTime = newTime;
if (doRefresh) {
incSearchIndex = 0;
incSearchBuffer[0] = 0;
int currPos = ListBox_getSelectedIndex(lb);
int currPid = 0;
int currScrollV = lb->scrollV;
if (follow)
currPid = ProcessList_get(pl, currPos)->pid;
if (recalculate)
ProcessList_scan(pl);
if (refreshTimeout == 0) {
ProcessList_sort(pl);
refreshTimeout = 1;
}
ListBox_prune(lb);
int size = ProcessList_size(pl);
int lbi = 0;
for (int i = 0; i < size; i++) {
Process* p = ProcessList_get(pl, i);
if (!userOnly || (p->st_uid == userId)) {
ListBox_set(lb, lbi, (Object*)p);
if ((!follow && lbi == currPos) || (follow && p->pid == currPid)) {
ListBox_setSelected(lb, lbi);
lb->scrollV = currScrollV;
}
lbi++;
}
}
}
doRefresh = true;
Header_draw(header);
ListBox_draw(lb, true);
int prev = ch;
ch = getch();
if (ch == ERR) {
if (!incSearchMode)
refreshTimeout--;
if (prev == ch && !recalculate) {
closeTimeout++;
if (closeTimeout == 10)
break;
} else
closeTimeout = 0;
continue;
}
if (incSearchMode) {
doRefresh = false;
if (ch == KEY_F(3)) {
int here = ListBox_getSelectedIndex(lb);
int size = ProcessList_size(pl);
int i = here+1;
while (i != here) {
if (i == size)
i = 0;
Process* p = ProcessList_get(pl, i);
if (String_contains_i(p->comm, incSearchBuffer)) {
ListBox_setSelected(lb, i);
break;
}
i++;
}
continue;
} else if (isprint((char)ch) && (incSearchIndex < INCSEARCH_MAX)) {
incSearchBuffer[incSearchIndex] = ch;
incSearchIndex++;
incSearchBuffer[incSearchIndex] = 0;
} else if ((ch == KEY_BACKSPACE || ch == 127) && (incSearchIndex > 0)) {
incSearchIndex--;
incSearchBuffer[incSearchIndex] = 0;
} else {
incSearchMode = false;
incSearchIndex = 0;
incSearchBuffer[0] = 0;
FunctionBar_draw(defaultBar, NULL);
continue;
}
bool found = false;
for (int i = 0; i < ProcessList_size(pl); i++) {
Process* p = ProcessList_get(pl, i);
if (String_contains_i(p->comm, incSearchBuffer)) {
ListBox_setSelected(lb, i);
found = true;
break;
}
}
if (found)
FunctionBar_draw(searchBar, incSearchBuffer);
else
FunctionBar_drawAttr(searchBar, incSearchBuffer, CRT_colors[FAILED_SEARCH]);
continue;
}
if (isdigit((char)ch)) {
int pid = ch-48 + acc;
for (int i = 0; i < ProcessList_size(pl) && ((Process*) ListBox_getSelected(lb))->pid != pid; i++)
ListBox_setSelected(lb, i);
acc = pid * 10;
if (acc > 100000)
acc = 0;
continue;
} else {
acc = 0;
}
if (ch == KEY_MOUSE) {
MEVENT mevent;
int ok = getmouse(&mevent);
if (ok == OK) {
if (mevent.y >= lb->y + 1 && mevent.y < LINES - 1) {
ListBox_setSelected(lb, mevent.y - lb->y + lb->scrollV - 1);
doRefresh = false;
refreshTimeout = resetRefreshTimeout;
follow = true;
continue;
} if (mevent.y == LINES - 1) {
FunctionBar* bar;
if (incSearchMode) bar = searchBar;
else bar = defaultBar;
ch = FunctionBar_synthesizeEvent(bar, mevent.x);
}
}
}
switch (ch) {
case KEY_RESIZE:
ListBox_resize(lb, COLS, LINES-headerHeight-1);
if (incSearchMode)
FunctionBar_draw(searchBar, incSearchBuffer);
else
FunctionBar_draw(defaultBar, NULL);
break;
case 'M':
{
refreshTimeout = 0;
pl->sortKey = PERCENT_MEM;
pl->treeView = false;
settings->changed = true;
ListBox_setRichHeader(lb, ProcessList_printHeader(pl));
break;
}
case 'T':
{
refreshTimeout = 0;
pl->sortKey = TIME;
pl->treeView = false;
settings->changed = true;
ListBox_setRichHeader(lb, ProcessList_printHeader(pl));
break;
}
case 'U':
{
for (int i = 0; i < ListBox_getSize(lb); i++) {
Process* p = (Process*) ListBox_get(lb, i);
p->tag = false;
}
doRefresh = true;
break;
}
case 'P':
{
refreshTimeout = 0;
pl->sortKey = PERCENT_CPU;
pl->treeView = false;
settings->changed = true;
ListBox_setRichHeader(lb, ProcessList_printHeader(pl));
break;
}
case KEY_F(1):
case 'h':
{
showHelp();
FunctionBar_draw(defaultBar, NULL);
refreshTimeout = 0;
break;
}
case '\014': // Ctrl+L
{
clear();
FunctionBar_draw(defaultBar, NULL);
refreshTimeout = 0;
break;
}
case ' ':
{
Process* p = (Process*) ListBox_getSelected(lb);
Process_toggleTag(p);
ListBox_onKey(lb, KEY_DOWN);
break;
}
case 's':
{
TraceScreen* ts = TraceScreen_new((Process*) ListBox_getSelected(lb));
TraceScreen_run(ts);
TraceScreen_delete(ts);
clear();
FunctionBar_draw(defaultBar, NULL);
refreshTimeout = 0;
CRT_enableDelay();
break;
}
case 'S':
case 'C':
case KEY_F(2):
{
Setup_run(settings, headerHeight);
// TODO: shouldn't need this, colors should be dynamic
ListBox_setRichHeader(lb, ProcessList_printHeader(pl));
headerHeight = Header_calculateHeight(header);
ListBox_move(lb, 0, headerHeight);
ListBox_resize(lb, COLS, LINES-headerHeight-1);
FunctionBar_draw(defaultBar, NULL);
refreshTimeout = 0;
break;
}
case 'F':
{
follow = true;
continue;
}
case 'u':
{
ListBox* lbu = ListBox_new(0, 0, 0, 0, LISTITEM_CLASS, true);
ListBox_setHeader(lbu, "Show processes of:");
UsersTable_foreach(ut, addUserToList, lbu);
TypedVector_sort(lbu->items);
ListItem* allUsers = ListItem_new("All users", -1);
ListBox_insert(lbu, 0, (Object*) allUsers);
char* fuFunctions[2] = {"Show ", "Cancel "};
ListItem* picked = (ListItem*) pickFromList(lb, lbu, 20, headerHeight, fuFunctions, defaultBar);
if (picked) {
if (picked == allUsers) {
userOnly = false;
break;
} else {
setUserOnly(ListItem_getRef(picked), &userOnly, &userId);
}
}
break;
}
case KEY_F(9):
case 'k':
{
if (!lbk) {
lbk = (ListBox*) SignalsListBox_new(0, 0, 0, 0);
}
SignalsListBox_reset((SignalsListBox*) lbk);
char* fuFunctions[2] = {"Send ", "Cancel "};
Signal* signal = (Signal*) pickFromList(lb, lbk, 15, headerHeight, fuFunctions, defaultBar);
if (signal) {
if (signal->number != 0) {
ListBox_setHeader(lb, "Sending...");
ListBox_draw(lb, true);
refresh();
bool anyTagged = false;
for (int i = 0; i < ListBox_getSize(lb); i++) {
Process* p = (Process*) ListBox_get(lb, i);
if (p->tag) {
Process_sendSignal(p, signal->number);
Process_toggleTag(p);
anyTagged = true;
}
}
if (!anyTagged) {
Process* p = (Process*) ListBox_getSelected(lb);
Process_sendSignal(p, signal->number);
}
napms(500);
}
}
ListBox_setRichHeader(lb, ProcessList_printHeader(pl));
refreshTimeout = 0;
break;
}
case KEY_F(10):
case 'q':
quit = 1;
break;
case '<':
case ',':
case KEY_F(18):
case '>':
case '.':
case KEY_F(6):
{
ListBox* lbf = ListBox_new(0,0,0,0,LISTITEM_CLASS,true);
ListBox_setHeader(lbf, "Sort by");
char* fuFunctions[2] = {"Sort ", "Cancel "};
ProcessField* fields = pl->fields;
for (int i = 0; fields[i]; i++) {
char* name = String_trim(Process_printField(fields[i]));
ListBox_add(lbf, (Object*) ListItem_new(name, fields[i]));
if (fields[i] == pl->sortKey)
ListBox_setSelected(lbf, i);
free(name);
}
ListItem* field = (ListItem*) pickFromList(lb, lbf, 15, headerHeight, fuFunctions, defaultBar);
if (field) {
pl->treeView = false;
settings->changed = true;
pl->sortKey = field->key;
}
((Object*)lbf)->delete((Object*)lbf);
ListBox_setRichHeader(lb, ProcessList_printHeader(pl));
refreshTimeout = 0;
break;
}
case 'I':
case KEY_F(4):
{
refreshTimeout = 0;
settings->changed = true;
ProcessList_invertSortOrder(pl);
break;
}
case KEY_F(8):
case '[':
case '=':
case '+':
{
doRefresh = changePriority(lb, 1);
break;
}
case KEY_F(7):
case ']':
case '-':
{
doRefresh = changePriority(lb, -1);
break;
}
case KEY_F(3):
case '/':
FunctionBar_draw(searchBar, incSearchBuffer);
incSearchMode = true;
break;
case 't':
case KEY_F(5):
refreshTimeout = 0;
pl->treeView = !pl->treeView;
settings->changed = true;
break;
case 'H':
refreshTimeout = 0;
pl->hideThreads = !pl->hideThreads;
settings->changed = true;
break;
case 'K':
refreshTimeout = 0;
pl->hideKernelThreads = !pl->hideKernelThreads;
settings->changed = true;
break;
default:
doRefresh = false;
refreshTimeout = resetRefreshTimeout;
ListBox_onKey(lb, ch);
break;
}
follow = false;
}
attron(CRT_colors[RESET_COLOR]);
mvhline(LINES-1, 0, ' ', COLS);
attroff(CRT_colors[RESET_COLOR]);
refresh();
CRT_done();
if (settings->changed)
Settings_write(settings);
Header_delete(header);
ProcessList_delete(pl);
FunctionBar_delete((Object*)searchBar);
FunctionBar_delete((Object*)defaultBar);
((Object*)lb)->delete((Object*)lb);
if (lbk)
((Object*)lbk)->delete((Object*)lbk);
UsersTable_delete(ut);
Settings_delete(settings);
debug_done();
return 0;
}

12
htop.desktop Normal file
View File

@ -0,0 +1,12 @@
[Desktop Entry]
Encoding=UTF-8
Version=0.6
Name=Htop
Type=Application
Comment=Show System Processes
Terminal=true
Exec=htop
Path=
Icon=htop
Categories=ConsoleOnly;System;
GenericName=Process Viewer

53
htop.h Normal file
View File

@ -0,0 +1,53 @@
/* Do not edit this file. It was automatically genarated. */
#ifndef HEADER_htop
#define HEADER_htop
/*
htop - htop.h
(C) 2004-2006 Hisham H. Muhammad
Released under the GNU GPL, see the COPYING file
in the source distribution for its full text.
*/
#include "ProcessList.h"
#include "CRT.h"
#include "ListBox.h"
#include "UsersTable.h"
#include "SignalItem.h"
#include "RichString.h"
#include "Settings.h"
#include "ScreenManager.h"
#include "FunctionBar.h"
#include "ListItem.h"
#include "CategoriesListBox.h"
#include "SignalsListBox.h"
#include "config.h"
#include "debug.h"
#include <unistd.h>
#include <math.h>
#include <sys/param.h>
#include <ctype.h>
#include <stdbool.h>
int usleep(int usec);
//#link m
#define INCSEARCH_MAX 40
void printVersionFlag();
void printHelpFlag();
void showHelp();
void showColumnConfig(ProcessList* pl);
void Setup_run(Settings* settings, int headerHeight);
int main(int argc, char** argv);
#endif

BIN
htop.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 169 B