2021-02-18 22:25:36 +01:00
#include "fastfetch.h"
2021-04-15 18:59:26 +02:00
#define FF_MEMORY_MODULE_NAME "Memory"
#define FF_MEMORY_NUM_FORMAT_ARGS 3
2021-04-09 14:07:05 +02:00
// Impl inspired by: https://github.com/sam-barr/paleofetch/blob/b7c58a52c0de39b53c9b5f417889a5886d324bfa/paleofetch.c#L544
2021-02-27 18:30:05 +01:00
void ffPrintMemory ( FFinstance * instance )
2021-02-18 22:25:36 +01:00
{
2021-02-19 10:07:00 +01:00
FILE * meminfo = fopen ( "/proc/meminfo" , "r" );
2021-02-18 22:25:36 +01:00
if ( meminfo == NULL ) {
2021-04-15 18:59:26 +02:00
ffPrintError ( instance , FF_MEMORY_MODULE_NAME , 0 , & instance -> config . memoryKey , & instance -> config . memoryFormat , FF_MEMORY_NUM_FORMAT_ARGS , "fopen( \" /proc/meminfo \" , \" r \" ) == NULL" );
2021-02-18 22:25:36 +01:00
return ;
}
2021-02-19 10:07:00 +01:00
char * line = NULL ;
2021-04-03 21:51:50 +02:00
size_t len = 0 ;
2021-02-18 22:25:36 +01:00
uint32_t total , shared , memfree , buffers , cached , reclaimable ;
while ( getline ( & line , & len , meminfo ) != - 1 ) {
2021-02-19 10:07:00 +01:00
sscanf ( line , "MemTotal: %u" , & total );
sscanf ( line , "Shmem: %u" , & shared );
sscanf ( line , "MemFree: %u" , & memfree );
sscanf ( line , "Buffers: %u" , & buffers );
sscanf ( line , "Cached: %u" , & cached );
sscanf ( line , "SReclaimable: %u" , & reclaimable );
2021-02-18 22:25:36 +01:00
}
2021-04-03 21:51:50 +02:00
if ( line != NULL )
free ( line );
2021-02-18 22:25:36 +01:00
fclose ( meminfo );
uint32_t used_mem = ( total + shared - memfree - buffers - cached - reclaimable ) / 1024 ;
uint32_t total_mem = total / 1024 ;
uint8_t percentage = ( uint8_t ) (( used_mem / ( double ) total_mem ) * 100 );
2021-04-15 18:59:26 +02:00
if ( used_mem == 0 && total_mem == 0 && percentage == 0 )
{
ffPrintError ( instance , FF_MEMORY_MODULE_NAME , 0 , & instance -> config . memoryKey , & instance -> config . memoryFormat , FF_MEMORY_NUM_FORMAT_ARGS , "/proc/meminfo could't be parsed" );
return ;
}
2021-03-23 19:48:52 +01:00
if ( instance -> config . memoryFormat . length == 0 )
2021-03-19 20:57:07 +01:00
{
2021-04-15 18:59:26 +02:00
ffPrintLogoAndKey ( instance , FF_MEMORY_MODULE_NAME , 0 , & instance -> config . memoryKey );
2021-03-19 20:57:07 +01:00
printf ( "%uMiB / %uMiB (%u%%) \n " , used_mem , total_mem , percentage );
}
else
{
2021-04-15 18:59:26 +02:00
ffPrintFormatString ( instance , FF_MEMORY_MODULE_NAME , 0 , & instance -> config . memoryKey , & instance -> config . memoryFormat , NULL , FF_MEMORY_NUM_FORMAT_ARGS , ( FFformatarg []){
{ FF_FORMAT_ARG_TYPE_UINT , & used_mem },
{ FF_FORMAT_ARG_TYPE_UINT , & total_mem },
{ FF_FORMAT_ARG_TYPE_UINT8 , & percentage }
});
2021-03-19 20:57:07 +01:00
}
2021-03-27 18:14:19 +01:00
}