Commit d6231bab authored by Hisham Muhammad's avatar Hisham Muhammad
Browse files

Initial import.

parents
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
/*
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);
}
/* 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
/*
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);
}
/* 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
#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;
}
/* 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
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.
/*
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);
}
/* 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
/*
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 "- ";
}
}
/* 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
/*
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.
}
/* 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
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.
#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;
}
/* 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
/*
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;
}
/* 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
/*
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;
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment