Meter.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. /*
  2. htop - Meter.c
  3. (C) 2004-2011 Hisham H. Muhammad
  4. Released under the GNU GPLv2+, see the COPYING file
  5. in the source distribution for its full text.
  6. */
  7. #include "config.h" // IWYU pragma: keep
  8. #include "Meter.h"
  9. #include <assert.h>
  10. #include <math.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include "CRT.h"
  14. #include "Macros.h"
  15. #include "Object.h"
  16. #include "ProvideCurses.h"
  17. #include "RichString.h"
  18. #include "Row.h"
  19. #include "Settings.h"
  20. #include "XUtils.h"
  21. #ifndef UINT32_WIDTH
  22. #define UINT32_WIDTH 32
  23. #endif
  24. #define GRAPH_HEIGHT 4 /* Unit: rows (lines) */
  25. typedef struct MeterMode_ {
  26. Meter_Draw draw;
  27. const char* uiName;
  28. int h;
  29. } MeterMode;
  30. /* Meter drawing modes */
  31. static inline void Meter_displayBuffer(const Meter* this, RichString* out) {
  32. if (Object_displayFn(this)) {
  33. Object_display(this, out);
  34. } else {
  35. RichString_writeWide(out, CRT_colors[Meter_attributes(this)[0]], this->txtBuffer);
  36. }
  37. }
  38. /* ---------- TextMeterMode ---------- */
  39. static void TextMeterMode_draw(Meter* this, int x, int y, int w) {
  40. const char* caption = Meter_getCaption(this);
  41. attrset(CRT_colors[METER_TEXT]);
  42. mvaddnstr(y, x, caption, w);
  43. attrset(CRT_colors[RESET_COLOR]);
  44. int captionLen = strlen(caption);
  45. x += captionLen;
  46. w -= captionLen;
  47. if (w <= 0)
  48. return;
  49. RichString_begin(out);
  50. Meter_displayBuffer(this, &out);
  51. RichString_printoffnVal(out, y, x, 0, w);
  52. RichString_delete(&out);
  53. }
  54. /* ---------- BarMeterMode ---------- */
  55. static const char BarMeterMode_characters[] = "|#*@$%&.";
  56. static void BarMeterMode_draw(Meter* this, int x, int y, int w) {
  57. // Draw the caption
  58. const char* caption = Meter_getCaption(this);
  59. attrset(CRT_colors[METER_TEXT]);
  60. int captionLen = 3;
  61. mvaddnstr(y, x, caption, captionLen);
  62. x += captionLen;
  63. w -= captionLen;
  64. // Draw the bar borders
  65. attrset(CRT_colors[BAR_BORDER]);
  66. mvaddch(y, x, '[');
  67. w--;
  68. mvaddch(y, x + MAXIMUM(w, 0), ']');
  69. w--;
  70. attrset(CRT_colors[RESET_COLOR]);
  71. x++;
  72. if (w < 1) {
  73. return;
  74. }
  75. // The text in the bar is right aligned;
  76. // Pad with maximal spaces and then calculate needed starting position offset
  77. RichString_begin(bar);
  78. RichString_appendChr(&bar, 0, ' ', w);
  79. RichString_appendWide(&bar, 0, this->txtBuffer);
  80. int startPos = RichString_sizeVal(bar) - w;
  81. if (startPos > w) {
  82. // Text is too large for bar
  83. // Truncate meter text at a space character
  84. for (int pos = 2 * w; pos > w; pos--) {
  85. if (RichString_getCharVal(bar, pos) == ' ') {
  86. while (pos > w && RichString_getCharVal(bar, pos - 1) == ' ')
  87. pos--;
  88. startPos = pos - w;
  89. break;
  90. }
  91. }
  92. // If still too large, print the start not the end
  93. startPos = MINIMUM(startPos, w);
  94. }
  95. assert(startPos >= 0);
  96. assert(startPos <= w);
  97. assert(startPos + w <= RichString_sizeVal(bar));
  98. int blockSizes[10];
  99. // First draw in the bar[] buffer...
  100. int offset = 0;
  101. for (uint8_t i = 0; i < this->curItems; i++) {
  102. double value = this->values[i];
  103. if (isPositive(value) && this->total > 0.0) {
  104. value = MINIMUM(value, this->total);
  105. blockSizes[i] = ceil((value / this->total) * w);
  106. } else {
  107. blockSizes[i] = 0;
  108. }
  109. int nextOffset = offset + blockSizes[i];
  110. // (Control against invalid values)
  111. nextOffset = CLAMP(nextOffset, 0, w);
  112. for (int j = offset; j < nextOffset; j++)
  113. if (RichString_getCharVal(bar, startPos + j) == ' ') {
  114. if (CRT_colorScheme == COLORSCHEME_MONOCHROME) {
  115. assert(i < strlen(BarMeterMode_characters));
  116. RichString_setChar(&bar, startPos + j, BarMeterMode_characters[i]);
  117. } else {
  118. RichString_setChar(&bar, startPos + j, '|');
  119. }
  120. }
  121. offset = nextOffset;
  122. }
  123. // ...then print the buffer.
  124. offset = 0;
  125. for (uint8_t i = 0; i < this->curItems; i++) {
  126. int attr = this->curAttributes ? this->curAttributes[i] : Meter_attributes(this)[i];
  127. RichString_setAttrn(&bar, CRT_colors[attr], startPos + offset, blockSizes[i]);
  128. RichString_printoffnVal(bar, y, x + offset, startPos + offset, MINIMUM(blockSizes[i], w - offset));
  129. offset += blockSizes[i];
  130. offset = CLAMP(offset, 0, w);
  131. }
  132. if (offset < w) {
  133. RichString_setAttrn(&bar, CRT_colors[BAR_SHADOW], startPos + offset, w - offset);
  134. RichString_printoffnVal(bar, y, x + offset, startPos + offset, w - offset);
  135. }
  136. RichString_delete(&bar);
  137. move(y, x + w + 1);
  138. attrset(CRT_colors[RESET_COLOR]);
  139. }
  140. /* ---------- GraphMeterMode ---------- */
  141. #ifdef HAVE_LIBNCURSESW
  142. #define PIXPERROW_UTF8 4
  143. static const char* const GraphMeterMode_dotsUtf8[] = {
  144. /*00*/" ", /*01*/"⢀", /*02*/"⢠", /*03*/"⢰", /*04*/ "⢸",
  145. /*10*/"⡀", /*11*/"⣀", /*12*/"⣠", /*13*/"⣰", /*14*/ "⣸",
  146. /*20*/"⡄", /*21*/"⣄", /*22*/"⣤", /*23*/"⣴", /*24*/ "⣼",
  147. /*30*/"⡆", /*31*/"⣆", /*32*/"⣦", /*33*/"⣶", /*34*/ "⣾",
  148. /*40*/"⡇", /*41*/"⣇", /*42*/"⣧", /*43*/"⣷", /*44*/ "⣿"
  149. };
  150. #endif
  151. #define PIXPERROW_ASCII 2
  152. static const char* const GraphMeterMode_dotsAscii[] = {
  153. /*00*/" ", /*01*/".", /*02*/":",
  154. /*10*/".", /*11*/".", /*12*/":",
  155. /*20*/":", /*21*/":", /*22*/":"
  156. };
  157. static void GraphMeterMode_draw(Meter* this, int x, int y, int w) {
  158. // Draw the caption
  159. const char* caption = Meter_getCaption(this);
  160. attrset(CRT_colors[METER_TEXT]);
  161. const int captionLen = 3;
  162. mvaddnstr(y, x, caption, captionLen);
  163. x += captionLen;
  164. w -= captionLen;
  165. GraphData* data = &this->drawData;
  166. // Expand the graph data buffer if necessary
  167. assert(data->nValues / 2 <= INT_MAX);
  168. if (w > (int)(data->nValues / 2) && MAX_METER_GRAPHDATA_VALUES > data->nValues) {
  169. size_t oldNValues = data->nValues;
  170. data->nValues = MAXIMUM(oldNValues + oldNValues / 2, (size_t)w * 2);
  171. data->nValues = MINIMUM(data->nValues, MAX_METER_GRAPHDATA_VALUES);
  172. data->values = xReallocArray(data->values, data->nValues, sizeof(*data->values));
  173. memmove(data->values + (data->nValues - oldNValues), data->values, oldNValues * sizeof(*data->values));
  174. memset(data->values, 0, (data->nValues - oldNValues) * sizeof(*data->values));
  175. }
  176. const size_t nValues = data->nValues;
  177. if (nValues < 1)
  178. return;
  179. // Record new value if necessary
  180. const Machine* host = this->host;
  181. if (!timercmp(&host->realtime, &(data->time), <)) {
  182. int globalDelay = host->settings->delay;
  183. struct timeval delay = { .tv_sec = globalDelay / 10, .tv_usec = (globalDelay % 10) * 100000L };
  184. timeradd(&host->realtime, &delay, &(data->time));
  185. memmove(&data->values[0], &data->values[1], (nValues - 1) * sizeof(*data->values));
  186. data->values[nValues - 1] = 0.0;
  187. if (this->curItems > 0) {
  188. assert(this->values);
  189. data->values[nValues - 1] = sumPositiveValues(this->values, this->curItems);
  190. }
  191. }
  192. if (w <= 0)
  193. return;
  194. // Graph drawing style (character set, etc.)
  195. const char* const* GraphMeterMode_dots;
  196. int GraphMeterMode_pixPerRow;
  197. #ifdef HAVE_LIBNCURSESW
  198. if (CRT_utf8) {
  199. GraphMeterMode_dots = GraphMeterMode_dotsUtf8;
  200. GraphMeterMode_pixPerRow = PIXPERROW_UTF8;
  201. } else
  202. #endif
  203. {
  204. GraphMeterMode_dots = GraphMeterMode_dotsAscii;
  205. GraphMeterMode_pixPerRow = PIXPERROW_ASCII;
  206. }
  207. // Starting positions of graph data and terminal column
  208. if ((size_t)w > nValues / 2) {
  209. x += w - nValues / 2;
  210. w = nValues / 2;
  211. }
  212. size_t i = nValues - (size_t)w * 2;
  213. // Draw the actual graph
  214. for (int col = 0; i < nValues - 1; i += 2, col++) {
  215. int pix = GraphMeterMode_pixPerRow * GRAPH_HEIGHT;
  216. double total = MAXIMUM(this->total, 1);
  217. int v1 = (int) lround(CLAMP(data->values[i] / total * pix, 1.0, pix));
  218. int v2 = (int) lround(CLAMP(data->values[i + 1] / total * pix, 1.0, pix));
  219. int colorIdx = GRAPH_1;
  220. for (int line = 0; line < GRAPH_HEIGHT; line++) {
  221. int line1 = CLAMP(v1 - (GraphMeterMode_pixPerRow * (GRAPH_HEIGHT - 1 - line)), 0, GraphMeterMode_pixPerRow);
  222. int line2 = CLAMP(v2 - (GraphMeterMode_pixPerRow * (GRAPH_HEIGHT - 1 - line)), 0, GraphMeterMode_pixPerRow);
  223. attrset(CRT_colors[colorIdx]);
  224. mvaddstr(y + line, x + col, GraphMeterMode_dots[line1 * (GraphMeterMode_pixPerRow + 1) + line2]);
  225. colorIdx = GRAPH_2;
  226. }
  227. }
  228. attrset(CRT_colors[RESET_COLOR]);
  229. }
  230. /* ---------- LEDMeterMode ---------- */
  231. static const char* const LEDMeterMode_digitsAscii[] = {
  232. " __ ", " ", " __ ", " __ ", " ", " __ ", " __ ", " __ ", " __ ", " __ ",
  233. "| |", " |", " __|", " __|", "|__|", "|__ ", "|__ ", " |", "|__|", "|__|",
  234. "|__|", " |", "|__ ", " __|", " |", " __|", "|__|", " |", "|__|", " __|"
  235. };
  236. #ifdef HAVE_LIBNCURSESW
  237. static const char* const LEDMeterMode_digitsUtf8[] = {
  238. "┌──┐", " ┐ ", "╶──┐", "╶──┐", "╷ ╷", "┌──╴", "┌──╴", "╶──┐", "┌──┐", "┌──┐",
  239. "│ │", " │ ", "┌──┘", " ──┤", "└──┤", "└──┐", "├──┐", " │", "├──┤", "└──┤",
  240. "└──┘", " ╵ ", "└──╴", "╶──┘", " ╵", "╶──┘", "└──┘", " ╵", "└──┘", "╶──┘"
  241. };
  242. #endif
  243. static const char* const* LEDMeterMode_digits;
  244. static void LEDMeterMode_drawDigit(int x, int y, int n) {
  245. for (int i = 0; i < 3; i++)
  246. mvaddstr(y + i, x, LEDMeterMode_digits[i * 10 + n]);
  247. }
  248. static void LEDMeterMode_draw(Meter* this, int x, int y, int w) {
  249. #ifdef HAVE_LIBNCURSESW
  250. if (CRT_utf8)
  251. LEDMeterMode_digits = LEDMeterMode_digitsUtf8;
  252. else
  253. #endif
  254. LEDMeterMode_digits = LEDMeterMode_digitsAscii;
  255. RichString_begin(out);
  256. Meter_displayBuffer(this, &out);
  257. int yText =
  258. #ifdef HAVE_LIBNCURSESW
  259. CRT_utf8 ? y + 1 :
  260. #endif
  261. y + 2;
  262. attrset(CRT_colors[LED_COLOR]);
  263. const char* caption = Meter_getCaption(this);
  264. mvaddstr(yText, x, caption);
  265. int xx = x + strlen(caption);
  266. int len = RichString_sizeVal(out);
  267. for (int i = 0; i < len; i++) {
  268. int c = RichString_getCharVal(out, i);
  269. if (c >= '0' && c <= '9') {
  270. if (xx - x + 4 > w)
  271. break;
  272. LEDMeterMode_drawDigit(xx, y, c - '0');
  273. xx += 4;
  274. } else {
  275. if (xx - x + 1 > w)
  276. break;
  277. #ifdef HAVE_LIBNCURSESW
  278. const cchar_t wc = { .chars = { c, '\0' }, .attr = 0 }; /* use LED_COLOR from attrset() */
  279. mvadd_wch(yText, xx, &wc);
  280. #else
  281. mvaddch(yText, xx, c);
  282. #endif
  283. xx += 1;
  284. }
  285. }
  286. attrset(CRT_colors[RESET_COLOR]);
  287. RichString_delete(&out);
  288. }
  289. static const MeterMode Meter_modes[] = {
  290. [0] = {
  291. .uiName = NULL,
  292. .h = 0,
  293. .draw = NULL,
  294. },
  295. [BAR_METERMODE] = {
  296. .uiName = "Bar",
  297. .h = 1,
  298. .draw = BarMeterMode_draw,
  299. },
  300. [TEXT_METERMODE] = {
  301. .uiName = "Text",
  302. .h = 1,
  303. .draw = TextMeterMode_draw,
  304. },
  305. [GRAPH_METERMODE] = {
  306. .uiName = "Graph",
  307. .h = GRAPH_HEIGHT,
  308. .draw = GraphMeterMode_draw,
  309. },
  310. [LED_METERMODE] = {
  311. .uiName = "LED",
  312. .h = 3,
  313. .draw = LEDMeterMode_draw,
  314. },
  315. };
  316. /* Meter class and methods */
  317. const MeterClass Meter_class = {
  318. .super = {
  319. .extends = Class(Object)
  320. }
  321. };
  322. Meter* Meter_new(const Machine* host, unsigned int param, const MeterClass* type) {
  323. Meter* this = xCalloc(1, sizeof(Meter));
  324. Object_setClass(this, type);
  325. this->h = 1;
  326. this->param = param;
  327. this->host = host;
  328. this->curItems = type->maxItems;
  329. this->curAttributes = NULL;
  330. this->values = type->maxItems ? xCalloc(type->maxItems, sizeof(double)) : NULL;
  331. this->total = type->total;
  332. this->caption = xStrdup(type->caption);
  333. if (Meter_initFn(this)) {
  334. Meter_init(this);
  335. }
  336. Meter_setMode(this, type->defaultMode);
  337. assert(this->mode > 0);
  338. return this;
  339. }
  340. /* Converts 'value' in kibibytes into a human readable string.
  341. Example output strings: "0K", "1023K", "98.7M" and "1.23G" */
  342. int Meter_humanUnit(char* buffer, double value, size_t size) {
  343. size_t i = 0;
  344. assert(value >= 0.0);
  345. while (value >= ONE_K) {
  346. if (i >= ARRAYSIZE(unitPrefixes) - 1) {
  347. if (value > 9999.0) {
  348. return xSnprintf(buffer, size, "inf");
  349. }
  350. break;
  351. }
  352. value /= ONE_K;
  353. ++i;
  354. }
  355. int precision = 0;
  356. if (i > 0) {
  357. // Fraction digits for mebibytes and above
  358. precision = value <= 99.9 ? (value <= 9.99 ? 2 : 1) : 0;
  359. // Round up if 'value' is in range (99.9, 100) or (9.99, 10)
  360. if (precision < 2) {
  361. double limit = precision == 1 ? 10.0 : 100.0;
  362. if (value < limit) {
  363. value = limit;
  364. }
  365. }
  366. }
  367. return xSnprintf(buffer, size, "%.*f%c", precision, value, unitPrefixes[i]);
  368. }
  369. void Meter_delete(Object* cast) {
  370. if (!cast)
  371. return;
  372. Meter* this = (Meter*) cast;
  373. if (Meter_doneFn(this)) {
  374. Meter_done(this);
  375. }
  376. free(this->drawData.values);
  377. free(this->caption);
  378. free(this->values);
  379. free(this);
  380. }
  381. void Meter_setCaption(Meter* this, const char* caption) {
  382. free_and_xStrdup(&this->caption, caption);
  383. }
  384. void Meter_setMode(Meter* this, MeterModeId modeIndex) {
  385. if (modeIndex == this->mode) {
  386. assert(this->mode > 0);
  387. return;
  388. }
  389. uint32_t supportedModes = Meter_supportedModes(this);
  390. assert(supportedModes);
  391. assert(!(supportedModes & (1 << 0)));
  392. assert(LAST_METERMODE <= UINT32_WIDTH);
  393. if (modeIndex >= LAST_METERMODE || !(supportedModes & (1UL << modeIndex)))
  394. return;
  395. assert(modeIndex >= 1);
  396. if (Meter_updateModeFn(this)) {
  397. assert(Meter_drawFn(this));
  398. this->draw = Meter_drawFn(this);
  399. Meter_updateMode(this, modeIndex);
  400. } else {
  401. free(this->drawData.values);
  402. this->drawData.values = NULL;
  403. this->drawData.nValues = 0;
  404. const MeterMode* mode = &Meter_modes[modeIndex];
  405. this->draw = mode->draw;
  406. this->h = mode->h;
  407. }
  408. this->mode = modeIndex;
  409. }
  410. MeterModeId Meter_nextSupportedMode(const Meter* this) {
  411. uint32_t supportedModes = Meter_supportedModes(this);
  412. assert(supportedModes);
  413. assert(this->mode < UINT32_WIDTH);
  414. uint32_t modeMask = ((uint32_t)-1 << 1) << this->mode;
  415. uint32_t nextModes = supportedModes & modeMask;
  416. if (!nextModes) {
  417. nextModes = supportedModes;
  418. }
  419. return (MeterModeId)countTrailingZeros(nextModes);
  420. }
  421. ListItem* Meter_toListItem(const Meter* this, bool moving) {
  422. char mode[20];
  423. if (this->mode > 0) {
  424. xSnprintf(mode, sizeof(mode), " [%s]", Meter_modes[this->mode].uiName);
  425. } else {
  426. mode[0] = '\0';
  427. }
  428. char name[32];
  429. if (Meter_getUiNameFn(this))
  430. Meter_getUiName(this, name, sizeof(name));
  431. else
  432. xSnprintf(name, sizeof(name), "%s", Meter_uiName(this));
  433. char buffer[50];
  434. xSnprintf(buffer, sizeof(buffer), "%s%s", name, mode);
  435. ListItem* li = ListItem_new(buffer, 0);
  436. li->moving = moving;
  437. return li;
  438. }
  439. /* Blank meter */
  440. static void BlankMeter_updateValues(Meter* this) {
  441. this->txtBuffer[0] = '\0';
  442. }
  443. static void BlankMeter_display(ATTR_UNUSED const Object* cast, ATTR_UNUSED RichString* out) {
  444. }
  445. static const int BlankMeter_attributes[] = {
  446. DEFAULT_COLOR
  447. };
  448. const MeterClass BlankMeter_class = {
  449. .super = {
  450. .extends = Class(Meter),
  451. .delete = Meter_delete,
  452. .display = BlankMeter_display,
  453. },
  454. .updateValues = BlankMeter_updateValues,
  455. .defaultMode = TEXT_METERMODE,
  456. .supportedModes = (1 << TEXT_METERMODE),
  457. .maxItems = 0,
  458. .total = 0.0,
  459. .attributes = BlankMeter_attributes,
  460. .name = "Blank",
  461. .uiName = "Blank",
  462. .caption = ""
  463. };