Build improvements: clang-tidy, sonar, Dockerfile. (#488)

This commit is contained in:
Brenden Matthews 2018-05-12 19:26:31 -04:00 committed by GitHub
parent eebc8c653b
commit 4b92556fca
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
98 changed files with 3684 additions and 3005 deletions

View File

@ -1,107 +0,0 @@
---
Language: Cpp
# BasedOnStyle: Google
AccessModifierOffset: -1
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlines: Left
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: true
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Attach
BreakBeforeInheritanceComma: false
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: true
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IncludeCategories:
- Regex: '^<.*\.h>'
Priority: 1
- Regex: '^<.*'
Priority: 2
- Regex: '.*'
Priority: 3
IncludeIsMainRegex: '([-_](test|unittest))?$'
IndentCaseLabels: true
IndentWidth: 2
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBlockIndentWidth: 2
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: false
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 200
PointerAlignment: Left
ReflowComments: true
SortIncludes: true
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Auto
TabWidth: 2
UseTab: Never
...

1
.dockerignore Normal file
View File

@ -0,0 +1 @@
build

1
.gitignore vendored
View File

@ -11,7 +11,6 @@ doc/*.html
Makefile
CMakeCache.txt
CMakeFiles
*.cmake
data/convertconf.h
data/defconfig.h
lua/libcairo-orig.c

View File

@ -7,9 +7,9 @@ matrix:
apt:
sources:
- ubuntu-toolchain-r-test
- llvm-toolchain-trusty-5.0
- llvm-toolchain-trusty-6.0
packages:
- g++-7
- g++-8
- cmake
- libxdamage-dev
- libx11-dev
@ -24,16 +24,19 @@ matrix:
- libimlib2-dev
- libxinerama-dev
- gawk
- clang-5.0
- clang-format-5.0
- clang-6.0
sonarcloud:
organization: "brndnmtthws-github"
token:
secure: "KikPusy+HXcEVLr0Dqb6mkrefDU5jm7EGQ5fwO4sBG7bRMcnHV3V14s5yB4Ol8btpUC0nkNn/41+f37lkG+oT4y9ZeIH2ZrhsSEHxOgH6DF9ZSVJwtpLrF9siWgfZ0m5c5V7U5rzVYL3jlO1hQfXKCfMNAcwlKcEUrfpk7jVEZc="
env:
- MATRIX_EVAL="CC=gcc-7 && CXX=g++-7"
- MATRIX_EVAL="CC=gcc-8 && CXX=g++-8"
- os: linux
addons:
apt:
sources:
- ubuntu-toolchain-r-test
- llvm-toolchain-trusty-5.0
- llvm-toolchain-trusty-6.0
packages:
- cmake
- libxdamage-dev
@ -49,28 +52,35 @@ matrix:
- libimlib2-dev
- libxinerama-dev
- gawk
- clang-5.0
- clang-format-5.0
- clang-6.0
sonarcloud:
organization: "brndnmtthws-github"
token:
secure: "KikPusy+HXcEVLr0Dqb6mkrefDU5jm7EGQ5fwO4sBG7bRMcnHV3V14s5yB4Ol8btpUC0nkNn/41+f37lkG+oT4y9ZeIH2ZrhsSEHxOgH6DF9ZSVJwtpLrF9siWgfZ0m5c5V7U5rzVYL3jlO1hQfXKCfMNAcwlKcEUrfpk7jVEZc="
env:
- MATRIX_EVAL="CC=clang && CXX=clang++"
- MATRIX_EVAL="CC=clang-6.0 && CXX=clang++-6.0"
before_install:
- eval "${MATRIX_EVAL}"
before_script:
- mkdir build
- cd build
- scan-build --use-cc=$CC --use-c++=$CXX -o scanbuildout cmake -DCHECK_CODE_FORMAT=ON ..
- travis_wait 30 make format-check
- cmake -DCHECK_CODE_QUALITY=ON ..
- cd ..
- mkdir build-no-x11
- cd build-no-x11
- scan-build --use-cc=$CC --use-c++=$CXX -o scanbuildout cmake -DCHECK_CODE_FORMAT=ON -DBUILD_X11=OFF ..
- cmake -DBUILD_X11=OFF ..
- cd ..
script:
- cd build
- scan-build --use-cc=$CC --use-c++=$CXX -o scanbuildout make -j4
- build-wrapper-linux-x86-64 --out-dir bw-output make -j4
- cd ../build-no-x11
- scan-build --use-cc=$CC --use-c++=$CXX -o scanbuildout make -j4
- make -j4
- cd ..
- sonar-scanner
branches:
only:
- master
sudo: false
cache:
directories:
- '$HOME/.sonar/cache'

View File

@ -19,7 +19,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
cmake_minimum_required(VERSION 3.5)
cmake_minimum_required(VERSION 3.6)
project(conky)
@ -38,13 +38,6 @@ include(ConkyPlatformChecks)
# CPack module for installation tasks
include(ConkyCPackSetup)
if(CHECK_CODE_FORMAT)
# Set up clang-format
set(CLANG_FORMAT_BIN_NAME clang-format clang-format-5.0)
set(CLANG_FORMAT_EXCLUDE_PATTERNS "build/" ${CMAKE_BINARY_DIR})
find_package(ClangFormat)
endif(CHECK_CODE_FORMAT)
# setup our configuration headers
configure_file(${CMAKE_MODULE_PATH}/config.h.in ${CMAKE_BINARY_DIR}/config.h)
configure_file(${CMAKE_MODULE_PATH}/build.h.in ${CMAKE_BINARY_DIR}/build.h)
@ -81,3 +74,15 @@ if(MAINTAINER_MODE)
install(FILES ${MAN_FILES}
DESTINATION ${MAN_PATH})
endif(MAINTAINER_MODE)
if(CHECK_CODE_QUALITY)
# Set up clang-tidy
set(CLANG_TIDY_BIN_NAME
clang-tidy
clang-tidy-5.0
clang-tidy-6.0
clang-tidy-7.0
)
set(CLANG_TIDY_EXCLUDE_PATTERNS "build/" ${CMAKE_BINARY_DIR})
find_package(ClangTidy)
endif(CHECK_CODE_QUALITY)

View File

@ -1,10 +1,36 @@
FROM debian:latest
RUN apt-get update && apt-get install -y cmake git g++ libimlib2-dev liblua5.3-dev libxext-dev libxft-dev libxdamage-dev libxinerama-dev ncurses-dev
COPY . /root/
RUN mkdir /root/build
WORKDIR /root/build
FROM ubuntu:latest
RUN apt-get update \
&& apt-get install -y \
cmake \
git \
g++ \
libimlib2-dev \
liblua5.3-dev \
libxext-dev \
libxft-dev \
libxdamage-dev \
libxinerama-dev \
ncurses-dev
COPY . /conky
WORKDIR /conky/build
ARG X11=yes
RUN sh -c 'if [ "$X11" = "yes" ] ; then cmake ../ ; else cmake -DBUILD_X11=OFF ../ ; fi'
RUN make all
RUN make install
RUN sh -c 'if [ "$X11" = "yes" ] ; then cmake ../ ; else cmake -DBUILD_X11=OFF ../ ; fi' \
&& make -j5 all \
&& make -j5 install \
&& apt-get remove -y \
cmake \
git \
g++ \
libimlib2-dev \
liblua5.3-dev \
libxext-dev \
libxft-dev \
libxdamage-dev \
libxinerama-dev \
ncurses-dev \
&& rm -rf /var/lib/apt/lists/* \
&& rm -rf /conky \
CMD conky

View File

@ -1,6 +1,6 @@
## Conky
[![Build Status](https://travis-ci.org/brndnmtthws/conky.png)](https://travis-ci.org/brndnmtthws/conky)
[![Build Status](https://travis-ci.org/brndnmtthws/conky.png)](https://travis-ci.org/brndnmtthws/conky) [![Quality Gate](https://sonarcloud.io/api/project_badges/measure?project=conky&metric=alert_status)](https://sonarcloud.io/dashboard/index/conky)
**Conky** is a free, light-weight system monitor for X, that displays
any kind of information on your desktop.

View File

@ -33,7 +33,9 @@ endif(NOT CMAKE_BUILD_TYPE)
# -std options for all build types
set(CMAKE_C_FLAGS "-std=c99 ${CMAKE_C_FLAGS}" CACHE STRING "Flags used by the C compiler during all build types." FORCE)
set(CMAKE_CXX_FLAGS "-std=c++0x ${CMAKE_CXX_FLAGS}" CACHE STRING "Flags used by the C++ compiler during all build types." FORCE)
set(CMAKE_CXX_FLAGS "-std=c++17 ${CMAKE_CXX_FLAGS}" CACHE STRING "Flags used by the C++ compiler during all build types." FORCE)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if(MAINTAINER_MODE)
# some extra debug flags when in 'maintainer mode'
@ -41,7 +43,6 @@ if(MAINTAINER_MODE)
set(CMAKE_CXX_FLAGS_DEBUG "-ggdb -Wall -W -Wextra -Wunused -pedantic -Werror -Wno-format ${CMAKE_CXX_FLAGS_DEBUG}" CACHE STRING "Flags used by the compiler during debug builds." FORCE)
endif(MAINTAINER_MODE)
option(RELEASE "Build release package" false)
mark_as_advanced(RELEASE)
@ -179,4 +180,4 @@ option(BUILD_JOURNAL "Enable support for reading from the systemd journal" false
option(BUILD_PULSEAUDIO "Enable support for Pulseaudio's default sink and source" false)
option(CHECK_CODE_FORMAT "Check code formatting with clang-format" false)
option(CHECK_CODE_QUALITY "Check code formatting/quality with clang" false)

View File

@ -1,34 +0,0 @@
# Find Clang format
#
#
if(NOT CLANG_FORMAT_BIN_NAME)
set(CLANG_FORMAT_BIN_NAME clang-format)
endif()
# if custom path check there first
if(CLANG_FORMAT_ROOT_DIR)
find_program(CLANG_FORMAT_BIN
NAMES
${CLANG_FORMAT_BIN_NAME}
PATHS
"${CLANG_FORMAT_ROOT_DIR}"
NO_DEFAULT_PATH)
endif()
find_program(CLANG_FORMAT_BIN NAMES ${CLANG_FORMAT_BIN_NAME})
include(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(
CLANG_FORMAT
DEFAULT_MSG
CLANG_FORMAT_BIN)
mark_as_advanced(
CLANG_FORMAT_BIN)
if(CLANG_FORMAT_FOUND)
# A CMake script to find all source files and setup clang-format targets for them
include(clang-format)
else()
message("clang-format not found. Not setting up format targets")
endif()

35
cmake/FindClangTidy.cmake Normal file
View File

@ -0,0 +1,35 @@
# Find Clang tidy
#
if(NOT CLANG_TIDY_BIN_NAME)
set(CLANG_TIDY_BIN_NAME clang-tidy)
endif()
# if custom path check there first
if(CLANG_TIDY_ROOT_DIR)
find_program(CLANG_TIDY_BIN
NAMES
${CLANG_TIDY_BIN_NAME}
PATHS
"${CLANG_TIDY_ROOT_DIR}"
NO_DEFAULT_PATH)
endif()
find_program(CLANG_TIDY_BIN NAMES ${CLANG_TIDY_BIN_NAME})
include(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(
CLANG_TIDY
DEFAULT_MSG
CLANG_TIDY_BIN)
mark_as_advanced(
CLANG_TIDY_BIN
)
if(CLANG_TIDY_FOUND)
# A CMake script to find all source files and setup clang-tidy targets for them
include(clang-tidy)
else()
message("clang-tidy not found. Not setting up tidy targets")
endif()

View File

@ -1,62 +0,0 @@
# A CMake script to find all source files and setup clang-format targets for them
# Find all source files
set(CLANG_FORMAT_CXX_FILE_EXTENSIONS ${CLANG_FORMAT_CXX_FILE_EXTENSIONS} *.cpp *.h *.cxx *.hxx *.hpp *.cc *.ipp)
file(GLOB_RECURSE ALL_SOURCE_FILES ${CLANG_FORMAT_CXX_FILE_EXTENSIONS})
# Don't include some common build folders
set(CLANG_FORMAT_EXCLUDE_PATTERNS ${CLANG_FORMAT_EXCLUDE_PATTERNS} "/CMakeFiles/" "cmake")
# get all project files file
foreach (SOURCE_FILE ${ALL_SOURCE_FILES})
foreach (EXCLUDE_PATTERN ${CLANG_FORMAT_EXCLUDE_PATTERNS})
string(FIND ${SOURCE_FILE} ${EXCLUDE_PATTERN} EXCLUDE_FOUND)
if (NOT ${EXCLUDE_FOUND} EQUAL -1)
list(REMOVE_ITEM ALL_SOURCE_FILES ${SOURCE_FILE})
endif ()
endforeach ()
endforeach ()
add_custom_target(format
COMMENT "Running clang-format to change files"
COMMAND ${CLANG_FORMAT_BIN}
-style=file
-i
${ALL_SOURCE_FILES}
)
add_custom_target(format-check
COMMENT "Checking clang-format changes"
# Use ! to negate the result for correct output
COMMAND !
${CLANG_FORMAT_BIN}
-style=file
-output-replacements-xml
${ALL_SOURCE_FILES}
| grep -q "replacement offset"
)
# Get the path to this file
get_filename_component(_clangcheckpath ${CMAKE_CURRENT_LIST_FILE} PATH)
# have at least one here by default
set(CHANGED_FILE_EXTENSIONS ".cpp")
foreach(EXTENSION ${CLANG_FORMAT_CXX_FILE_EXTENSIONS})
set(CHANGED_FILE_EXTENSIONS "${CHANGED_FILE_EXTENSIONS},${EXTENSION}" )
endforeach()
set(EXCLUDE_PATTERN_ARGS)
foreach(EXCLUDE_PATTERN ${CLANG_FORMAT_EXCLUDE_PATTERNS})
list(APPEND EXCLUDE_PATTERN_ARGS "--exclude=${EXCLUDE_PATTERN}")
endforeach()
# call the script to chech changed files in git
add_custom_target(format-check-changed
COMMENT "Checking changed files in git"
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
COMMAND ${_clangcheckpath}/../scripts/clang-format-check-changed.py
--file-extensions \"${CHANGED_FILE_EXTENSIONS}\"
${EXCLUDE_PATTERN_ARGS}
--clang-format-bin ${CLANG_FORMAT_BIN}
)

14
cmake/clang-tidy.cmake Normal file
View File

@ -0,0 +1,14 @@
# Run clang-tidy
set(DO_CLANG_TIDY
"${CLANG_TIDY_BIN}"
-format-style='{BasedOnStyle: google, IndentWidth: 2}'
-checks=*,-clang-analyzer-alpha.*
)
if(CLANG_TIDY_BIN)
set_target_properties(
conky PROPERTIES
CXX_CLANG_TIDY "${DO_CLANG_TIDY}"
)
endif()

4
sonar-project.properties Normal file
View File

@ -0,0 +1,4 @@
sonar.projectKey=conky
sonar.projectName=Conky
sonar.sources=src
sonar.cfamily.build-wrapper-output=build/bw-output

View File

@ -27,10 +27,10 @@
*
*/
#include "algebra.h"
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory>
#include "config.h"
#include "conky.h"
@ -46,7 +46,9 @@ int find_match_op(const char *expr) {
switch (expr[idx]) {
case '=':
case '!':
if (expr[idx + 1] != '=') return -1;
if (expr[idx + 1] != '=') {
return -1;
}
/* fall through */
case '<':
case '>':
@ -61,18 +63,27 @@ int get_match_type(const char *expr) {
int idx;
const char *str;
if ((idx = find_match_op(expr)) == -1) return -1;
if ((idx = find_match_op(expr)) == -1) {
return -1;
}
str = expr + idx;
if (*str == '=' && *(str + 1) == '=')
if (*str == '=' && *(str + 1) == '=') {
return OP_EQ;
else if (*str == '!' && *(str + 1) == '=')
}
if (*str == '!' && *(str + 1) == '=') {
return OP_NEQ;
else if (*str == '>') {
if (*(str + 1) == '=') return OP_GEQ;
}
if (*str == '>') {
if (*(str + 1) == '=') {
return OP_GEQ;
}
return OP_GT;
} else if (*str == '<') {
if (*(str + 1) == '=') return OP_LEQ;
}
if (*str == '<') {
if (*(str + 1) == '=') {
return OP_LEQ;
}
return OP_LT;
}
return -1;
@ -84,21 +95,21 @@ int get_match_type(const char *expr) {
* this is equal to the output of str(n)cmp(). Use a macro here, as
* it's type-independent.
*/
#define COMPARE(v, t) \
switch (t) { \
case OP_GT: \
return (v > 0); \
case OP_LT: \
return (v < 0); \
case OP_EQ: \
return (v == 0); \
case OP_GEQ: \
return (v >= 0); \
case OP_LEQ: \
return (v <= 0); \
case OP_NEQ: \
return (v != 0); \
} \
#define COMPARE(v, t) \
switch (t) { \
case OP_GT: \
return ((v) > 0); \
case OP_LT: \
return ((v) < 0); \
case OP_EQ: \
return ((v) == 0); \
case OP_GEQ: \
return ((v) >= 0); \
case OP_LEQ: \
return ((v) <= 0); \
case OP_NEQ: \
return ((v) != 0); \
} \
return 0
int lcompare(long a, enum match_type mtype, long b) {
@ -121,22 +132,35 @@ enum arg_type get_arg_type(const char *arg) {
p = arg;
e = arg + strlen(arg) - 1;
while (p != e && *e && *e == ' ') e--;
while (p != e && *p == ' ') p++;
if (*p == '"' && *e == '"') return ARG_STRING;
if (*p == '-') // allow negative values
p++;
while (p <= e) {
if (!isdigit(*p)) break;
while (p != e && (*e != 0) && *e == ' ') {
e--;
}
while (p != e && *p == ' ') {
p++;
}
if (p == e + 1) return ARG_LONG;
if (*p == '"' && *e == '"') {
return ARG_STRING;
}
if (*p == '-') { // allow negative values
p++;
}
while (p <= e) {
if (isdigit(*p) == 0) {
break;
}
p++;
}
if (p == e + 1) {
return ARG_LONG;
}
if (*p == '.') {
p++;
while (p <= e) {
if (!isdigit(*p)) return ARG_BAD;
if (isdigit(*p) == 0) {
return ARG_BAD;
}
p++;
}
return ARG_DOUBLE;
@ -150,9 +174,15 @@ char *arg_to_string(const char *arg) {
start = arg;
len = 0;
while (*start && *start == ' ') start++;
if (!(*(start++) == '"')) return NULL;
while (start[len] != '"') len++;
while ((*start != 0) && *start == ' ') {
start++;
}
if (!(*(start++) == '"')) {
return nullptr;
}
while (start[len] != '"') {
len++;
}
return strndup(start, len);
}
double arg_to_double(const char *arg) {
@ -181,14 +211,16 @@ int compare(const char *expr) {
idx = find_match_op(expr);
mtype = get_match_type(expr);
if (!idx || mtype == -1) {
if ((idx == 0) || mtype == -1) {
NORM_ERR("failed to parse compare string '%s'", expr);
return -2;
}
expr_dup = strdup(expr);
expr_dup[idx] = '\0';
if (expr_dup[idx + 1] == '=') expr_dup[++idx] = '\0';
if (expr_dup[idx + 1] == '=') {
expr_dup[++idx] = '\0';
}
type1 = get_arg_type(expr_dup);
type2 = get_arg_type(expr_dup + idx + 1);
@ -197,8 +229,12 @@ int compare(const char *expr) {
free(expr_dup);
return -2;
}
if (type1 == ARG_LONG && type2 == ARG_DOUBLE) type1 = ARG_DOUBLE;
if (type1 == ARG_DOUBLE && type2 == ARG_LONG) type2 = ARG_DOUBLE;
if (type1 == ARG_LONG && type2 == ARG_DOUBLE) {
type1 = ARG_DOUBLE;
}
if (type1 == ARG_DOUBLE && type2 == ARG_LONG) {
type2 = ARG_DOUBLE;
}
if (type1 != type2) {
NORM_ERR("trying to compare args '%s' and '%s' of different type", expr_dup,
(expr_dup + idx + 1));
@ -210,7 +246,7 @@ int compare(const char *expr) {
char *a, *b;
a = arg_to_string(expr_dup);
b = arg_to_string(expr_dup + idx + 1);
idx = scompare(a, (enum match_type)mtype, b);
idx = scompare(a, static_cast<enum match_type>(mtype), b);
free(a);
free(b);
free(expr_dup);
@ -220,12 +256,12 @@ int compare(const char *expr) {
lng_a = arg_to_long(expr_dup);
lng_b = arg_to_long(expr_dup + idx + 1);
free(expr_dup);
return lcompare(lng_a, (enum match_type)mtype, lng_b);
return lcompare(lng_a, static_cast<enum match_type>(mtype), lng_b);
case ARG_DOUBLE:
dbl_a = arg_to_double(expr_dup);
dbl_b = arg_to_double(expr_dup + idx + 1);
free(expr_dup);
return dcompare(dbl_a, (enum match_type)mtype, dbl_b);
return dcompare(dbl_a, static_cast<enum match_type>(mtype), dbl_b);
case ARG_BAD: /* make_gcc_happy() */;
}
/* not reached */
@ -245,7 +281,7 @@ int check_if_match(struct text_object *obj) {
val = compare(expression.get());
if (val == -2) {
NORM_ERR("compare failed for expression '%s'", expression.get());
} else if (!val) {
} else if (val == 0) {
result = 0;
}
return result;

View File

@ -26,7 +26,7 @@
#include "logging.h"
#include "text_object.h"
#include <errno.h>
#include <cerrno>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/time.h>
@ -70,9 +70,11 @@ static int net_recv_ex(int sock, void *buf, int size, struct timeval *tv) {
errno = 0;
FD_ZERO(&fds);
FD_SET(sock, &fds);
res = select(sock + 1, &fds, NULL, NULL, tv);
res = select(sock + 1, &fds, nullptr, nullptr, tv);
} while (res < 0 && errno == EINTR);
if (res < 0) return 0;
if (res < 0) {
return 0;
}
if (res == 0) {
// timeout
errno = ETIMEDOUT; // select was succesfull, errno is now 0
@ -82,9 +84,11 @@ static int net_recv_ex(int sock, void *buf, int size, struct timeval *tv) {
// socket ready, read the data
do {
errno = 0;
res = recv(sock, (char *)buf, size, 0);
res = recv(sock, static_cast<char *>(buf), size, 0);
} while (res < 0 && errno == EINTR);
if (res < 0) return 0;
if (res < 0) {
return 0;
}
if (res == 0) {
// orderly shutdown
errno = ENOTCONN;
@ -103,9 +107,11 @@ static int net_recv(int sock, void *buf, int size) {
int len;
struct timeval tv = {0, 250000};
while (todo) {
len = net_recv_ex(sock, (char *)buf + off, todo, &tv);
if (!len) return 0;
while (todo != 0) {
len = net_recv_ex(sock, static_cast<char *>(buf) + off, todo, &tv);
if (len == 0) {
return 0;
}
todo -= len;
off += len;
}
@ -118,9 +124,13 @@ static int net_recv(int sock, void *buf, int size) {
static int get_line(int sock, char line[], short linesize) {
// get the line length
short sz;
if (!net_recv(sock, &sz, sizeof(sz))) return -1;
if (net_recv(sock, &sz, sizeof(sz)) == 0) {
return -1;
}
sz = ntohs(sz);
if (!sz) return 0;
if (sz == 0) {
return 0;
}
// get the line
while (sz >= linesize) {
@ -128,7 +138,9 @@ static int get_line(int sock, char line[], short linesize) {
net_recv(sock, line, linesize);
sz -= linesize;
}
if (!net_recv(sock, line, sz)) return 0;
if (net_recv(sock, line, sz) == 0) {
return 0;
}
line[sz] = 0;
return sz;
}
@ -155,7 +167,7 @@ static int get_line(int sock, char line[], short linesize) {
static int fill_items(int sock, PAPCUPSD_S apc) {
char line[512];
int len;
while ((len = get_line(sock, line, sizeof(line)))) {
while ((len = get_line(sock, line, sizeof(line))) != 0) {
// fill the right types in
FILL("UPSNAME", APCUPSD_NAME, FALSE);
FILL("MODEL", APCUPSD_MODEL, FALSE);
@ -170,22 +182,23 @@ static int fill_items(int sock, PAPCUPSD_S apc) {
FILL("LASTXFER", APCUPSD_LASTXFER, FALSE);
}
return len == 0;
return static_cast<int>(len == 0);
}
//
// Conky update function for apcupsd data
//
int update_apcupsd(void) {
int update_apcupsd() {
int i;
APCUPSD_S apc;
int sock;
for (i = 0; i < _APCUPSD_COUNT; ++i)
for (i = 0; i < _APCUPSD_COUNT; ++i) {
memcpy(apc.items[i], "N/A", 4); // including \0
}
do {
struct addrinfo hints;
struct addrinfo hints {};
struct addrinfo *ai, *rp;
int res;
short sz = 0;
@ -204,7 +217,7 @@ int update_apcupsd(void) {
NORM_ERR("APCUPSD getaddrinfo: %s", gai_strerror(res));
break;
}
for (rp = ai; rp != NULL; rp = rp->ai_next) {
for (rp = ai; rp != nullptr; rp = rp->ai_next) {
sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sock == -1) {
continue;
@ -215,7 +228,7 @@ int update_apcupsd(void) {
close(sock);
}
freeaddrinfo(ai);
if (rp == NULL) {
if (rp == nullptr) {
// no error reporting, the daemon is probably not running
break;
}
@ -234,7 +247,9 @@ int update_apcupsd(void) {
//
// read the lines of output and put them into the info structure
//
if (!fill_items(sock, &apc)) break;
if (fill_items(sock, &apc) == 0) {
break;
}
} while (0);
@ -250,7 +265,9 @@ int update_apcupsd(void) {
int apcupsd_scan_arg(const char *arg) {
char host[64];
int port;
if (sscanf(arg, "%63s %d", host, &port) != 2) return 1;
if (sscanf(arg, "%63s %d", host, &port) != 2) {
return 1;
}
apcupsd.port = port;
strncpy(apcupsd.host, host, sizeof(apcupsd.host));

View File

@ -101,7 +101,7 @@ class audacious_cb : public conky::callback<aud_result> {
audacious_cb(uint32_t period) : Base(period, false, Tuple()) {
#ifdef NEW_AUDACIOUS_FOUND
g_type_init();
DBusGConnection *connection = dbus_g_bus_get(DBUS_BUS_SESSION, NULL);
DBusGConnection *connection = dbus_g_bus_get(DBUS_BUS_SESSION, nullptr);
if (!connection)
throw std::runtime_error("unable to establish dbus connection");
@ -128,8 +128,8 @@ class audacious_cb : public conky::callback<aud_result> {
void audacious_cb::work() {
aud_result tmp;
gchar *psong, *pfilename;
psong = NULL;
pfilename = NULL;
psong = nullptr;
pfilename = nullptr;
do {
if (!audacious_remote_is_running(session)) {

View File

@ -44,7 +44,7 @@ static char *unknown = "unknown";
void fail(GError *error, struct information *);
void update_bmpx() {
GError *error = NULL;
GError *error = nullptr;
struct information *current_info = &info;
gint current_track;
GHashTable *metadata;
@ -54,7 +54,7 @@ void update_bmpx() {
dbus_g_type_specialized_init();
bus = dbus_g_bus_get(DBUS_BUS_SESSION, &error);
if (bus == NULL) {
if (bus == nullptr) {
NORM_ERR("BMPx error 1: %s\n", error->message);
fail(error, current_info);
return;

View File

@ -24,14 +24,14 @@
#include "c++wrap.hh"
#include <stdio.h>
#include <cstdio>
#include <unistd.h>
/* force use of POSIX strerror_r instead of non-portable GNU specific */
#ifdef _GNU_SOURCE
#undef _GNU_SOURCE
#endif
#include <string.h>
#include <cstring>
#if __cplusplus <= 199711L
#define thread_local __thread
@ -42,17 +42,23 @@
namespace {
int pipe2_emulate(int pipefd[2], int flags) {
if (pipe(pipefd) == -1) return -1;
if (pipe(pipefd) == -1) {
return -1;
}
if (flags & O_CLOEXEC) {
if ((flags & O_CLOEXEC) != 0) {
// we emulate O_CLOEXEC if the system does not have it
// not very thread-safe, but at least it works
for (int i = 0; i < 2; ++i) {
int r = fcntl(pipefd[i], F_GETFD);
if (r == -1) return -1;
if (r == -1) {
return -1;
}
if (fcntl(pipefd[i], F_SETFD, r | FD_CLOEXEC) == -1) return -1;
if (fcntl(pipefd[i], F_SETFD, r | FD_CLOEXEC) == -1) {
return -1;
}
}
}
@ -67,15 +73,16 @@ int (*const pipe2_ptr)(int[2], int) = &pipe2;
std::string strerror_r(int errnum) {
static thread_local char buf[100];
if (strerror_r(errnum, buf, sizeof buf) != 0)
if (strerror_r(errnum, buf, sizeof buf) != 0) {
snprintf(buf, sizeof buf, "Unknown error %i", errnum);
}
return buf;
}
std::pair<int, int> pipe2(int flags) {
int fd[2];
if (pipe2_ptr(fd, flags) == -1)
if (pipe2_ptr(fd, flags) == -1) {
throw errno_error("pipe2");
else
return std::pair<int, int>(fd[0], fd[1]);
}
{ return std::pair<int, int>(fd[0], fd[1]); }
}

View File

@ -99,7 +99,7 @@ void curl_internal::do_work() {
struct headers_ {
struct curl_slist *h;
headers_() : h(NULL) {}
headers_() : h(nullptr) {}
~headers_() { curl_slist_free_all(h); }
} headers;

View File

@ -39,7 +39,7 @@
static short colour_depth = 0;
static long redmask, greenmask, bluemask;
static void set_up_gradient(void) {
static void set_up_gradient() {
int i;
#ifdef BUILD_X11
if (out_to_x.get(*state)) {
@ -81,9 +81,9 @@ unsigned int adjust_colours(unsigned int colour) {
r = (colour & 0xff0000) >> 16;
g = (colour & 0xff00) >> 8;
b = colour & 0xff;
colour = (int)(r * CONST_8_TO_5_BITS) << 11;
colour |= (int)(g * CONST_8_TO_6_BITS) << 5;
colour |= (int)(b * CONST_8_TO_5_BITS);
colour = static_cast<int>(r * CONST_8_TO_5_BITS) << 11;
colour |= static_cast<int>(g * CONST_8_TO_6_BITS) << 5;
colour |= static_cast<int>(b * CONST_8_TO_5_BITS);
}
return colour;
}
@ -96,8 +96,8 @@ unsigned long *do_gradient(int width, unsigned long first_colour,
int reddiff, greendiff, bluediff; // difference
short redshift = (2 * colour_depth / 3 + colour_depth % 3);
short greenshift = (colour_depth / 3);
unsigned long *colours =
(unsigned long *)malloc(width * sizeof(unsigned long));
auto *colours =
static_cast<unsigned long *>(malloc(width * sizeof(unsigned long)));
int i;
if (colour_depth == 0) {
@ -118,7 +118,7 @@ unsigned long *do_gradient(int width, unsigned long first_colour,
for (i = 0; i < width; i++) {
int red3 = 0, green3 = 0, blue3 = 0; // colour components
float factor = ((float)i / (width - 1));
float factor = (static_cast<float>(i) / (width - 1));
/* the '+ 0.5' bit rounds our floats to ints properly */
if (red1 >= red2) {
@ -167,7 +167,8 @@ long get_x11_color(const char *name) {
XColor color;
color.pixel = 0;
if (!XParseColor(display, DefaultColormap(display, screen), name, &color)) {
if (XParseColor(display, DefaultColormap(display, screen), name, &color) ==
0) {
/* lets check if it's a hex colour with the # missing in front
* if yes, then do something about it */
char newname[DEFAULT_TEXT_BUFFER_SIZE];
@ -175,17 +176,17 @@ long get_x11_color(const char *name) {
newname[0] = '#';
strncpy(&newname[1], name, DEFAULT_TEXT_BUFFER_SIZE - 1);
/* now lets try again */
if (!XParseColor(display, DefaultColormap(display, screen), &newname[0],
&color)) {
if (XParseColor(display, DefaultColormap(display, screen), &newname[0],
&color) == 0) {
NORM_ERR("can't parse X color '%s'", name);
return 0xFF00FF;
}
}
if (!XAllocColor(display, DefaultColormap(display, screen), &color)) {
if (XAllocColor(display, DefaultColormap(display, screen), &color) == 0) {
NORM_ERR("can't allocate X color '%s'", name);
}
return (long)color.pixel;
return static_cast<long>(color.pixel);
}
long get_x11_color(const std::string &colour) {

View File

@ -68,12 +68,13 @@ void parse_combine_arg(struct text_object *obj, const char *arg) {
}
if (startvar[0] >= 0 && endvar[0] >= 0 && startvar[1] >= 0 &&
endvar[1] >= 0) {
cd = (struct combine_data *)malloc(sizeof(struct combine_data));
cd =
static_cast<struct combine_data *>(malloc(sizeof(struct combine_data)));
memset(cd, 0, sizeof(struct combine_data));
cd->left = (char *)malloc(endvar[0] - startvar[0] + 1);
cd->seperation = (char *)malloc(startvar[1] - endvar[0] + 1);
cd->right = (char *)malloc(endvar[1] - startvar[1] + 1);
cd->left = static_cast<char *>(malloc(endvar[0] - startvar[0] + 1));
cd->seperation = static_cast<char *>(malloc(startvar[1] - endvar[0] + 1));
cd->right = static_cast<char *>(malloc(endvar[1] - startvar[1] + 1));
strncpy(cd->left, arg + startvar[0], endvar[0] - startvar[0]);
cd->left[endvar[0] - startvar[0]] = 0;
@ -84,9 +85,11 @@ void parse_combine_arg(struct text_object *obj, const char *arg) {
strncpy(cd->right, arg + startvar[1], endvar[1] - startvar[1]);
cd->right[endvar[1] - startvar[1]] = 0;
obj->sub = (struct text_object *)malloc(sizeof(struct text_object));
obj->sub =
static_cast<struct text_object *>(malloc(sizeof(struct text_object)));
extract_variable_text_internal(obj->sub, cd->left);
obj->sub->sub = (struct text_object *)malloc(sizeof(struct text_object));
obj->sub->sub =
static_cast<struct text_object *>(malloc(sizeof(struct text_object)));
extract_variable_text_internal(obj->sub->sub, cd->right);
obj->data.opaque = cd;
} else {
@ -95,7 +98,7 @@ void parse_combine_arg(struct text_object *obj, const char *arg) {
}
void print_combine(struct text_object *obj, char *p, int p_max_size) {
struct combine_data *cd = (struct combine_data *)obj->data.opaque;
auto *cd = static_cast<struct combine_data *>(obj->data.opaque);
std::vector<std::vector<char>> buf;
buf.resize(2);
buf[0].resize(max_user_text.get(*state));
@ -111,49 +114,60 @@ void print_combine(struct text_object *obj, char *p, int p_max_size) {
struct llrows *ll_rows[2], *current[2];
struct text_object *objsub = obj->sub;
if (!cd || !p_max_size) return;
if ((cd == nullptr) || (p_max_size == 0)) {
return;
}
p[0] = 0;
for (i = 0; i < 2; i++) {
nr_rows[i] = 1;
nextstart = 0;
ll_rows[i] = (struct llrows *)malloc(sizeof(struct llrows));
ll_rows[i] = static_cast<struct llrows *>(malloc(sizeof(struct llrows)));
current[i] = ll_rows[i];
for (j = 0; j < i; j++) objsub = objsub->sub;
for (j = 0; j < i; j++) {
objsub = objsub->sub;
}
generate_text_internal(&(buf[i][0]), max_user_text.get(*state), *objsub);
for (j = 0; buf[i][j] != 0; j++) {
if (buf[i][j] == '\t') buf[i][j] = ' ';
if (buf[i][j] == '\n')
if (buf[i][j] == '\t') {
buf[i][j] = ' ';
}
if (buf[i][j] == '\n') {
buf[i][j] = 0; // the vars inside combine may not have a \n at the end
}
if (buf[i][j] ==
2) { // \002 is used instead of \n to separate lines inside a var
buf[i][j] = 0;
current[i]->row = strdup(&(buf[i][0]) + nextstart);
if (i == 0 && (long)strlen(current[i]->row) > longest)
longest = (long)strlen(current[i]->row);
current[i]->next = (struct llrows *)malloc(sizeof(struct llrows));
if (i == 0 && static_cast<long>(strlen(current[i]->row)) > longest) {
longest = static_cast<long>(strlen(current[i]->row));
}
current[i]->next =
static_cast<struct llrows *>(malloc(sizeof(struct llrows)));
current[i] = current[i]->next;
nextstart = j + 1;
nr_rows[i]++;
}
}
current[i]->row = strdup(&(buf[i][0]) + nextstart);
if (i == 0 && (long)strlen(current[i]->row) > longest)
longest = (long)strlen(current[i]->row);
current[i]->next = NULL;
if (i == 0 && static_cast<long>(strlen(current[i]->row)) > longest) {
longest = static_cast<long>(strlen(current[i]->row));
}
current[i]->next = nullptr;
current[i] = ll_rows[i];
}
for (j = 0; j < (nr_rows[0] > nr_rows[1] ? nr_rows[0] : nr_rows[1]); j++) {
if (current[0]) {
if (current[0] != nullptr) {
strcat(p, current[0]->row);
i = strlen(current[0]->row);
} else
} else {
i = 0;
}
while (i < longest) {
strcat(p, " ");
i++;
}
if (current[1]) {
if (current[1] != nullptr) {
strcat(p, cd->seperation);
strcat(p, current[1]->row);
}
@ -161,14 +175,17 @@ void print_combine(struct text_object *obj, char *p, int p_max_size) {
#ifdef HAVE_OPENMP
#pragma omp parallel for schedule(dynamic, 10)
#endif /* HAVE_OPENMP */
for (i = 0; i < 2; i++)
if (current[i]) current[i] = current[i]->next;
for (i = 0; i < 2; i++) {
if (current[i] != nullptr) {
current[i] = current[i]->next;
}
}
}
#ifdef HAVE_OPENMP
#pragma omp parallel for schedule(dynamic, 10)
#endif /* HAVE_OPENMP */
for (i = 0; i < 2; i++) {
while (ll_rows[i] != NULL) {
while (ll_rows[i] != nullptr) {
current[i] = ll_rows[i];
free(current[i]->row);
ll_rows[i] = current[i]->next;
@ -178,9 +195,11 @@ void print_combine(struct text_object *obj, char *p, int p_max_size) {
}
void free_combine(struct text_object *obj) {
struct combine_data *cd = (struct combine_data *)obj->data.opaque;
auto *cd = static_cast<struct combine_data *>(obj->data.opaque);
if (!cd) return;
if (cd == nullptr) {
return;
}
free(cd->left);
free(cd->seperation);
free(cd->right);

View File

@ -27,16 +27,16 @@
*
*/
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/ioctl.h>
#include <time.h>
#include <unistd.h>
#include <cctype>
#include <cerrno>
#include <ctime>
#include <vector>
#include "config.h"
#include "conky.h"
@ -94,7 +94,7 @@ char *strndup(const char *s, size_t n) {
}
#endif /* HAVE_STRNDUP */
int update_uname(void) {
int update_uname() {
uname(&info.uname_s);
#if defined(__DragonFly__)
@ -102,8 +102,8 @@ int update_uname(void) {
size_t desc_n;
char desc[256];
if (sysctlbyname("kern.version", NULL, &desc_n, NULL, 0) == -1 ||
sysctlbyname("kern.version", desc, &desc_n, NULL, 0) == -1)
if (sysctlbyname("kern.version", nullptr, &desc_n, NULL, 0) == -1 ||
sysctlbyname("kern.version", desc, &desc_n, nullptr, 0) == -1)
perror("kern.version");
else {
char *start = desc;
@ -118,8 +118,8 @@ int update_uname(void) {
return 0;
}
double get_time(void) {
struct timespec tv;
double get_time() {
struct timespec tv {};
#ifdef _POSIX_MONOTONIC_CLOCK
clock_gettime(CLOCK_MONOTONIC, &tv);
#else
@ -132,24 +132,25 @@ double get_time(void) {
* variable_substitute, except only cheques for $HOME and ~/ in
* path. If HOME is unset it uses an empty string for substitution */
std::string to_real_path(const std::string &source) {
const char *homedir = getenv("HOME") ?: "";
if (source.find("~/") == 0)
const char *homedir = getenv("HOME") != nullptr ? getenv("HOME") : "";
if (source.find("~/") == 0) {
return homedir + source.substr(1);
else if (source.find("$HOME/") == 0)
}
if (source.find("$HOME/") == 0) {
return homedir + source.substr(5);
else
}
return source;
}
int open_fifo(const char *file, int *reported) {
int fd = 0;
fd = open(file, O_RDONLY | O_NONBLOCK);
fd = open(file, O_RDONLY | O_NONBLOCK | O_CLOEXEC);
if (fd == -1) {
if (!reported || *reported == 0) {
if ((reported == nullptr) || *reported == 0) {
NORM_ERR("can't open %s: %s", file, strerror(errno));
if (reported) {
if (reported != nullptr) {
*reported = 1;
}
}
@ -160,18 +161,18 @@ int open_fifo(const char *file, int *reported) {
}
FILE *open_file(const char *file, int *reported) {
FILE *fp = 0;
FILE *fp = nullptr;
fp = fopen(file, "r");
fp = fopen(file, "re");
if (!fp) {
if (!reported || *reported == 0) {
if (fp == nullptr) {
if ((reported == nullptr) || *reported == 0) {
NORM_ERR("can't open %s: %s", file, strerror(errno));
if (reported) {
if (reported != nullptr) {
*reported = 1;
}
}
return NULL;
return nullptr;
}
return fp;
@ -180,7 +181,9 @@ FILE *open_file(const char *file, int *reported) {
std::string variable_substitute(std::string s) {
std::string::size_type pos = 0;
while ((pos = s.find('$', pos)) != std::string::npos) {
if (pos + 1 >= s.size()) break;
if (pos + 1 >= s.size()) {
break;
}
if (s[pos + 1] == '$') {
s.erase(pos, 1);
@ -189,22 +192,27 @@ std::string variable_substitute(std::string s) {
std::string var;
std::string::size_type l = 0;
if (isalpha(s[pos + 1])) {
if (isalpha(s[pos + 1]) != 0) {
l = 1;
while (pos + l < s.size() && isalnum(s[pos + l])) ++l;
while (pos + l < s.size() && (isalnum(s[pos + l]) != 0)) {
++l;
}
var = s.substr(pos + 1, l - 1);
} else if (s[pos + 1] == '{') {
l = s.find('}', pos);
if (l == std::string::npos) break;
if (l == std::string::npos) {
break;
}
l -= pos - 1;
var = s.substr(pos + 2, l - 3);
} else
} else {
++pos;
}
if (l) {
if (l != 0u) {
s.erase(pos, l);
const char *val = getenv(var.c_str());
if (val) {
if (val != nullptr) {
s.insert(pos, val);
pos += strlen(val);
}
@ -265,7 +273,7 @@ void format_seconds_short(char *buf, unsigned int n, long seconds) {
conky::simple_config_setting<bool> no_buffers("no_buffers", true, true);
void update_stuff(void) {
void update_stuff() {
/* clear speeds, addresses and up status in case device was removed and
* doesn't get updated */
@ -273,7 +281,7 @@ void update_stuff(void) {
#pragma omp parallel for schedule(dynamic, 10)
#endif /* HAVE_OPENMP */
for (int i = 0; i < MAX_NET_INTERFACES; ++i) {
if (netstats[i].dev) {
if (netstats[i].dev != nullptr) {
netstats[i].up = 0;
netstats[i].recv_speed = 0.0;
netstats[i].trans_speed = 0.0;
@ -300,24 +308,22 @@ void update_stuff(void) {
/* Ohkie to return negative values for temperatures */
int round_to_int_temp(float f) {
if (f >= 0.0) {
return (int)(f + 0.5);
} else {
return (int)(f - 0.5);
return static_cast<int>(f + 0.5);
}
return static_cast<int>(f - 0.5);
}
/* Don't return negative values for cpugraph, bar, gauge, percentage.
* Causes unreasonable numbers to show */
unsigned int round_to_int(float f) {
if (f >= 0.0) {
return (int)(f + 0.5);
} else {
return 0;
return static_cast<int>(f + 0.5);
}
return 0;
}
void scan_loadavg_arg(struct text_object *obj, const char *arg) {
obj->data.i = 0;
if (arg && !arg[1] && isdigit(arg[0])) {
if ((arg != nullptr) && (arg[1] == 0) && (isdigit(arg[0]) != 0)) {
obj->data.i = atoi(arg);
if (obj->data.i > 3 || obj->data.i < 1) {
NORM_ERR("loadavg arg needs to be in range (1,3)");
@ -339,9 +345,10 @@ void print_loadavg(struct text_object *obj, char *p, int p_max_size) {
}
void scan_no_update(struct text_object *obj, const char *arg) {
obj->data.s = (char *)malloc(text_buffer_size.get(*state));
obj->data.s = static_cast<char *>(malloc(text_buffer_size.get(*state)));
evaluate(arg, obj->data.s, text_buffer_size.get(*state));
obj->data.s = (char *)realloc(obj->data.s, strlen(obj->data.s) + 1);
obj->data.s =
static_cast<char *>(realloc(obj->data.s, strlen(obj->data.s) + 1));
}
void free_no_update(struct text_object *obj) { free(obj->data.s); }
@ -352,7 +359,7 @@ void print_no_update(struct text_object *obj, char *p, int p_max_size) {
#ifdef BUILD_X11
void scan_loadgraph_arg(struct text_object *obj, const char *arg) {
char *buf = 0;
char *buf = nullptr;
buf = scan_graph(obj, arg, 0);
free_and_zero(buf);
@ -368,21 +375,19 @@ double loadgraphval(struct text_object *obj) {
uint8_t cpu_percentage(struct text_object *obj) {
if (obj->data.i > info.cpu_count) {
NORM_ERR("obj->data.i %i info.cpu_count %i", obj->data.i, info.cpu_count);
CRIT_ERR(NULL, NULL, "attempting to use more CPUs than you have!");
CRIT_ERR(nullptr, nullptr, "attempting to use more CPUs than you have!");
}
if (info.cpu_usage) {
if (info.cpu_usage != nullptr) {
return round_to_int(info.cpu_usage[obj->data.i] * 100.0);
} else {
return 0;
}
return 0;
}
double cpu_barval(struct text_object *obj) {
if (info.cpu_usage) {
if (info.cpu_usage != nullptr) {
return info.cpu_usage[obj->data.i];
} else {
return 0.;
}
return 0.;
}
#define PRINT_HR_GENERATOR(name) \
@ -404,31 +409,35 @@ PRINT_HR_GENERATOR(swapmax)
uint8_t mem_percentage(struct text_object *obj) {
(void)obj;
return (info.memmax ? round_to_int(info.mem * 100 / info.memmax) : 0);
return (info.memmax != 0u ? round_to_int(info.mem * 100 / info.memmax) : 0);
}
double mem_barval(struct text_object *obj) {
(void)obj;
return info.memmax ? ((double)info.mem / info.memmax) : 0;
return info.memmax != 0u ? (static_cast<double>(info.mem) / info.memmax) : 0;
}
double mem_with_buffers_barval(struct text_object *obj) {
(void)obj;
return info.memmax ? ((double)info.memwithbuffers / info.memmax) : 0;
return info.memmax != 0u
? (static_cast<double>(info.memwithbuffers) / info.memmax)
: 0;
}
uint8_t swap_percentage(struct text_object *obj) {
(void)obj;
return (info.swapmax ? round_to_int(info.swap * 100 / info.swapmax) : 0);
return (info.swapmax != 0u ? round_to_int(info.swap * 100 / info.swapmax)
: 0);
}
double swap_barval(struct text_object *obj) {
(void)obj;
return info.swapmax ? ((double)info.swap / info.swapmax) : 0;
return info.swapmax != 0u ? (static_cast<double>(info.swap) / info.swapmax)
: 0;
}
void print_kernel(struct text_object *obj, char *p, int p_max_size) {
@ -471,12 +480,12 @@ void print_version(struct text_object *obj, char *p, int p_max_size) {
void print_uptime(struct text_object *obj, char *p, int p_max_size) {
(void)obj;
format_seconds(p, p_max_size, (int)info.uptime);
format_seconds(p, p_max_size, static_cast<int>(info.uptime));
}
void print_uptime_short(struct text_object *obj, char *p, int p_max_size) {
(void)obj;
format_seconds_short(p, p_max_size, (int)info.uptime);
format_seconds_short(p, p_max_size, static_cast<int>(info.uptime));
}
void print_processes(struct text_object *obj, char *p, int p_max_size) {
@ -529,13 +538,13 @@ int if_empty_iftest(struct text_object *obj) {
static int check_contains(char *f, char *s) {
int ret = 0;
FILE *where = open_file(f, 0);
FILE *where = open_file(f, nullptr);
if (where) {
if (where != nullptr) {
char buf1[256];
while (fgets(buf1, 256, where)) {
if (strstr(buf1, s)) {
while (fgets(buf1, 256, where) != nullptr) {
if (strstr(buf1, s) != nullptr) {
ret = 1;
break;
}
@ -552,11 +561,17 @@ int if_existing_iftest(struct text_object *obj) {
int result = 0;
spc = strchr(obj->data.s, ' ');
if (spc != NULL) *spc = 0;
if (access(obj->data.s, F_OK) == 0) {
if (spc == NULL || check_contains(obj->data.s, spc + 1)) result = 1;
if (spc != nullptr) {
*spc = 0;
}
if (access(obj->data.s, F_OK) == 0) {
if (spc == nullptr || (check_contains(obj->data.s, spc + 1) != 0)) {
result = 1;
}
}
if (spc != nullptr) {
*spc = ' ';
}
if (spc != NULL) *spc = ' ';
return result;
}
@ -564,7 +579,7 @@ int if_running_iftest(struct text_object *obj) {
#ifdef __linux__
if (!get_process_by_name(obj->data.s)) {
#else
if ((obj->data.s) && system(obj->data.s)) {
if (((obj->data.s) != nullptr) && (system(obj->data.s) != 0)) {
#endif
return 0;
}
@ -581,14 +596,14 @@ void free_acpitemp(struct text_object *obj) { close(obj->data.i); }
void print_freq(struct text_object *obj, char *p, int p_max_size) {
static int ok = 1;
if (ok) {
if (ok != 0) {
ok = get_freq(p, p_max_size, "%.0f", 1, obj->data.i);
}
}
void print_freq_g(struct text_object *obj, char *p, int p_max_size) {
static int ok = 1;
if (ok) {
if (ok != 0) {
#ifndef __OpenBSD__
ok = get_freq(p, p_max_size, "%'.2f", 1000, obj->data.i);
#else
@ -605,7 +620,8 @@ void print_acpifan(struct text_object *obj, char *p, int p_max_size) {
}
void print_acpiacadapter(struct text_object *obj, char *p, int p_max_size) {
get_acpi_ac_adapter(p, p_max_size, (const char *)obj->data.opaque);
get_acpi_ac_adapter(p, p_max_size,
static_cast<const char *>(obj->data.opaque));
}
void print_battery(struct text_object *obj, char *p, int p_max_size) {
@ -633,21 +649,25 @@ void print_blink(struct text_object *obj, char *p, int p_max_size) {
static int last_len = 0;
int i;
if (visible) {
if (visible != 0) {
generate_text_internal(&(buf[0]), max_user_text.get(*state), *obj->sub);
last_len = strlen(&(buf[0]));
} else {
for (i = 0; i < last_len; i++) buf[i] = ' ';
for (i = 0; i < last_len; i++) {
buf[i] = ' ';
}
}
snprintf(p, p_max_size, "%s", &(buf[0]));
visible = !visible;
visible = static_cast<int>(static_cast<int>(visible) == 0);
}
void print_include(struct text_object *obj, char *p, int p_max_size) {
std::vector<char> buf(max_user_text.get(*state));
if (!obj->sub) return;
if (obj->sub == nullptr) {
return;
}
generate_text_internal(&(buf[0]), max_user_text.get(*state), *obj->sub);
snprintf(p, p_max_size, "%s", &(buf[0]));
@ -672,19 +692,20 @@ void print_to_bytes(struct text_object *obj, char *p, int p_max_size) {
generate_text_internal(&(buf[0]), max_user_text.get(*state), *obj->sub);
if (sscanf(&(buf[0]), "%Lf%s", &bytes, unit) == 2 && strlen(unit) < 16) {
if (strncasecmp("b", unit, 1) == 0)
if (strncasecmp("b", unit, 1) == 0) {
snprintf(&(buf[0]), max_user_text.get(*state), "%Lf", bytes);
else if (strncasecmp("k", unit, 1) == 0)
} else if (strncasecmp("k", unit, 1) == 0) {
snprintf(&(buf[0]), max_user_text.get(*state), "%Lf", bytes * 1024);
else if (strncasecmp("m", unit, 1) == 0)
} else if (strncasecmp("m", unit, 1) == 0) {
snprintf(&(buf[0]), max_user_text.get(*state), "%Lf",
bytes * 1024 * 1024);
else if (strncasecmp("g", unit, 1) == 0)
} else if (strncasecmp("g", unit, 1) == 0) {
snprintf(&(buf[0]), max_user_text.get(*state), "%Lf",
bytes * 1024 * 1024 * 1024);
else if (strncasecmp("t", unit, 1) == 0)
} else if (strncasecmp("t", unit, 1) == 0) {
snprintf(&(buf[0]), max_user_text.get(*state), "%Lf",
bytes * 1024 * 1024 * 1024 * 1024);
}
}
snprintf(p, p_max_size, "%s", &(buf[0]));
}
@ -695,6 +716,8 @@ void print_updates(struct text_object *obj, char *p, int p_max_size) {
}
int updatenr_iftest(struct text_object *obj) {
if (get_total_updates() % get_updatereset() != obj->data.i - 1) return 0;
if (get_total_updates() % get_updatereset() != obj->data.i - 1) {
return 0;
}
return 1;
}

View File

@ -66,8 +66,8 @@ FILE *open_file(const char *file, int *reported);
int open_fifo(const char *file, int *reported);
std::string variable_substitute(std::string s);
void format_seconds(char *buf, unsigned int n, long t);
void format_seconds_short(char *buf, unsigned int n, long t);
void format_seconds(char *buf, unsigned int n, long seconds);
void format_seconds_short(char *buf, unsigned int n, long seconds);
int round_to_int_temp(float);

File diff suppressed because it is too large Load Diff

View File

@ -360,7 +360,7 @@ template <class T>
void free_and_zero(T *&ptr) {
if (ptr) {
free(ptr);
ptr = NULL;
ptr = nullptr;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -53,7 +53,7 @@
#include <AvailabilityMacros.h>
#include <stdio.h>
#include <cstdio>
#include <sys/mount.h> // statfs
#include <sys/sysctl.h>
@ -65,12 +65,12 @@
#include <mach/mach.h> // update_total_processes
#include "top.h" // get_top_info
#include <dispatch/dispatch.h> // get_top_info
#include <libproc.h> // get_top_info
#include "top.h" // get_top_info
#include <ifaddrs.h> // update_net_stats
#include "net_stat.h" // update_net_stats
#include <ifaddrs.h> // update_net_stats
#include "darwin_sip.h" // sip status
@ -88,7 +88,7 @@
/* (E)nhanced printf */
#ifdef DEBUG_MODE
#include <stdarg.h>
#include <cstdarg>
void eprintf(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
@ -110,7 +110,7 @@ static conky::simple_config_setting<bool> top_cpu_separate("top_cpu_separate",
static int getsysctl(const char *name, void *ptr, size_t len) {
size_t nlen = len;
if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
if (sysctlbyname(name, ptr, &nlen, nullptr, 0) == -1) {
return -1;
}
@ -166,7 +166,7 @@ int clock_gettime(int clock_id, struct timespec *ts) {
* Uses mach API to get load info ( task_count, thread_count )
*
*/
static void helper_update_threads_processes(void) {
static void helper_update_threads_processes() {
static host_name_port_t machHost;
static processor_set_name_port_t processorSet = 0;
static bool machStuffInitialised = false;
@ -181,13 +181,15 @@ static void helper_update_threads_processes(void) {
}
/* get load info */
struct processor_set_load_info loadInfo;
struct processor_set_load_info loadInfo {};
mach_msg_type_number_t count = PROCESSOR_SET_LOAD_INFO_COUNT;
kern_return_t err =
processor_set_statistics(processorSet, PROCESSOR_SET_LOAD_INFO,
(processor_set_info_t)&loadInfo, &count);
kern_return_t err = processor_set_statistics(
processorSet, PROCESSOR_SET_LOAD_INFO,
reinterpret_cast<processor_set_info_t>(&loadInfo), &count);
if (err != KERN_SUCCESS) return;
if (err != KERN_SUCCESS) {
return;
}
info.procs = loadInfo.task_count;
info.threads = loadInfo.thread_count;
@ -228,13 +230,14 @@ static void get_cpu_sample(struct cpusample *sample) {
natural_t processorCount;
processor_cpu_load_info_t processorTickInfo;
mach_msg_type_number_t processorInfoCount;
struct cpusample *samples = NULL;
struct cpusample *samples = nullptr;
machHost = mach_host_self();
kern_return_t err = host_processor_info(
machHost, PROCESSOR_CPU_LOAD_INFO, &processorCount,
(processor_info_array_t *)&processorTickInfo, &processorInfoCount);
reinterpret_cast<processor_info_array_t *>(&processorTickInfo),
&processorInfoCount);
if (err != KERN_SUCCESS) {
printf("host_statistics: %s\n", mach_error_string(err));
return;
@ -279,10 +282,8 @@ static void get_cpu_sample(struct cpusample *sample) {
* Dealloc
*/
vm_deallocate(mach_task_self(), (vm_address_t)processorTickInfo,
(vm_size_t)(processorInfoCount * sizeof(natural_t)));
static_cast<vm_size_t>(processorInfoCount * sizeof(natural_t)));
delete[] samples;
return;
}
/*
@ -296,31 +297,31 @@ static void get_cpu_sample(struct cpusample *sample) {
* ATTENTION: Do not forget to free the array once you are done with it,
* it is not freed automatically.
*/
static int helper_get_proc_list(struct kinfo_proc **p = NULL) {
static int helper_get_proc_list(struct kinfo_proc **p) {
int err = 0;
size_t length = 0;
static const int name[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
/* Call sysctl with a NULL buffer to get proper length */
err = sysctl((int *)name, (sizeof(name) / sizeof(*name)) - 1, NULL, &length,
NULL, 0);
if (err) {
perror(NULL);
/* Call sysctl with a nullptr buffer to get proper length */
err = sysctl((int *)name, (sizeof(name) / sizeof(*name)) - 1, nullptr, &length,
nullptr, 0);
if (err != 0) {
perror(nullptr);
return (-1);
}
/* Allocate buffer */
*p = (kinfo_proc *)malloc(length);
if (!p) {
perror(NULL);
*p = static_cast<kinfo_proc *>(malloc(length));
if (p == nullptr) {
perror(nullptr);
return (-1);
}
/* Get the actual process list */
err = sysctl((int *)name, (sizeof(name) / sizeof(*name)) - 1, *p, &length,
NULL, 0);
if (err) {
perror(NULL);
nullptr, 0);
if (err != 0) {
perror(nullptr);
return (-1);
}
@ -356,10 +357,10 @@ static int swapmode(unsigned long *retavail, unsigned long *retfree) {
*/
int swapMIB[] = {CTL_VM, 5};
struct xsw_usage swapUsage;
struct xsw_usage swapUsage {};
size_t swapUsageSize = sizeof(swapUsage);
memset(&swapUsage, 0, sizeof(swapUsage));
if (sysctl(swapMIB, 2, &swapUsage, &swapUsageSize, NULL, 0) == 0) {
if (sysctl(swapMIB, 2, &swapUsage, &swapUsageSize, nullptr, 0) == 0) {
*retfree = swapUsage.xsu_avail / 1024;
*retavail = swapUsage.xsu_total / 1024;
} else {
@ -370,17 +371,17 @@ static int swapmode(unsigned long *retavail, unsigned long *retfree) {
return 1;
}
void prepare_update(void) {
void prepare_update() {
// in freebsd.cc this is empty so leaving it here too!
}
int update_uptime(void) {
int update_uptime() {
int mib[2] = {CTL_KERN, KERN_BOOTTIME};
struct timeval boottime;
struct timeval boottime {};
time_t now;
size_t size = sizeof(boottime);
if ((sysctl(mib, 2, &boottime, &size, NULL, 0) != -1) &&
if ((sysctl(mib, 2, &boottime, &size, nullptr, 0) != -1) &&
(boottime.tv_sec != 0)) {
time(&now);
info.uptime = now - boottime.tv_sec;
@ -404,7 +405,9 @@ int check_mount(struct text_object *obj) {
int num_mounts = 0;
struct statfs *mounts;
if (!obj->data.s) return 0;
if (obj->data.s == nullptr) {
return 0;
}
num_mounts = getmntinfo(&mounts, MNT_WAIT);
@ -413,10 +416,11 @@ int check_mount(struct text_object *obj) {
return 0;
}
for (int i = 0; i < num_mounts; i++)
for (int i = 0; i < num_mounts; i++) {
if (strcmp(mounts[i].f_mntonname, obj->data.s) == 0) {
return 1;
}
}
return 0;
}
@ -496,16 +500,16 @@ static void update_pages_stolen(libtop_tsamp_t *tsamp) {
/* These are all declared as QUAD/uint64_t sysctls in the kernel. */
if (-1 == sysctl(mib_reserved, mib_reserved_len, &reserved, &reserved_len,
NULL, 0)) {
nullptr, 0)) {
return;
}
if (-1 == sysctl(mib_unusable, mib_unusable_len, &unusable, &unusable_len,
NULL, 0)) {
nullptr, 0)) {
return;
}
if (-1 == sysctl(mib_other, mib_other_len, &other, &other_len, NULL, 0)) {
if (-1 == sysctl(mib_other, mib_other_len, &other, &other_len, nullptr, 0)) {
return;
}
@ -535,7 +539,8 @@ static int libtop_tsamp_update_vm_stats(libtop_tsamp_t *tsamp) {
mach_msg_type_number_t count = sizeof(tsamp->vm_stat) / sizeof(natural_t);
kr = host_statistics64(mach_host_self(), HOST_VM_INFO64,
(host_info64_t)&tsamp->vm_stat, &count);
reinterpret_cast<host_info64_t>(&tsamp->vm_stat),
&count);
if (kr != KERN_SUCCESS) {
return kr;
}
@ -545,9 +550,9 @@ static int libtop_tsamp_update_vm_stats(libtop_tsamp_t *tsamp) {
}
// Check whether we got purgeable memory statistics
tsamp->purgeable_is_valid =
(count == (sizeof(tsamp->vm_stat) / sizeof(natural_t)));
if (!tsamp->purgeable_is_valid) {
tsamp->purgeable_is_valid = static_cast<boolean_t>(
count == (sizeof(tsamp->vm_stat) / sizeof(natural_t)));
if (tsamp->purgeable_is_valid == 0u) {
tsamp->vm_stat.purgeable_count = 0;
tsamp->vm_stat.purges = 0;
}
@ -559,20 +564,20 @@ static int libtop_tsamp_update_vm_stats(libtop_tsamp_t *tsamp) {
* helper function for update_meminfo()
* return physical memory in bytes
*/
uint64_t get_physical_memory(void) {
uint64_t get_physical_memory() {
int mib[2] = {CTL_HW, HW_MEMSIZE};
int64_t physical_memory = 0;
size_t length = sizeof(int64_t);
if (sysctl(mib, 2, &physical_memory, &length, NULL, 0) == -1) {
if (sysctl(mib, 2, &physical_memory, &length, nullptr, 0) == -1) {
physical_memory = 0;
}
return physical_memory;
}
int update_meminfo(void) {
int update_meminfo() {
/* XXX implement remaining memory-related variables (see conky.h) */
/* XXX conky breaks the values ... :( probably some rounding problem...
Though we get the right values (based on top) */
@ -582,9 +587,11 @@ int update_meminfo(void) {
unsigned long swap_avail, swap_free;
static libtop_tsamp_t *tsamp = nullptr;
if (!tsamp) {
if (tsamp == nullptr) {
tsamp = new libtop_tsamp_t;
if (!tsamp) return 0;
if (tsamp == nullptr) {
return 0;
}
memset(tsamp, 0, sizeof(libtop_tsamp_t));
tsamp->pagesize = page_size;
@ -599,7 +606,9 @@ int update_meminfo(void) {
* but first update pages stolen count
*/
update_pages_stolen(tsamp);
if (libtop_tsamp_update_vm_stats(tsamp) == KERN_FAILURE) return 0;
if (libtop_tsamp_update_vm_stats(tsamp) == KERN_FAILURE) {
return 0;
}
/*
* This is actually a tricky part.
@ -644,7 +653,7 @@ int update_meminfo(void) {
return 0;
}
int update_net_stats(void) {
int update_net_stats() {
struct net_stat *ns;
double delta;
long long r, t, last_recv, last_trans;
@ -661,10 +670,10 @@ int update_net_stats(void) {
return 0;
}
for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
ns = get_net_stat((const char *)ifa->ifa_name, NULL, NULL);
for (ifa = ifap; ifa != nullptr; ifa = ifa->ifa_next) {
ns = get_net_stat((const char *)ifa->ifa_name, nullptr, nullptr);
if (ifa->ifa_flags & IFF_UP) {
if ((ifa->ifa_flags & IFF_UP) != 0u) {
struct ifaddrs *iftmp;
ns->up = 1;
@ -676,19 +685,20 @@ int update_net_stats(void) {
}
for (iftmp = ifa->ifa_next;
iftmp != NULL && strcmp(ifa->ifa_name, iftmp->ifa_name) == 0;
iftmp != nullptr && strcmp(ifa->ifa_name, iftmp->ifa_name) == 0;
iftmp = iftmp->ifa_next) {
if (iftmp->ifa_addr->sa_family == AF_INET) {
memcpy(&(ns->addr), iftmp->ifa_addr, iftmp->ifa_addr->sa_len);
}
}
ifd = (struct if_data *)ifa->ifa_data;
ifd = static_cast<struct if_data *>(ifa->ifa_data);
r = ifd->ifi_ibytes;
t = ifd->ifi_obytes;
if (r < ns->last_read_recv) {
ns->recv += ((long long)4294967295U - ns->last_read_recv) + r;
ns->recv +=
(static_cast<long long>(4294967295U) - ns->last_read_recv) + r;
} else {
ns->recv += (r - ns->last_read_recv);
}
@ -696,7 +706,8 @@ int update_net_stats(void) {
ns->last_read_recv = r;
if (t < ns->last_read_trans) {
ns->trans += ((long long)4294967295U - ns->last_read_trans) + t;
ns->trans +=
(static_cast<long long>(4294967295U) - ns->last_read_trans) + t;
} else {
ns->trans += (t - ns->last_read_trans);
}
@ -715,7 +726,7 @@ int update_net_stats(void) {
return 0;
}
int update_threads(void) {
int update_threads() {
helper_update_threads_processes();
return 0;
}
@ -731,20 +742,22 @@ int update_threads(void) {
* Foreach pid and foreach pid's threads check their state and increment
* the run_threads counter acordingly.
*/
int update_running_threads(void) {
struct kinfo_proc *p = NULL;
int update_running_threads() {
struct kinfo_proc *p = nullptr;
int proc_count = 0;
int run_threads = 0;
proc_count = helper_get_proc_list(&p);
if (proc_count == -1) return 0;
if (proc_count == -1) {
return 0;
}
for (int i = 0; i < proc_count; i++)
if (p[i].kp_proc.p_stat & SRUN) {
for (int i = 0; i < proc_count; i++) {
if ((p[i].kp_proc.p_stat & SRUN) != 0) {
pid_t pid = 0;
struct proc_taskinfo pti;
struct proc_threadinfo pthi;
struct proc_taskinfo pti {};
struct proc_threadinfo pthi {};
int num_threads = 0;
pid = p[i].kp_proc.p_pid;
@ -753,24 +766,30 @@ int update_running_threads(void) {
if (sizeof(pti) ==
proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &pti, sizeof(pti))) {
num_threads = pti.pti_threadnum;
} else
} else {
continue;
}
/* foreach thread check its state */
for (int i = 0; i < num_threads; i++)
for (int i = 0; i < num_threads; i++) {
if (sizeof(pthi) ==
proc_pidinfo(pid, PROC_PIDTHREADINFO, i, &pthi, sizeof(pthi))) {
if (pthi.pth_run_state == TH_STATE_RUNNING) run_threads++;
} else
if (pthi.pth_run_state == TH_STATE_RUNNING) {
run_threads++;
}
} else {
continue;
}
}
}
}
free(p);
info.run_threads = run_threads;
return 0;
}
int update_total_processes(void) {
int update_total_processes() {
helper_update_threads_processes();
return 0;
@ -811,20 +830,23 @@ int update_total_processes(void) {
*/
}
int update_running_processes(void) {
struct kinfo_proc *p = NULL;
int update_running_processes() {
struct kinfo_proc *p = nullptr;
int proc_count = 0;
int run_procs = 0;
proc_count = helper_get_proc_list(&p);
if (proc_count == -1) return 0;
if (proc_count == -1) {
return 0;
}
for (int i = 0; i < proc_count; i++) {
int state = p[i].kp_proc.p_stat;
if (state == SRUN) // XXX this check needs to be fixed...
if (state == SRUN) { // XXX this check needs to be fixed...
run_procs++;
}
}
free(p);
@ -838,7 +860,7 @@ int update_running_processes(void) {
* The macOS implementation gets the number of active cpus
* in compliance with linux implementation.
*/
void get_cpu_count(void) {
void get_cpu_count() {
int cpu_count = 0;
if (GETSYSCTL("hw.activecpu", cpu_count) == 0) {
@ -850,13 +872,14 @@ void get_cpu_count(void) {
/* XXX this can be moved to update_cpu_usage() but keep here to follow linux
* implementation */
if (!info.cpu_usage) {
if (info.cpu_usage == nullptr) {
/*
* Allocate ncpus+1 slots because cpu_usage[0] is overall usage.
*/
info.cpu_usage = (float *)malloc((info.cpu_count + 1) * sizeof(float));
if (info.cpu_usage == NULL) {
CRIT_ERR(NULL, NULL, "malloc");
info.cpu_usage =
static_cast<float *>(malloc((info.cpu_count + 1) * sizeof(float)));
if (info.cpu_usage == nullptr) {
CRIT_ERR(nullptr, nullptr, "malloc");
}
}
}
@ -869,17 +892,17 @@ struct cpu_info {
long oldused;
};
int update_cpu_usage(void) {
int update_cpu_usage() {
/* XXX add support for multiple cpus (see linux.cc) */
static bool cpu_setup = 0;
long used, total;
static struct cpu_info *cpu = NULL;
static struct cpu_info *cpu = nullptr;
unsigned int malloc_cpu_size = 0;
extern void *global_cpu;
struct cpusample sample;
struct cpusample sample {};
static pthread_mutex_t last_stat_update_mutex = PTHREAD_MUTEX_INITIALIZER;
static double last_stat_update = 0.0;
@ -896,17 +919,17 @@ int update_cpu_usage(void) {
pthread_mutex_unlock(&last_stat_update_mutex);
/* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */
if ((cpu_setup == 0) || (!info.cpu_usage)) {
if ((static_cast<int>(cpu_setup) == 0) || (info.cpu_usage == nullptr)) {
get_cpu_count();
cpu_setup = 1;
}
if (!global_cpu) {
if (global_cpu == nullptr) {
/*
* Allocate ncpus+1 slots because cpu_usage[0] is overall usage.
*/
malloc_cpu_size = (info.cpu_count + 1) * sizeof(struct cpu_info);
cpu = (cpu_info *)malloc(malloc_cpu_size);
cpu = static_cast<cpu_info *>(malloc(malloc_cpu_size));
memset(cpu, 0, malloc_cpu_size);
global_cpu = cpu;
}
@ -916,8 +939,8 @@ int update_cpu_usage(void) {
used = total - sample.totalIdleTime;
if ((total - cpu[0].oldtotal) != 0) {
info.cpu_usage[0] =
((double)(used - cpu[0].oldused)) / (double)(total - cpu[0].oldtotal);
info.cpu_usage[0] = (static_cast<double>(used - cpu[0].oldused)) /
static_cast<double>(total - cpu[0].oldtotal);
} else {
info.cpu_usage[0] = 0;
}
@ -928,33 +951,34 @@ int update_cpu_usage(void) {
return 0;
}
int update_load_average(void) {
int update_load_average() {
double v[3];
getloadavg(v, 3);
info.loadavg[0] = (double)v[0];
info.loadavg[1] = (double)v[1];
info.loadavg[2] = (double)v[2];
info.loadavg[0] = v[0];
info.loadavg[1] = v[1];
info.loadavg[2] = v[2];
return 0;
}
double get_acpi_temperature(int fd) {
double get_acpi_temperature(int /*fd*/) {
printf("get_acpi_temperature: STUB\n");
return 0.0;
}
void get_battery_stuff(char *buf, unsigned int n, const char *bat, int item) {
void get_battery_stuff(char * /*buf*/, unsigned int /*n*/, const char * /*bat*/,
int /*item*/) {
printf("get_battery_stuff: STUB\n");
}
int get_battery_perct(const char *bat) {
int get_battery_perct(const char * /*bat*/) {
printf("get_battery_perct: STUB\n");
return 1;
}
double get_battery_perct_bar(struct text_object *obj) {
double get_battery_perct_bar(struct text_object * /*obj*/) {
printf("get_battery_perct_bar: STUB\n");
return 0.0;
}
@ -967,18 +991,19 @@ int open_acpi_temperature(const char *name) {
return 0;
}
void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size,
const char *adapter) {
void get_acpi_ac_adapter(char * /*p_client_buffer*/,
size_t /*client_buffer_size*/,
const char * /*adapter*/) {
printf("get_acpi_ac_adapter: STUB\n");
}
void get_acpi_fan(char *p_client_buffer, size_t client_buffer_size) {
void get_acpi_fan(char * /*p_client_buffer*/, size_t /*client_buffer_size*/) {
printf("get_acpi_fan: STUB\n");
}
/* void */
char get_freq(char *p_client_buffer, size_t client_buffer_size,
const char *p_format, int divisor, unsigned int cpu) {
const char *p_format, int divisor, unsigned int /*cpu*/) {
/*
* For now, we get the factory cpu frequency, not **current** cpu frequency
* (Also, it is always the same for every core, so ignore |cpu| argument)
@ -990,8 +1015,8 @@ char get_freq(char *p_client_buffer, size_t client_buffer_size,
unsigned int freq;
size_t len;
if (!p_client_buffer || client_buffer_size <= 0 || !p_format ||
divisor <= 0) {
if ((p_client_buffer == nullptr) || client_buffer_size <= 0 ||
(p_format == nullptr) || divisor <= 0) {
return 0;
}
@ -999,14 +1024,14 @@ char get_freq(char *p_client_buffer, size_t client_buffer_size,
mib[1] = HW_CPU_FREQ;
len = sizeof(freq);
if (sysctl(mib, 2, &freq, &len, NULL, 0) == 0) {
if (sysctl(mib, 2, &freq, &len, nullptr, 0) == 0) {
/*
* convert to MHz
*/
divisor *= 1000000;
snprintf(p_client_buffer, client_buffer_size, p_format,
(float)freq / divisor);
static_cast<float>(freq) / divisor);
} else {
snprintf(p_client_buffer, client_buffer_size, p_format, 0.0f);
return 0;
@ -1022,20 +1047,21 @@ void update_wifi_stats(void)
}
#endif
int update_diskio(void) {
int update_diskio() {
printf("update_diskio: STUB\n");
return 0;
}
void get_battery_short_status(char *buffer, unsigned int n, const char *bat) {
void get_battery_short_status(char * /*buffer*/, unsigned int /*n*/,
const char * /*bat*/) {
printf("get_battery_short_status: STUB\n");
}
int get_entropy_avail(unsigned int *val) {
int get_entropy_avail(const unsigned int *val) {
(void)val;
return 1;
}
int get_entropy_poolsize(unsigned int *val) {
int get_entropy_poolsize(const unsigned int *val) {
(void)val;
return 1;
}
@ -1049,9 +1075,12 @@ int get_entropy_poolsize(unsigned int *val) {
*/
static void calc_cpu_usage_for_proc(struct process *proc, uint64_t total) {
float mul = 100.0;
if (top_cpu_separate.get(*state)) mul *= info.cpu_count;
if (top_cpu_separate.get(*state)) {
mul *= info.cpu_count;
}
proc->amount = mul * (proc->user_time + proc->kernel_time) / (float)total;
proc->amount =
mul * (proc->user_time + proc->kernel_time) / static_cast<float>(total);
}
/*
@ -1061,7 +1090,7 @@ static void calc_cpu_usage_for_proc(struct process *proc, uint64_t total) {
static void calc_cpu_total(struct process *proc, uint64_t *total) {
uint64_t current_total = 0; /* of current iteration */
// uint64_t total = 0; /* delta */
struct cpusample sample;
struct cpusample sample {};
get_cpu_sample(&sample);
current_total =
@ -1119,8 +1148,8 @@ static void calc_cpu_time_for_proc(struct process *process,
* process ) to implement get_top_info()
*/
static void get_top_info_for_kinfo_proc(struct kinfo_proc *p) {
struct process *proc = NULL;
struct proc_taskinfo pti;
struct process *proc = nullptr;
struct proc_taskinfo pti {};
pid_t pid;
pid = p->kp_proc.p_pid;
@ -1164,8 +1193,9 @@ static void get_top_info_for_kinfo_proc(struct kinfo_proc *p) {
/*
* wait until done
*/
while (!(calc_cpu_total_finished && calc_proc_total_finished))
while (!(calc_cpu_total_finished && calc_proc_total_finished)) {
;
}
/* calc the amount(%) of CPU the process used */
calc_cpu_usage_for_proc(proc, t);
@ -1174,9 +1204,9 @@ static void get_top_info_for_kinfo_proc(struct kinfo_proc *p) {
/* While topless is obviously better, top is also not bad. */
void get_top_info(void) {
void get_top_info() {
int proc_count = 0;
struct kinfo_proc *p = NULL;
struct kinfo_proc *p = nullptr;
/*
* QUICKFIX for #16
@ -1199,13 +1229,16 @@ void get_top_info(void) {
*/
proc_count = helper_get_proc_list(&p);
if (proc_count == -1) return;
if (proc_count == -1) {
return;
}
/*
* get top info for-each process
*/
for (int i = 0; i < proc_count; i++) {
if (!((p[i].kp_proc.p_flag & P_SYSTEM)) && *p[i].kp_proc.p_comm != '\0') {
if ((((p[i].kp_proc.p_flag & P_SYSTEM)) == 0) &&
*p[i].kp_proc.p_comm != '\0') {
get_top_info_for_kinfo_proc(&p[i]);
}
}
@ -1224,9 +1257,11 @@ void get_top_info(void) {
* Also, flip the result on occasion
*/
bool _csr_check(int aMask, bool aFlipflag) {
bool bit = (info.csr_config & aMask);
bool bit = (info.csr_config & aMask) != 0u;
if (aFlipflag) return !bit;
if (aFlipflag) {
return !bit;
}
return bit;
}
@ -1234,7 +1269,7 @@ bool _csr_check(int aMask, bool aFlipflag) {
/*
* Extract info from the csr_config variable and set the flags struct
*/
void fill_csr_config_flags_struct(void) {
void fill_csr_config_flags_struct() {
info.csr_config_flags.csr_allow_apple_internal =
_csr_check(CSR_ALLOW_APPLE_INTERNAL, 0);
info.csr_config_flags.csr_allow_untrusted_kexts =
@ -1260,7 +1295,7 @@ void fill_csr_config_flags_struct(void) {
/*
* Get SIP configuration ( sets csr_config and csr_config_flags )
*/
int get_sip_status(void) {
int get_sip_status() {
if (csr_get_active_config ==
nullptr) /* check if weakly linked symbol exists */
{
@ -1315,7 +1350,9 @@ void print_sip_status(struct text_object *obj, char *p, int p_max_size) {
/* conky window output */
(void)obj;
if (!obj->data.s) return;
if (obj->data.s == nullptr) {
return;
}
if (strlen(obj->data.s) == 0) {
snprintf(p, p_max_size, "%s",
@ -1371,11 +1408,11 @@ void print_sip_status(struct text_object *obj, char *p, int p_max_size) {
info.csr_config_flags.csr_allow_user_approved_kexts ? "YES" : "NO");
break;
case 'a':
snprintf(
p, p_max_size, "%s",
(info.csr_config && (info.csr_config != CSR_ALLOW_APPLE_INTERNAL))
? "unsupported configuration, beware!"
: "configuration is ok");
snprintf(p, p_max_size, "%s",
((info.csr_config != 0u) &&
(info.csr_config != CSR_ALLOW_APPLE_INTERNAL))
? "unsupported configuration, beware!"
: "configuration is ok");
break;
default:
snprintf(p, p_max_size, "%s", "unsupported");

View File

@ -49,8 +49,8 @@ int clock_gettime(int clock_id, struct timespec *ts);
int update_running_threads(void);
int get_entropy_avail(unsigned int *);
int get_entropy_poolsize(unsigned int *);
int get_entropy_avail(const unsigned int *);
int get_entropy_poolsize(const unsigned int *);
/* System Integrity Protection */
int get_sip_status(void);

View File

@ -49,11 +49,14 @@ typedef std::unordered_map<std::string, lua::cpp_function> data_sources_t;
data_sources_t *data_sources;
data_source_base &get_data_source(lua::state *l) {
if (l->gettop() != 1) throw std::runtime_error("Wrong number of parameters");
if (l->gettop() != 1) {
throw std::runtime_error("Wrong number of parameters");
}
l->rawgetfield(lua::REGISTRYINDEX, priv::data_source_metatable);
if (not l->getmetatable(-2) or not l->rawequal(-1, -2))
if (not l->getmetatable(-2) or not l->rawequal(-1, -2)) {
throw std::runtime_error("Invalid parameter");
}
return *static_cast<data_source_base *>(l->touserdata(1));
}
@ -89,15 +92,16 @@ void do_register_data_source(const std::string &name,
data_source_constructor() { data_sources = new data_sources_t(); }
~data_source_constructor() {
delete data_sources;
data_sources = NULL;
data_sources = nullptr;
}
};
static data_source_constructor constructor;
bool inserted = data_sources->insert({name, fn}).second;
if (not inserted)
if (not inserted) {
throw std::logic_error("Data source with name '" + name +
"' already registered");
}
}
disabled_data_source::disabled_data_source(lua::state *l,
@ -144,9 +148,9 @@ void export_data_sources(lua::state &l) {
l.newtable();
{
for (auto i = data_sources->begin(); i != data_sources->end(); ++i) {
l.pushfunction(i->second);
l.rawsetfield(-2, i->first.c_str());
for (auto &data_source : *data_sources) {
l.pushfunction(data_source.second);
l.rawsetfield(-2, data_source.first.c_str());
}
}
l.rawsetfield(-2, "variables");

View File

@ -28,8 +28,8 @@
*/
#include "diskio.h"
#include <stdlib.h>
#include <sys/stat.h>
#include <cstdlib>
#include <vector>
#include "common.h"
#include "config.h"
@ -43,9 +43,9 @@
* also containing the totals. */
struct diskio_stat stats;
void clear_diskio_stats(void) {
void clear_diskio_stats() {
struct diskio_stat *cur;
while (stats.next) {
while (stats.next != nullptr) {
cur = stats.next;
stats.next = stats.next->next;
free_and_zero(cur->dev);
@ -54,26 +54,26 @@ void clear_diskio_stats(void) {
}
struct diskio_stat *prepare_diskio_stat(const char *s) {
struct stat sb;
struct stat sb {};
std::vector<char> stat_name(text_buffer_size.get(*state)),
device_name(text_buffer_size.get(*state)),
device_s(text_buffer_size.get(*state));
struct diskio_stat *cur = &stats;
char *rpbuf;
if (!s) {
if (s == nullptr) {
return &stats;
}
if (strncmp(s, "label:", 6) == 0) {
snprintf(&(device_name[0]), text_buffer_size.get(*state),
"/dev/disk/by-label/%s", s + 6);
rpbuf = realpath(&device_name[0], NULL);
rpbuf = realpath(&device_name[0], nullptr);
} else {
rpbuf = realpath(s, NULL);
rpbuf = realpath(s, nullptr);
}
if (rpbuf) {
if (rpbuf != nullptr) {
strncpy(&device_s[0], rpbuf, text_buffer_size.get(*state));
free(rpbuf);
} else {
@ -95,15 +95,15 @@ struct diskio_stat *prepare_diskio_stat(const char *s) {
snprintf(&(stat_name[0]), text_buffer_size.get(*state), "/dev/%s",
&(device_name[0]));
if (stat(&(stat_name[0]), &sb) || !S_ISBLK(sb.st_mode)) {
if ((stat(&(stat_name[0]), &sb) != 0) || !S_ISBLK(sb.st_mode)) {
NORM_ERR("diskio device '%s' does not exist", &device_s[0]);
}
#endif
/* lookup existing */
while (cur->next) {
while (cur->next != nullptr) {
cur = cur->next;
if (!strcmp(cur->dev, &(device_name[0]))) {
if (strcmp(cur->dev, &(device_name[0])) == 0) {
return cur;
}
}
@ -130,17 +130,20 @@ void parse_diskio_arg(struct text_object *obj, const char *arg) {
*/
static void print_diskio_dir(struct text_object *obj, int dir, char *p,
int p_max_size) {
struct diskio_stat *diskio = (struct diskio_stat *)obj->data.opaque;
auto *diskio = static_cast<struct diskio_stat *>(obj->data.opaque);
double val;
if (!diskio) return;
if (diskio == nullptr) {
return;
}
if (dir < 0)
if (dir < 0) {
val = diskio->current_read;
else if (dir == 0)
} else if (dir == 0) {
val = diskio->current;
else
} else {
val = diskio->current_write;
}
/* TODO: move this correction from kB to kB/s elsewhere
* (or get rid of it??) */
@ -161,7 +164,7 @@ void print_diskio_write(struct text_object *obj, char *p, int p_max_size) {
#ifdef BUILD_X11
void parse_diskiograph_arg(struct text_object *obj, const char *arg) {
char *buf = 0;
char *buf = nullptr;
buf = scan_graph(obj, arg, 0);
obj->data.opaque = prepare_diskio_stat(dev_name(buf));
@ -169,21 +172,21 @@ void parse_diskiograph_arg(struct text_object *obj, const char *arg) {
}
double diskiographval(struct text_object *obj) {
struct diskio_stat *diskio = (struct diskio_stat *)obj->data.opaque;
auto *diskio = static_cast<struct diskio_stat *>(obj->data.opaque);
return (diskio ? diskio->current : 0);
return (diskio != nullptr ? diskio->current : 0);
}
double diskiographval_read(struct text_object *obj) {
struct diskio_stat *diskio = (struct diskio_stat *)obj->data.opaque;
auto *diskio = static_cast<struct diskio_stat *>(obj->data.opaque);
return (diskio ? diskio->current_read : 0);
return (diskio != nullptr ? diskio->current_read : 0);
}
double diskiographval_write(struct text_object *obj) {
struct diskio_stat *diskio = (struct diskio_stat *)obj->data.opaque;
auto *diskio = static_cast<struct diskio_stat *>(obj->data.opaque);
return (diskio ? diskio->current_write : 0);
return (diskio != nullptr ? diskio->current_write : 0);
}
#endif /* BUILD_X11 */
@ -212,9 +215,9 @@ void update_diskio_values(struct diskio_stat *ds, unsigned int reads,
sum_r += ds->sample_read[i];
sum_w += ds->sample_write[i];
}
ds->current = sum / (double)samples;
ds->current_read = sum_r / (double)samples;
ds->current_write = sum_w / (double)samples;
ds->current = sum / static_cast<double>(samples);
ds->current_read = sum_r / static_cast<double>(samples);
ds->current_write = sum_w / static_cast<double>(samples);
/* shift sample history */
for (i = samples - 1; i > 0; i--) {

View File

@ -67,7 +67,7 @@ static short cpu_setup = 0;
static int getsysctl(const char *name, void *ptr, size_t len) {
size_t nlen = len;
if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
if (sysctlbyname(name, ptr, &nlen, nullptr, 0) == -1) {
fprintf(stderr, "getsysctl(): %s failed '%s'\n", name, strerror(errno));
return -1;
}
@ -84,9 +84,9 @@ static int swapmode(unsigned long *retavail, unsigned long *retfree) {
int total, used;
size_t len = sizeof(int);
if (sysctlbyname("vm.swap_size", &total, &len, NULL, 0) == -1)
if (sysctlbyname("vm.swap_size", &total, &len, nullptr, 0) == -1)
perror("vm_swap_usage(): vm.swap_size");
else if (sysctlbyname("vm.swap_anon_use", &used, &len, NULL, 0) == -1)
else if (sysctlbyname("vm.swap_anon_use", &used, &len, nullptr, 0) == -1)
perror("vm_swap_usage(): vm.swap_anon_use");
else {
int size = getpagesize();
@ -109,7 +109,7 @@ int update_uptime(void) {
time_t now;
size_t size = sizeof(boottime);
if ((sysctl(mib, 2, &boottime, &size, NULL, 0) != -1) && boottime.tv_sec) {
if ((sysctl(mib, 2, &boottime, &size, nullptr, 0) != -1) && boottime.tv_sec) {
time(&now);
info.uptime = now - boottime.tv_sec;
} else {
@ -187,7 +187,7 @@ int update_net_stats(void) {
}
for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
ns = get_net_stat((const char *)ifa->ifa_name, NULL, NULL);
ns = get_net_stat((const char *)ifa->ifa_name, nullptr, NULL);
if (ifa->ifa_flags & IFF_UP) {
struct ifaddrs *iftmp;
@ -201,7 +201,7 @@ int update_net_stats(void) {
}
for (iftmp = ifa->ifa_next;
iftmp != NULL && strcmp(ifa->ifa_name, iftmp->ifa_name) == 0;
iftmp != nullptr && strcmp(ifa->ifa_name, iftmp->ifa_name) == 0;
iftmp = iftmp->ifa_next) {
if (iftmp->ifa_addr->sa_family == AF_INET) {
memcpy(&(ns->addr), iftmp->ifa_addr, iftmp->ifa_addr->sa_len);
@ -243,7 +243,7 @@ int update_net_stats(void) {
static int kern_proc_all_n() {
size_t len = 0;
if (sysctlbyname("kern.proc.all_lwp", NULL, &len, NULL, 0) == -1) {
if (sysctlbyname("kern.proc.all_lwp", nullptr, &len, NULL, 0) == -1) {
perror("kern.proc.all_lwp");
return -1;
}
@ -264,7 +264,7 @@ static struct kinfo_proc *kern_proc_all(size_t proc_n) {
struct kinfo_proc *kp = (struct kinfo_proc *)malloc(len);
if (kp) {
if (sysctlbyname("kern.proc.all_lwp", kp, &len, NULL, 0) == -1)
if (sysctlbyname("kern.proc.all_lwp", kp, &len, nullptr, 0) == -1)
perror("kern_proc(): kern.proc.all_lwp");
else
return kp;
@ -272,7 +272,7 @@ static struct kinfo_proc *kern_proc_all(size_t proc_n) {
} else
perror("malloc");
}
return NULL;
return nullptr;
}
void get_cpu_count(void) {
@ -286,8 +286,8 @@ void get_cpu_count(void) {
}
info.cpu_usage = (float *)malloc((info.cpu_count + 1) * sizeof(float));
if (info.cpu_usage == NULL) {
CRIT_ERR(NULL, NULL, "malloc");
if (info.cpu_usage == nullptr) {
CRIT_ERR(nullptr, NULL, "malloc");
}
}
@ -313,7 +313,7 @@ static void stat_cpu(struct cpu_info *cpu, struct kinfo_cputime *percpu,
}
int update_cpu_usage(void) {
static struct cpu_info *cpu = NULL;
static struct cpu_info *cpu = nullptr;
extern void *global_cpu;
/* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */
@ -335,7 +335,7 @@ int update_cpu_usage(void) {
info.cpu_count * sizeof(struct kinfo_cputime));
if (percpu) {
if (sysctlbyname("kern.cputime", percpu, &percpu_n, NULL, 0) == -1 &&
if (sysctlbyname("kern.cputime", percpu, &percpu_n, nullptr, 0) == -1 &&
errno != ENOMEM) {
printf("update_cpu_usage(): with %d cpu(s) ", info.cpu_count);
perror("kern.cputime");
@ -545,7 +545,7 @@ void update_wifi_stats(void)
}
for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
ns = get_net_stat((const char *) ifa->ifa_name, NULL, NULL);
ns = get_net_stat((const char *) ifa->ifa_name, nullptr, NULL);
s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
@ -586,7 +586,7 @@ cleanup:
int update_diskio(void) {
int devs_count, num_selected, num_selections, dn;
struct device_selection *dev_select = NULL;
struct device_selection *dev_select = nullptr;
long select_generation;
static struct statinfo statinfo_cur;
char device_name[DEFAULT_TEXT_BUFFER_SIZE];
@ -606,7 +606,7 @@ int update_diskio(void) {
devs_count = statinfo_cur.dinfo->numdevs;
if (selectdevs(&dev_select, &num_selected, &num_selections,
&select_generation, statinfo_cur.dinfo->generation,
statinfo_cur.dinfo->devices, devs_count, NULL, 0, NULL, 0,
statinfo_cur.dinfo->devices, devs_count, nullptr, 0, NULL, 0,
DS_SELECT_ONLY, MAXSHOWDEVS, 1) >= 0) {
for (dn = 0; dn < devs_count; dn++) {
int di;

View File

@ -49,14 +49,14 @@
#endif
struct _entropy {
_entropy() : avail(0), poolsize(0) {}
unsigned int avail;
unsigned int poolsize;
_entropy() = default;
unsigned int avail{0};
unsigned int poolsize{0};
};
static _entropy entropy;
int update_entropy(void) {
int update_entropy() {
get_entropy_avail(&entropy.avail);
get_entropy_poolsize(&entropy.poolsize);
return 0;
@ -69,7 +69,8 @@ void print_entropy_avail(struct text_object *obj, char *p, int p_max_size) {
uint8_t entropy_percentage(struct text_object *obj) {
(void)obj;
return round_to_int((double)entropy.avail * 100.0 / (double)entropy.poolsize);
return round_to_int(static_cast<double>(entropy.avail) * 100.0 /
static_cast<double>(entropy.poolsize));
}
void print_entropy_poolsize(struct text_object *obj, char *p, int p_max_size) {
@ -80,5 +81,5 @@ void print_entropy_poolsize(struct text_object *obj, char *p, int p_max_size) {
double entropy_barval(struct text_object *obj) {
(void)obj;
return (double)entropy.avail / entropy.poolsize;
return static_cast<double>(entropy.avail) / entropy.poolsize;
}

View File

@ -103,13 +103,13 @@ int parseTrainingXml(char *data, Character *s) {
struct tm end_tm, cache_tm;
// initialize the time structs
time_t now = time(NULL);
time_t now = time(nullptr);
localtime_r(&now, &end_tm);
localtime_r(&now, &cache_tm);
if (!data) return 1;
doc = xmlReadMemory(data, strlen(data), "", NULL, XML_PARSE_RECOVER);
doc = xmlReadMemory(data, strlen(data), "", nullptr, XML_PARSE_RECOVER);
root = xmlDocGetRootElement(doc);
for (n = root->children; n; n = n->next) {
@ -153,14 +153,14 @@ int parseTrainingXml(char *data, Character *s) {
static char *getXmlFromAPI(const char *apiKeyID, const char *apiVCode,
const char *charid, const char *url) {
struct curl_httppost *post = NULL;
struct curl_httppost *last = NULL;
struct curl_httppost *post = nullptr;
struct curl_httppost *last = nullptr;
struct xmlData chr;
char *content;
CURL *curl_handle;
int rc = 0;
chr.data = NULL;
chr.data = nullptr;
chr.size = 0;
curl_handle = curl_easy_init();
@ -183,8 +183,8 @@ static char *getXmlFromAPI(const char *apiKeyID, const char *apiVCode,
rc = curl_easy_perform(curl_handle);
if (chr.data == NULL) {
return NULL;
if (chr.data == nullptr) {
return nullptr;
}
content = strdup(chr.data);
@ -197,9 +197,9 @@ static void init_eve(void) {
int i;
for (i = 0; i < MAXCHARS; i++) {
eveCharacters[i].charid = NULL;
eveCharacters[i].skillname = NULL;
eveCharacters[i].time = NULL;
eveCharacters[i].charid = nullptr;
eveCharacters[i].skillname = nullptr;
eveCharacters[i].time = nullptr;
eveCharacters[i].level = 0;
eveCharacters[i].skill = 0;
eveCharacters[i].delay = 0;
@ -210,7 +210,7 @@ static int isCacheValid(struct tm cached) {
// struct timeval tv;
// struct timezone tz;
double offset = 0;
time_t now = time(NULL);
time_t now = time(nullptr);
time_t cache = 0;
double diff = 0;
@ -232,7 +232,7 @@ static char *formatTime(struct tm *ends) {
// struct timeval tv;
// struct timezone tz;
double offset = 0;
time_t now = time(NULL);
time_t now = time(nullptr);
time_t tEnds = 0;
long lin = 0;
long lie = 0;
@ -279,20 +279,20 @@ static void writeSkilltree(char *content, const char *filename) {
static char *getSkillname(const char *file, int skillid) {
char *skilltree;
char *skill = NULL;
char *skill = nullptr;
xmlNodePtr n;
xmlDocPtr doc = 0;
xmlNodePtr root = 0;
skilltree = getXmlFromAPI(NULL, NULL, NULL, EVEURL_SKILLTREE);
skilltree = getXmlFromAPI(nullptr, NULL, NULL, EVEURL_SKILLTREE);
if (skilltree) {
writeSkilltree(skilltree, file);
free(skilltree);
}
doc = xmlReadFile(file, NULL, XML_PARSE_RECOVER);
doc = xmlReadFile(file, nullptr, XML_PARSE_RECOVER);
unlink(file);
if (!doc) return NULL;
if (!doc) return nullptr;
root = xmlDocGetRootElement(doc);
@ -307,10 +307,10 @@ static char *getSkillname(const char *file, int skillid) {
for (r = q->children; r; r = r->next) {
xmlElementPtr ele = (xmlElementPtr)r;
xmlAttrPtr attr = (xmlAttrPtr)ele->attributes;
char *mySkill = NULL;
char *mySkill = nullptr;
int id;
while (attr != NULL) {
while (attr != nullptr) {
if (!strcasecmp((const char *)attr->name, "typeName")) {
mySkill = strdup((const char *)attr->children->content);
} else if (!strcasecmp((const char *)attr->name, "typeID")) {
@ -337,7 +337,7 @@ END:
}
static char *eve(char *apiKeyID, char *apiVCode, char *charid) {
Character *chr = NULL;
Character *chr = nullptr;
char skillfile[] = "/tmp/.cesfXXXXXX";
int i = 0;
char *output = 0;
@ -349,7 +349,7 @@ static char *eve(char *apiKeyID, char *apiVCode, char *charid) {
int tmp_fd, old_umask;
for (i = 0; i < num_chars; i++) {
if (eveCharacters[i].charid != NULL) {
if (eveCharacters[i].charid != nullptr) {
if (strcasecmp(eveCharacters[i].charid, charid) == 0) {
chr = &eveCharacters[i];
break;
@ -358,7 +358,7 @@ static char *eve(char *apiKeyID, char *apiVCode, char *charid) {
}
if (!chr) {
if (num_chars == MAXCHARS - 1) return NULL;
if (num_chars == MAXCHARS - 1) return nullptr;
chr = &eveCharacters[num_chars];
memset(chr, 0, sizeof(Character));
chr->charid = strdup(charid);
@ -366,7 +366,7 @@ static char *eve(char *apiKeyID, char *apiVCode, char *charid) {
}
if (chr->delay > 0) {
now = time(NULL);
now = time(nullptr);
if (now < chr->delay) {
output = strdup("Server error");
return output;
@ -386,9 +386,9 @@ static char *eve(char *apiKeyID, char *apiVCode, char *charid) {
}
} else {
content = getXmlFromAPI(apiKeyID, apiVCode, charid, EVEURL_TRAINING);
if (content == NULL) {
if (content == nullptr) {
error = strdup("Server error");
now = time(NULL);
now = time(nullptr);
now += (time_t)1800;
chr->delay = now;
return error;

View File

@ -28,11 +28,12 @@
*/
#include "exec.h"
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <cmath>
#include <cstdio>
#include <mutex>
#include "conky.h"
#include "core.h"
@ -42,9 +43,9 @@
#include "update-cb.hh"
struct execi_data {
float interval;
char *cmd;
execi_data() : interval(0), cmd(0) {}
float interval{0};
char *cmd{nullptr};
execi_data() = default;
};
// our own implementation of popen, the difference : the value of 'childpid'
@ -59,28 +60,29 @@ static FILE *pid_popen(const char *command, const char *mode, pid_t *child) {
// create a pipe and close the ends if mode is something illegal
if (strcmp(mode, "r") == 0) {
if (pipe(ends) != 0) {
return NULL;
return nullptr;
}
parentend = ends[0];
childend = ends[1];
} else if (strcmp(mode, "w") == 0) {
if (pipe(ends) != 0) {
return NULL;
return nullptr;
}
parentend = ends[1];
childend = ends[0];
} else {
return NULL;
return nullptr;
}
*child = fork();
if (*child == -1) {
close(parentend);
close(childend);
return NULL;
} else if (*child > 0) {
return nullptr;
}
if (*child > 0) {
close(childend);
waitpid(*child, NULL, 0);
waitpid(*child, nullptr, 0);
} else {
// don't read from both stdin and pipe or write to both stdout and pipe
if (childend == ends[0]) {
@ -91,10 +93,12 @@ static FILE *pid_popen(const char *command, const char *mode, pid_t *child) {
close(parentend);
// by dupping childend, the returned fd will have close-on-exec turned off
if (dup(childend) == -1) perror("dup()");
if (fcntl(childend, F_DUPFD_CLOEXEC) == -1) {
perror("dup()");
}
close(childend);
execl("/bin/sh", "sh", "-c", command, (char *)NULL);
execl("/bin/sh", "sh", "-c", command, (char *)nullptr);
_exit(EXIT_FAILURE); // child should die here, (normally execl will take
// care of this but it can fail)
}
@ -119,17 +123,20 @@ void exec_cb::work() {
std::shared_ptr<FILE> fp;
char b[0x1000];
if (FILE *t = pid_popen(std::get<0>(tuple).c_str(), "r", &childpid))
if (FILE *t = pid_popen(std::get<0>(tuple).c_str(), "r", &childpid)) {
fp.reset(t, fclose);
else
} else {
return;
}
while (!feof(fp.get()) && !ferror(fp.get())) {
while ((feof(fp.get()) == 0) && (ferror(fp.get()) == 0)) {
int length = fread(b, 1, sizeof b, fp.get());
buf.append(b, length);
}
if (*buf.rbegin() == '\n') buf.resize(buf.size() - 1);
if (*buf.rbegin() == '\n') {
buf.resize(buf.size() - 1);
}
std::lock_guard<std::mutex> l(result_mutex);
result = buf;
@ -145,12 +152,14 @@ static void remove_deleted_chars(char *string) {
if (i != 0) {
strcpy(&(string[i - 1]), &(string[i + 1]));
i--;
} else
} else {
strcpy(
&(string[i]),
&(string[i + 1])); // necessary for ^H's at the start of a string
} else
}
} else {
i++;
}
}
}
@ -191,7 +200,7 @@ static inline double get_barnum(const char *buf) {
*/
void fill_p(const char *buffer, struct text_object *obj, char *p,
int p_max_size) {
if (obj->parse == true) {
if (obj->parse) {
evaluate(buffer, p, p_max_size);
} else {
snprintf(p, p_max_size, "%s", buffer);
@ -216,7 +225,7 @@ void scan_exec_arg(struct text_object *obj, const char *arg,
struct execi_data *ed;
/* in case we have an execi object, we need to parse out the interval */
if (execflag & EF_EXECI) {
if ((execflag & EF_EXECI) != 0u) {
ed = new execi_data;
int n;
@ -224,7 +233,7 @@ void scan_exec_arg(struct text_object *obj, const char *arg,
if (sscanf(arg, "%f %n", &ed->interval, &n) <= 0) {
NORM_ERR("missing execi interval: ${execi* <interval> command}");
delete ed;
ed = NULL;
ed = nullptr;
return;
}
@ -233,14 +242,14 @@ void scan_exec_arg(struct text_object *obj, const char *arg,
}
/* parse any special options for the graphical exec types */
if (execflag & EF_BAR) {
if ((execflag & EF_BAR) != 0u) {
cmd = scan_bar(obj, cmd, 100);
#ifdef BUILD_X11
} else if (execflag & EF_GAUGE) {
} else if ((execflag & EF_GAUGE) != 0u) {
cmd = scan_gauge(obj, cmd, 100);
} else if (execflag & EF_GRAPH) {
} else if ((execflag & EF_GRAPH) != 0u) {
cmd = scan_graph(obj, cmd, 100);
if (!cmd) {
if (cmd == nullptr) {
NORM_ERR("error parsing arguments to execgraph object");
}
#endif /* BUILD_X11 */
@ -248,10 +257,11 @@ void scan_exec_arg(struct text_object *obj, const char *arg,
/* finally, store the resulting command, or an empty string if something went
* wrong */
if (execflag & EF_EXEC) {
obj->data.s = strndup(cmd ? cmd : "", text_buffer_size.get(*state));
} else if (execflag & EF_EXECI) {
ed->cmd = strndup(cmd ? cmd : "", text_buffer_size.get(*state));
if ((execflag & EF_EXEC) != 0u) {
obj->data.s =
strndup(cmd != nullptr ? cmd : "", text_buffer_size.get(*state));
} else if ((execflag & EF_EXECI) != 0u) {
ed->cmd = strndup(cmd != nullptr ? cmd : "", text_buffer_size.get(*state));
obj->data.opaque = ed;
}
}
@ -262,7 +272,7 @@ void scan_exec_arg(struct text_object *obj, const char *arg,
* @param[out] obj stores the callback handle
*/
void register_exec(struct text_object *obj) {
if (obj->data.s && obj->data.s[0]) {
if ((obj->data.s != nullptr) && (obj->data.s[0] != 0)) {
obj->exec_handle = new conky::callback_handle<exec_cb>(
conky::register_cb<exec_cb>(1, true, obj->data.s));
} else {
@ -279,9 +289,9 @@ void register_exec(struct text_object *obj) {
* @param[out] obj stores the callback handle
*/
void register_execi(struct text_object *obj) {
struct execi_data *ed = (struct execi_data *)obj->data.opaque;
auto *ed = static_cast<struct execi_data *>(obj->data.opaque);
if (ed && ed->cmd && ed->cmd[0]) {
if ((ed != nullptr) && (ed->cmd != nullptr) && (ed->cmd[0] != 0)) {
uint32_t period =
std::max(lround(ed->interval / active_update_interval()), 1l);
obj->exec_handle = new conky::callback_handle<exec_cb>(
@ -299,7 +309,7 @@ void register_execi(struct text_object *obj) {
* @param[in] p_max_size the maximum size of p...
*/
void print_exec(struct text_object *obj, char *p, int p_max_size) {
if (obj->exec_handle) {
if (obj->exec_handle != nullptr) {
fill_p((*obj->exec_handle)->get_result_copy().c_str(), obj, p, p_max_size);
}
}
@ -311,11 +321,10 @@ void print_exec(struct text_object *obj, char *p, int p_max_size) {
* @return a value between 0.0 and 100.0
*/
double execbarval(struct text_object *obj) {
if (obj->exec_handle) {
if (obj->exec_handle != nullptr) {
return get_barnum((*obj->exec_handle)->get_result_copy().c_str());
} else {
return 0.0;
}
return 0.0;
}
/**
@ -326,7 +335,7 @@ double execbarval(struct text_object *obj) {
void free_exec(struct text_object *obj) {
free_and_zero(obj->data.s);
delete obj->exec_handle;
obj->exec_handle = NULL;
obj->exec_handle = nullptr;
}
/**
@ -335,16 +344,18 @@ void free_exec(struct text_object *obj) {
* @param[in] obj holds the data that we need to free up
*/
void free_execi(struct text_object *obj) {
struct execi_data *ed = (struct execi_data *)obj->data.opaque;
auto *ed = static_cast<struct execi_data *>(obj->data.opaque);
/* if ed is NULL, there is nothing to do */
if (!ed) return;
/* if ed is nullptr, there is nothing to do */
if (ed == nullptr) {
return;
}
delete obj->exec_handle;
obj->exec_handle = NULL;
obj->exec_handle = nullptr;
free_and_zero(ed->cmd);
delete ed;
ed = NULL;
obj->data.opaque = NULL;
ed = nullptr;
obj->data.opaque = nullptr;
}

View File

@ -40,7 +40,9 @@ void font_setting::lua_setter(lua::state &l, bool init) {
Base::lua_setter(l, init);
if (init && out_to_x.get(*state)) {
if (fonts.size() == 0) fonts.resize(1);
if (fonts.empty()) {
fonts.resize(1);
}
fonts[0].name = do_convert(l, -1).first;
}
@ -52,10 +54,10 @@ font_setting font;
#ifdef BUILD_XFT
namespace {
class xftalpha_setting : public conky::simple_config_setting<float> {
typedef conky::simple_config_setting<float> Base;
using Base = conky::simple_config_setting<float>;
protected:
virtual void lua_setter(lua::state &l, bool init) {
void lua_setter(lua::state &l, bool init) override {
lua::stack_sentry s(l, -2);
Base::lua_setter(l, init);
@ -75,24 +77,26 @@ xftalpha_setting xftalpha;
} // namespace
#endif /* BUILD_XFT */
void set_font(void) {
void set_font() {
#ifdef BUILD_XFT
if (use_xft.get(*state)) return;
if (use_xft.get(*state)) {
return;
}
#endif /* BUILD_XFT */
if (fonts[selected_font].font) {
if (fonts[selected_font].font != nullptr) {
XSetFont(display, window.gc, fonts[selected_font].font->fid);
}
}
void setup_fonts(void) {
void setup_fonts() {
if (not out_to_x.get(*state)) {
return;
}
#ifdef BUILD_XFT
if (use_xft.get(*state)) {
if (window.xftdraw) {
if (window.xftdraw != nullptr) {
XftDrawDestroy(window.xftdraw);
window.xftdraw = 0;
window.xftdraw = nullptr;
}
window.xftdraw = XftDrawCreate(display, window.drawable, window.visual,
window.colourmap);
@ -105,7 +109,7 @@ int add_font(const char *data_in) {
if (not out_to_x.get(*state)) {
return 0;
}
fonts.push_back(font_list());
fonts.emplace_back();
fonts.rbegin()->name = data_in;
return fonts.size() - 1;
@ -115,7 +119,7 @@ void free_fonts(bool utf8) {
if (not out_to_x.get(*state)) {
return;
}
for (size_t i = 0; i < fonts.size(); i++) {
for (auto &font : fonts) {
#ifdef BUILD_XFT
if (use_xft.get(*state)) {
/*
@ -128,71 +132,73 @@ void free_fonts(bool utf8) {
} else
#endif /* BUILD_XFT */
{
if (fonts[i].font) {
XFreeFont(display, fonts[i].font);
if (font.font != nullptr) {
XFreeFont(display, font.font);
}
if (utf8 && fonts[i].fontset) {
XFreeFontSet(display, fonts[i].fontset);
if (utf8 && (font.fontset != nullptr)) {
XFreeFontSet(display, font.fontset);
}
}
}
fonts.clear();
selected_font = 0;
#ifdef BUILD_XFT
if (window.xftdraw) {
if (window.xftdraw != nullptr) {
XftDrawDestroy(window.xftdraw);
window.xftdraw = 0;
window.xftdraw = nullptr;
}
#endif /* BUILD_XFT */
}
void load_fonts(bool utf8) {
if (not out_to_x.get(*state)) return;
for (size_t i = 0; i < fonts.size(); i++) {
if (not out_to_x.get(*state)) {
return;
}
for (auto &font : fonts) {
#ifdef BUILD_XFT
/* load Xft font */
if (use_xft.get(*state)) {
if (not fonts[i].xftfont)
fonts[i].xftfont =
XftFontOpenName(display, screen, fonts[i].name.c_str());
if (font.xftfont == nullptr) {
font.xftfont = XftFontOpenName(display, screen, font.name.c_str());
}
if (fonts[i].xftfont) {
if (font.xftfont != nullptr) {
continue;
}
NORM_ERR("can't load Xft font '%s'", fonts[i].name.c_str());
if ((fonts[i].xftfont = XftFontOpenName(display, screen, "courier-12")) !=
NULL) {
NORM_ERR("can't load Xft font '%s'", font.name.c_str());
if ((font.xftfont = XftFontOpenName(display, screen, "courier-12")) !=
nullptr) {
continue;
}
CRIT_ERR(NULL, NULL, "can't load Xft font '%s'", "courier-12");
CRIT_ERR(nullptr, nullptr, "can't load Xft font '%s'", "courier-12");
continue;
}
#endif
if (utf8 && fonts[i].fontset == NULL) {
if (utf8 && font.fontset == nullptr) {
char **missing;
int missingnum;
char *missingdrawn;
fonts[i].fontset = XCreateFontSet(display, fonts[i].name.c_str(),
&missing, &missingnum, &missingdrawn);
font.fontset = XCreateFontSet(display, font.name.c_str(), &missing,
&missingnum, &missingdrawn);
XFreeStringList(missing);
if (fonts[i].fontset == NULL) {
NORM_ERR("can't load font '%s'", fonts[i].name.c_str());
fonts[i].fontset = XCreateFontSet(display, "fixed", &missing,
&missingnum, &missingdrawn);
if (fonts[i].fontset == NULL) {
CRIT_ERR(NULL, NULL, "can't load font '%s'", "fixed");
if (font.fontset == nullptr) {
NORM_ERR("can't load font '%s'", font.name.c_str());
font.fontset = XCreateFontSet(display, "fixed", &missing, &missingnum,
&missingdrawn);
if (font.fontset == nullptr) {
CRIT_ERR(nullptr, nullptr, "can't load font '%s'", "fixed");
}
}
}
/* load normal font */
if (!fonts[i].font && (fonts[i].font = XLoadQueryFont(
display, fonts[i].name.c_str())) == NULL) {
NORM_ERR("can't load font '%s'", fonts[i].name.c_str());
if ((fonts[i].font = XLoadQueryFont(display, "fixed")) == NULL) {
CRIT_ERR(NULL, NULL, "can't load font '%s'", "fixed");
if ((font.font == nullptr) &&
(font.font = XLoadQueryFont(display, font.name.c_str())) == nullptr) {
NORM_ERR("can't load font '%s'", font.name.c_str());
if ((font.font = XLoadQueryFont(display, "fixed")) == nullptr) {
CRIT_ERR(nullptr, nullptr, "can't load font '%s'", "fixed");
}
}
}

View File

@ -47,11 +47,11 @@ struct font_list {
font_list()
: name(),
font(NULL),
fontset(NULL)
font(nullptr),
fontset(nullptr)
#ifdef BUILD_XFT
,
xftfont(NULL),
xftfont(nullptr),
font_alpha(0xffff)
#endif
{

View File

@ -82,7 +82,7 @@ static short cpu_setup = 0;
static int getsysctl(const char *name, void *ptr, size_t len) {
size_t nlen = len;
if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
if (sysctlbyname(name, ptr, &nlen, nullptr, 0) == -1) {
return -1;
}
@ -93,7 +93,7 @@ static int getsysctl(const char *name, void *ptr, size_t len) {
return 0;
}
struct ifmibdata *data = NULL;
struct ifmibdata *data = nullptr;
size_t len = 0;
static int swapmode(unsigned long *retavail, unsigned long *retfree) {
@ -127,7 +127,7 @@ int update_uptime(void) {
time_t now;
size_t size = sizeof(boottime);
if ((sysctl(mib, 2, &boottime, &size, NULL, 0) != -1) &&
if ((sysctl(mib, 2, &boottime, &size, nullptr, 0) != -1) &&
(boottime.tv_sec != 0)) {
time(&now);
info.uptime = now - boottime.tv_sec;
@ -209,7 +209,7 @@ int update_net_stats(void) {
}
for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
ns = get_net_stat((const char *)ifa->ifa_name, NULL, NULL);
ns = get_net_stat((const char *)ifa->ifa_name, nullptr, NULL);
if (ifa->ifa_flags & IFF_UP) {
struct ifaddrs *iftmp;
@ -223,7 +223,7 @@ int update_net_stats(void) {
}
for (iftmp = ifa->ifa_next;
iftmp != NULL && strcmp(ifa->ifa_name, iftmp->ifa_name) == 0;
iftmp != nullptr && strcmp(ifa->ifa_name, iftmp->ifa_name) == 0;
iftmp = iftmp->ifa_next) {
if (iftmp->ifa_addr->sa_family == AF_INET) {
memcpy(&(ns->addr), iftmp->ifa_addr, iftmp->ifa_addr->sa_len);
@ -301,8 +301,8 @@ void get_cpu_count(void) {
}
info.cpu_usage = (float *)malloc((info.cpu_count + 1) * sizeof(float));
if (info.cpu_usage == NULL) {
CRIT_ERR(NULL, NULL, "malloc");
if (info.cpu_usage == nullptr) {
CRIT_ERR(nullptr, NULL, "malloc");
}
}
@ -314,9 +314,9 @@ struct cpu_info {
int update_cpu_usage(void) {
int i, j = 0;
long used, total;
long *cp_time = NULL;
long *cp_time = nullptr;
size_t cp_len;
static struct cpu_info *cpu = NULL;
static struct cpu_info *cpu = nullptr;
unsigned int malloc_cpu_size = 0;
extern void *global_cpu;
@ -337,7 +337,7 @@ int update_cpu_usage(void) {
cp_len = CPUSTATES * sizeof(long);
cp_time = (long int *)malloc(cp_len);
if (sysctlbyname("kern.cp_time", cp_time, &cp_len, NULL, 0) < 0) {
if (sysctlbyname("kern.cp_time", cp_time, &cp_len, nullptr, 0) < 0) {
fprintf(stderr, "Cannot get kern.cp_time\n");
}
@ -364,7 +364,7 @@ int update_cpu_usage(void) {
/* on e.g. i386 SMP we may have more values than actual cpus; this will just
* drop extra values */
if (sysctlbyname("kern.cp_times", cp_time, &cp_len, NULL, 0) < 0 &&
if (sysctlbyname("kern.cp_times", cp_time, &cp_len, nullptr, 0) < 0 &&
errno != ENOMEM) {
fprintf(stderr, "Cannot get kern.cp_times\n");
}
@ -489,7 +489,7 @@ static int check_bat(const char *bat) {
int get_battery_perct(const char *bat) {
int batcapacity;
get_battery_stats(NULL, &batcapacity, NULL, NULL);
get_battery_stats(nullptr, &batcapacity, NULL, NULL);
return batcapacity;
}
@ -545,7 +545,7 @@ char get_freq(char *p_client_buffer, size_t client_buffer_size,
}
freq_sysctl = (char *)calloc(16, sizeof(char));
if (freq_sysctl == NULL) {
if (freq_sysctl == nullptr) {
exit(-1);
}
@ -578,7 +578,7 @@ void update_wifi_stats(void)
}
for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
ns = get_net_stat((const char *) ifa->ifa_name, NULL, NULL);
ns = get_net_stat((const char *) ifa->ifa_name, nullptr, NULL);
s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
@ -619,7 +619,7 @@ cleanup:
int update_diskio(void) {
int devs_count, num_selected, num_selections, dn;
struct device_selection *dev_select = NULL;
struct device_selection *dev_select = nullptr;
long select_generation;
static struct statinfo statinfo_cur;
char device_name[text_buffer_size.get(*state)];
@ -631,7 +631,7 @@ int update_diskio(void) {
statinfo_cur.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo));
stats.current = stats.current_read = stats.current_write = 0;
if (devstat_getdevs(NULL, &statinfo_cur) < 0) {
if (devstat_getdevs(nullptr, &statinfo_cur) < 0) {
free(statinfo_cur.dinfo);
return 0;
}
@ -639,7 +639,7 @@ int update_diskio(void) {
devs_count = statinfo_cur.dinfo->numdevs;
if (devstat_selectdevs(&dev_select, &num_selected, &num_selections,
&select_generation, statinfo_cur.dinfo->generation,
statinfo_cur.dinfo->devices, devs_count, NULL, 0, NULL,
statinfo_cur.dinfo->devices, devs_count, nullptr, 0, NULL,
0, DS_SELECT_ONLY, MAXSHOWDEVS, 1) >= 0) {
for (dn = 0; dn < devs_count; dn++) {
int di;
@ -680,7 +680,7 @@ void get_top_info(void) {
p = kvm_getprocs(kd, KERN_PROC_PROC, 0, &n_processes);
for (i = 0; i < n_processes; i++) {
if (!((p[i].ki_flag & P_SYSTEM)) && p[i].ki_comm != NULL) {
if (!((p[i].ki_flag & P_SYSTEM)) && p[i].ki_comm != nullptr) {
proc = get_process(p[i].ki_pid);
proc->time_stamp = g_time;

View File

@ -28,11 +28,11 @@
*/
#include "fs.h"
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <cctype>
#include <cerrno>
#include "conky.h"
#include "logging.h"
#include "specials.h"
@ -72,14 +72,16 @@ static void update_fs_stat(struct fs_stat *fs);
void get_fs_type(const char *path, char *result);
int update_fs_stats(void) {
int update_fs_stats() {
unsigned i;
static double last_fs_update = 0.0;
if (current_update_time - last_fs_update < 13) return 0;
if (current_update_time - last_fs_update < 13) {
return 0;
}
for (i = 0; i < MAX_FS_STATS; ++i) {
if (fs_stats[i].set) {
if (fs_stats[i].set != 0) {
update_fs_stat(&fs_stats[i]);
}
}
@ -87,7 +89,7 @@ int update_fs_stats(void) {
return 0;
}
void clear_fs_stats(void) {
void clear_fs_stats() {
unsigned i;
for (i = 0; i < MAX_FS_STATS; ++i) {
memset(&fs_stats[i], 0, sizeof(struct fs_stat));
@ -95,12 +97,12 @@ void clear_fs_stats(void) {
}
struct fs_stat *prepare_fs_stat(const char *s) {
struct fs_stat *next = 0;
struct fs_stat *next = nullptr;
unsigned i;
/* lookup existing or get new */
for (i = 0; i < MAX_FS_STATS; ++i) {
if (fs_stats[i].set) {
if (fs_stats[i].set != 0) {
if (strncmp(fs_stats[i].path, s, DEFAULT_TEXT_BUFFER_SIZE) == 0) {
return &fs_stats[i];
}
@ -109,9 +111,9 @@ struct fs_stat *prepare_fs_stat(const char *s) {
}
}
/* new path */
if (!next) {
if (next == nullptr) {
NORM_ERR("too many fs stats");
return 0;
return nullptr;
}
strncpy(next->path, s, DEFAULT_TEXT_BUFFER_SIZE);
next->set = 1;
@ -129,13 +131,13 @@ static void update_fs_stat(struct fs_stat *fs) {
fs->free = (long long)s.f_bfree * s.f_frsize;
(void)strncpy(fs->type, s.f_basetype, sizeof(fs->type));
#else
struct statfs64 s;
struct statfs64 s {};
if (statfs64(fs->path, &s) == 0) {
fs->size = (long long)s.f_blocks * s.f_bsize;
fs->size = static_cast<long long>(s.f_blocks) * s.f_bsize;
/* bfree (root) or bavail (non-roots) ? */
fs->avail = (long long)s.f_bavail * s.f_bsize;
fs->free = (long long)s.f_bfree * s.f_bsize;
fs->avail = static_cast<long long>(s.f_bavail) * s.f_bsize;
fs->free = static_cast<long long>(s.f_bfree) * s.f_bsize;
get_fs_type(fs->path, fs->type);
#endif
} else {
@ -152,7 +154,7 @@ void get_fs_type(const char *path, char *result) {
defined(__OpenBSD__) || defined(__DragonFly__) || defined(__HAIKU__) || \
(defined(__APPLE__) && defined(__MACH__))
struct statfs64 s;
struct statfs64 s {};
if (statfs64(path, &s) == 0) {
strncpy(result, s.f_fstypename, DEFAULT_TEXT_BUFFER_SIZE);
} else {
@ -169,7 +171,7 @@ void get_fs_type(const char *path, char *result) {
int match;
char *slash;
if (mtab == NULL) {
if (mtab == nullptr) {
NORM_ERR("setmntent /proc/mounts: %s", strerror(errno));
strncpy(result, "unknown", DEFAULT_TEXT_BUFFER_SIZE);
return;
@ -185,13 +187,13 @@ void get_fs_type(const char *path, char *result) {
if (!match) break;
fseek(mtab, 0, SEEK_SET);
slash = strrchr(search_path, '/');
if (slash == NULL) CRIT_ERR(NULL, NULL, "invalid path '%s'", path);
if (slash == nullptr) CRIT_ERR(NULL, NULL, "invalid path '%s'", path);
if (strlen(slash) == 1) /* trailing slash */
*(slash) = '\0';
else if (strlen(slash) > 1)
*(slash + 1) = '\0';
else
CRIT_ERR(NULL, NULL, "found a crack in the matrix!");
CRIT_ERR(nullptr, NULL, "found a crack in the matrix!");
} while (strlen(search_path) > 0);
free(search_path);
@ -208,8 +210,8 @@ void get_fs_type(const char *path, char *result) {
void init_fs_bar(struct text_object *obj, const char *arg) {
arg = scan_bar(obj, arg, 1);
if (arg) {
while (isspace(*arg)) {
if (arg != nullptr) {
while (isspace(*arg) != 0) {
arg++;
}
if (*arg == '\0') {
@ -222,14 +224,15 @@ void init_fs_bar(struct text_object *obj, const char *arg) {
}
static double get_fs_perc(struct text_object *obj, bool get_free) {
struct fs_stat *fs = static_cast<struct fs_stat *>(obj->data.opaque);
auto *fs = static_cast<struct fs_stat *>(obj->data.opaque);
double ret = 0.0;
if (fs && fs->size) {
if (get_free)
if ((fs != nullptr) && (fs->size != 0)) {
if (get_free) {
ret = fs->avail;
else
} else {
ret = fs->size - fs->free;
}
ret /= fs->size;
}
@ -243,7 +246,7 @@ double fs_free_barval(struct text_object *obj) {
}
void init_fs(struct text_object *obj, const char *arg) {
obj->data.opaque = prepare_fs_stat(arg ? arg : "/");
obj->data.opaque = prepare_fs_stat(arg != nullptr ? arg : "/");
}
uint8_t fs_free_percentage(struct text_object *obj) {
@ -265,7 +268,9 @@ HUMAN_PRINT_FS_GENERATOR(size, fs->size)
HUMAN_PRINT_FS_GENERATOR(used, fs->size - fs->free)
void print_fs_type(struct text_object *obj, char *p, int p_max_size) {
struct fs_stat *fs = (struct fs_stat *)obj->data.opaque;
auto *fs = static_cast<struct fs_stat *>(obj->data.opaque);
if (fs) snprintf(p, p_max_size, "%s", fs->type);
if (fs != nullptr) {
snprintf(p, p_max_size, "%s", fs->type);
}
}

View File

@ -58,7 +58,7 @@ void print_fs_used(struct text_object *, char *, int);
void print_fs_type(struct text_object *, char *, int);
int update_fs_stats(void);
struct fs_stat *prepare_fs_stat(const char *path);
struct fs_stat *prepare_fs_stat(const char *s);
void clear_fs_stats(void);
#endif /* _FS_H */

View File

@ -96,15 +96,15 @@ void get_cpu_count(void) {
info.cpu_count = si.cpu_count;
info.cpu_usage = (float *)malloc((info.cpu_count + 1) * sizeof(float));
if (info.cpu_usage == NULL) {
CRIT_ERR(NULL, NULL, "malloc");
if (info.cpu_usage == nullptr) {
CRIT_ERR(nullptr, NULL, "malloc");
}
}
int update_cpu_usage() {
// TODO
static bigtime_t prev = 0;
static cpu_info *prev_cpuinfo = NULL;
static cpu_info *prev_cpuinfo = nullptr;
bigtime_t now;
cpu_info *cpuinfo;
@ -118,8 +118,8 @@ int update_cpu_usage() {
if (!prev_cpuinfo) {
prev_cpuinfo = (cpu_info *)malloc(malloc_cpu_size);
if (prev_cpuinfo == NULL) {
CRIT_ERR(NULL, NULL, "malloc");
if (prev_cpuinfo == nullptr) {
CRIT_ERR(nullptr, NULL, "malloc");
}
memset(prev_cpuinfo, 0, malloc_cpu_size);
}
@ -127,8 +127,8 @@ int update_cpu_usage() {
cpuinfo = (cpu_info *)malloc(malloc_cpu_size);
memset(cpuinfo, 0, malloc_cpu_size);
if (cpuinfo == NULL) {
CRIT_ERR(NULL, NULL, "malloc");
if (cpuinfo == nullptr) {
CRIT_ERR(nullptr, NULL, "malloc");
}
now = system_time();
@ -165,7 +165,7 @@ int get_battery_perct(const char *bat) {
/*
int batcapacity;
get_battery_stats(NULL, &batcapacity, NULL, NULL);
get_battery_stats(nullptr, &batcapacity, NULL, NULL);
return batcapacity;
*/
// TODO

View File

@ -67,7 +67,7 @@ static void free_hddtemp_info(void) {
DBGP("free_hddtemp_info() called");
if (!hdd_info_head.next) return;
__free_hddtemp_info(hdd_info_head.next);
hdd_info_head.next = NULL;
hdd_info_head.next = nullptr;
}
static void add_hddtemp_info(char *dev, short temp, char unit) {
@ -85,7 +85,7 @@ static void add_hddtemp_info(char *dev, short temp, char unit) {
static char *fetch_hddtemp_output(void) {
int sockfd;
char *buf = NULL;
char *buf = nullptr;
int buflen, offset = 0, rlen;
struct addrinfo hints, *result, *rp;
int i;
@ -97,7 +97,7 @@ static char *fetch_hddtemp_output(void) {
if ((i = getaddrinfo(hddtemp_host.get(*state).c_str(),
hddtemp_port.get(*state).c_str(), &hints, &result))) {
NORM_ERR("getaddrinfo(): %s", gai_strerror(i));
return NULL;
return nullptr;
}
for (rp = result; rp; rp = rp->ai_next) {
@ -131,7 +131,7 @@ GET_OUT:
}
/* this is an iterator:
* set line to NULL in consecutive calls to get the next field
* set line to nullptr in consecutive calls to get the next field
* note that exhausing iteration is assumed - otherwise *saveptr
* is not being freed!
*/
@ -195,7 +195,7 @@ int update_hddtemp(void) {
}
do {
add_hddtemp_info(dev, val, unit);
} while (!read_hdd_val(NULL, &dev, &val, &unit, &saveptr));
} while (!read_hdd_val(nullptr, &dev, &val, &unit, &saveptr));
free(data);
return 0;
}

View File

@ -52,21 +52,21 @@ struct _i8k {
/* FIXME: there should be an ioctl interface to request specific data */
#define PROC_I8K "/proc/i8k"
#define I8K_DELIM " "
static char *i8k_procbuf = NULL;
static char *i8k_procbuf = nullptr;
int update_i8k(void) {
FILE *fp;
if (!i8k_procbuf) {
i8k_procbuf = (char *)malloc(128 * sizeof(char));
}
if ((fp = fopen(PROC_I8K, "r")) == NULL) {
if ((fp = fopen(PROC_I8K, "r")) == nullptr) {
free_and_zero(i8k_procbuf);
/*THREAD_CRIT_ERR(NULL, NULL, "/proc/i8k doesn't exist! use insmod to make
/*THREAD_CRIT_ERR(nullptr, NULL, "/proc/i8k doesn't exist! use insmod to make
sure the kernel " "driver is loaded...");*/
NORM_ERR(
"/proc/i8k doesn't exist! use insmod to make sure the kernel driver is "
"loaded...");
clean_up_without_threads(NULL, NULL);
clean_up_without_threads(nullptr, NULL);
return 1;
}
@ -80,15 +80,15 @@ int update_i8k(void) {
DBGP("read `%s' from /proc/i8k\n", i8k_procbuf);
i8k.version = strtok(&i8k_procbuf[0], I8K_DELIM);
i8k.bios = strtok(NULL, I8K_DELIM);
i8k.serial = strtok(NULL, I8K_DELIM);
i8k.cpu_temp = strtok(NULL, I8K_DELIM);
i8k.left_fan_status = strtok(NULL, I8K_DELIM);
i8k.right_fan_status = strtok(NULL, I8K_DELIM);
i8k.left_fan_rpm = strtok(NULL, I8K_DELIM);
i8k.right_fan_rpm = strtok(NULL, I8K_DELIM);
i8k.ac_status = strtok(NULL, I8K_DELIM);
i8k.buttons_status = strtok(NULL, I8K_DELIM);
i8k.bios = strtok(nullptr, I8K_DELIM);
i8k.serial = strtok(nullptr, I8K_DELIM);
i8k.cpu_temp = strtok(nullptr, I8K_DELIM);
i8k.left_fan_status = strtok(nullptr, I8K_DELIM);
i8k.right_fan_status = strtok(nullptr, I8K_DELIM);
i8k.left_fan_rpm = strtok(nullptr, I8K_DELIM);
i8k.right_fan_rpm = strtok(nullptr, I8K_DELIM);
i8k.ac_status = strtok(nullptr, I8K_DELIM);
i8k.buttons_status = strtok(nullptr, I8K_DELIM);
return 0;
}

View File

@ -86,11 +86,11 @@ void get_ibm_acpi_fan(struct text_object *obj, char *p, int p_max_size) {
snprintf(fan, 127, "%s/fan", IBM_ACPI_DIR);
fp = fopen(fan, "r");
if (fp != NULL) {
if (fp != nullptr) {
while (!feof(fp)) {
char line[256];
if (fgets(line, 255, fp) == NULL) {
if (fgets(line, 255, fp) == nullptr) {
break;
}
if (sscanf(line, "speed: %u", &speed)) {
@ -98,7 +98,7 @@ void get_ibm_acpi_fan(struct text_object *obj, char *p, int p_max_size) {
}
}
} else {
CRIT_ERR(NULL, NULL,
CRIT_ERR(nullptr, NULL,
"can't open '%s': %s\nYou are not using the IBM ACPI. Remove "
"ibm* from your " PACKAGE_NAME " config file.",
fan, strerror(errno));
@ -136,11 +136,11 @@ int get_ibm_acpi_temps(void) {
snprintf(thermal, 127, "%s/thermal", IBM_ACPI_DIR);
fp = fopen(thermal, "r");
if (fp != NULL) {
if (fp != nullptr) {
while (!feof(fp)) {
char line[256];
if (fgets(line, 255, fp) == NULL) {
if (fgets(line, 255, fp) == nullptr) {
break;
}
if (sscanf(line, "temperatures: %d %d %d %d %d %d %d %d",
@ -151,7 +151,7 @@ int get_ibm_acpi_temps(void) {
}
}
} else {
CRIT_ERR(NULL, NULL,
CRIT_ERR(nullptr, NULL,
"can't open '%s': %s\nYou are not using the IBM ACPI. Remove "
"ibm* from your " PACKAGE_NAME " config file.",
thermal, strerror(errno));
@ -186,12 +186,12 @@ void get_ibm_acpi_volume(struct text_object *obj, char *p, int p_max_size) {
snprintf(volume, 127, "%s/volume", IBM_ACPI_DIR);
fp = fopen(volume, "r");
if (fp != NULL) {
if (fp != nullptr) {
while (!feof(fp)) {
char line[256];
unsigned int read_vol = -1;
if (fgets(line, 255, fp) == NULL) {
if (fgets(line, 255, fp) == nullptr) {
break;
}
if (sscanf(line, "level: %u", &read_vol)) {
@ -203,7 +203,7 @@ void get_ibm_acpi_volume(struct text_object *obj, char *p, int p_max_size) {
}
}
} else {
CRIT_ERR(NULL, NULL,
CRIT_ERR(nullptr, NULL,
"can't open '%s': %s\nYou are not using the IBM ACPI. Remove "
"ibm* from your " PACKAGE_NAME " config file.",
volume, strerror(errno));
@ -217,7 +217,7 @@ void get_ibm_acpi_volume(struct text_object *obj, char *p, int p_max_size) {
snprintf(p, p_max_size, "%d", vol);
}
/* static FILE *fp = NULL; */
/* static FILE *fp = nullptr; */
/* get LCD brightness on IBM/Lenovo laptops running the ibm acpi.
* /proc/acpi/ibm/brightness looks like this (3 lines):
@ -240,11 +240,11 @@ void get_ibm_acpi_brightness(struct text_object *obj, char *p, int p_max_size) {
snprintf(filename, 127, "%s/brightness", IBM_ACPI_DIR);
fp = fopen(filename, "r");
if (fp != NULL) {
if (fp != nullptr) {
while (!feof(fp)) {
char line[256];
if (fgets(line, 255, fp) == NULL) {
if (fgets(line, 255, fp) == nullptr) {
break;
}
if (sscanf(line, "level: %u", &brightness)) {
@ -252,7 +252,7 @@ void get_ibm_acpi_brightness(struct text_object *obj, char *p, int p_max_size) {
}
}
} else {
CRIT_ERR(NULL, NULL,
CRIT_ERR(nullptr, NULL,
"can't open '%s': %s\nYou are not using the IBM ACPI. Remove "
"ibm* from your " PACKAGE_NAME " config file.",
filename, strerror(errno));
@ -285,11 +285,11 @@ void get_ibm_acpi_thinklight(struct text_object *obj, char *p, int p_max_size) {
snprintf(filename, 127, "%s/light", IBM_ACPI_DIR);
fp = fopen(filename, "r");
if (fp != NULL) {
if (fp != nullptr) {
while (!feof(fp)) {
char line[256];
if (fgets(line, 255, fp) == NULL) {
if (fgets(line, 255, fp) == nullptr) {
break;
}
if (sscanf(line, "status: %s", thinklight)) {
@ -297,7 +297,7 @@ void get_ibm_acpi_thinklight(struct text_object *obj, char *p, int p_max_size) {
}
}
} else {
CRIT_ERR(NULL, NULL,
CRIT_ERR(nullptr, NULL,
"can't open '%s': %s\nYou are not using the IBM "
"ACPI. Remove ibm* from your " PACKAGE_NAME " config file.",
filename, strerror(errno));

View File

@ -50,7 +50,7 @@ struct ical_event *add_event(struct ical_event *listend,
start = icalcomponent_get_dtstart(new_ev);
if (icaltime_compare(
start, icaltime_from_timet_with_zone(time(NULL), 0, NULL)) <= 0) {
start, icaltime_from_timet_with_zone(time(nullptr), 0, NULL)) <= 0) {
icalproperty *rrule =
icalcomponent_get_first_property(new_ev, ICAL_RRULE_PROPERTY);
if (rrule) {
@ -59,7 +59,7 @@ struct ical_event *add_event(struct ical_event *listend,
icaltimetype nexttime = icalrecur_iterator_next(ritr);
while (!icaltime_is_null_time(nexttime)) {
if (icaltime_compare(nexttime, icaltime_from_timet_with_zone(
time(NULL), 0, NULL)) > 0) {
time(nullptr), 0, NULL)) > 0) {
start = nexttime;
break;
}
@ -67,7 +67,7 @@ struct ical_event *add_event(struct ical_event *listend,
}
icalrecur_iterator_free(ritr);
} else
return NULL;
return nullptr;
}
ev_new = (struct ical_event *)malloc(sizeof(struct ical_event));
memset(ev_new, 0, sizeof(struct ical_event));
@ -133,7 +133,7 @@ void parse_ical_args(struct text_object *obj, const char *arg,
NORM_ERR("No ical events available");
return;
}
ll_start = add_event(NULL, curc);
ll_start = add_event(nullptr, curc);
ll_end = ll_start;
while (1) {
curc = icalcomponent_get_next_component(allc, ICAL_VEVENT_COMPONENT);

View File

@ -45,11 +45,11 @@ static iconv_t **iconv_cd = 0;
int register_iconv(iconv_t *new_iconv) {
iconv_cd = (void ***)realloc(iconv_cd, sizeof(iconv_t *) * (iconv_count + 1));
if (!iconv_cd) {
CRIT_ERR(NULL, NULL, "Out of memory");
CRIT_ERR(nullptr, NULL, "Out of memory");
}
iconv_cd[iconv_count] = (void **)malloc(sizeof(iconv_t));
if (!iconv_cd[iconv_count]) {
CRIT_ERR(NULL, NULL, "Out of memory");
CRIT_ERR(nullptr, NULL, "Out of memory");
}
memcpy(iconv_cd[iconv_count], new_iconv, sizeof(iconv_t));
iconv_count++;
@ -91,7 +91,7 @@ void iconv_convert(size_t *a, char *buff_in, char *p, size_t p_max_size) {
strncpy(buff_in, p, p_max_size);
iconv(*iconv_cd[iconv_selected - 1], NULL, NULL, NULL, NULL);
iconv(*iconv_cd[iconv_selected - 1], nullptr, NULL, NULL, NULL);
while (dummy1 > 0) {
bytes =
iconv(*iconv_cd[iconv_selected - 1], &ptr, &dummy1, &outptr, &dummy2);

View File

@ -28,11 +28,11 @@
#include "text_object.h"
#include <Imlib2.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include "x11.h"
@ -69,7 +69,7 @@ void imlib_cache_size_setting::lua_setter(lua::state &l, bool init) {
Base::lua_setter(l, init);
if (init && out_to_x.get(l)) {
image_list_start = image_list_end = NULL;
image_list_start = image_list_end = nullptr;
context = imlib_context_new();
imlib_context_push(context);
imlib_set_cache_size(do_convert(l, -1).first);
@ -98,24 +98,24 @@ void imlib_cache_size_setting::cleanup(lua::state &l) {
}
}
void cimlib_cleanup(void) {
struct image_list_s *cur = image_list_start, *last = NULL;
while (cur) {
void cimlib_cleanup() {
struct image_list_s *cur = image_list_start, *last = nullptr;
while (cur != nullptr) {
last = cur;
cur = last->next;
free(last);
}
image_list_start = image_list_end = NULL;
image_list_start = image_list_end = nullptr;
}
void cimlib_add_image(const char *args) {
struct image_list_s *cur = NULL;
struct image_list_s *cur = nullptr;
const char *tmp;
cur = (struct image_list_s *)malloc(sizeof(struct image_list_s));
cur = static_cast<struct image_list_s *>(malloc(sizeof(struct image_list_s)));
memset(cur, 0, sizeof(struct image_list_s));
if (!sscanf(args, "%1023s", cur->name)) {
if (sscanf(args, "%1023s", cur->name) == 0) {
NORM_ERR(
"Invalid args for $image. Format is: '<path to image> (-p"
"x,y) (-s WxH) (-n) (-f interval)' (got '%s')",
@ -128,27 +128,27 @@ void cimlib_add_image(const char *args) {
//
// now we check for optional args
tmp = strstr(args, "-p ");
if (tmp) {
if (tmp != nullptr) {
tmp += 3;
sscanf(tmp, "%i,%i", &cur->x, &cur->y);
}
tmp = strstr(args, "-s ");
if (tmp) {
if (tmp != nullptr) {
tmp += 3;
if (sscanf(tmp, "%ix%i", &cur->w, &cur->h)) {
if (sscanf(tmp, "%ix%i", &cur->w, &cur->h) != 0) {
cur->wh_set = 1;
}
}
tmp = strstr(args, "-n");
if (tmp) {
if (tmp != nullptr) {
cur->no_cache = 1;
}
tmp = strstr(args, "-f ");
if (tmp) {
if (tmp != nullptr) {
tmp += 3;
if (sscanf(tmp, "%d", &cur->flush_interval)) {
if (sscanf(tmp, "%d", &cur->flush_interval) != 0) {
cur->no_cache = 0;
}
}
@ -157,7 +157,7 @@ void cimlib_add_image(const char *args) {
cur->flush_interval = 0;
}
if (image_list_end) {
if (image_list_end != nullptr) {
image_list_end->next = cur;
image_list_end = cur;
} else {
@ -168,7 +168,7 @@ void cimlib_add_image(const char *args) {
static void cimlib_draw_image(struct image_list_s *cur, int *clip_x,
int *clip_y, int *clip_x2, int *clip_y2) {
int w, h;
time_t now = time(NULL);
time_t now = time(nullptr);
static int rep = 0;
if (imlib_context_get_drawable() != window.drawable) {
@ -176,8 +176,10 @@ static void cimlib_draw_image(struct image_list_s *cur, int *clip_x,
}
image = imlib_load_image(cur->name);
if (!image) {
if (!rep) NORM_ERR("Unable to load image '%s'", cur->name);
if (image == nullptr) {
if (rep == 0) {
NORM_ERR("Unable to load image '%s'", cur->name);
}
rep = 1;
return;
}
@ -194,7 +196,7 @@ static void cimlib_draw_image(struct image_list_s *cur, int *clip_x,
imlib_image_set_has_alpha(1);
w = imlib_image_get_width();
h = imlib_image_get_height();
if (!cur->wh_set) {
if (cur->wh_set == 0) {
cur->w = w;
cur->h = h;
}
@ -202,22 +204,30 @@ static void cimlib_draw_image(struct image_list_s *cur, int *clip_x,
imlib_blend_image_onto_image(image, 1, 0, 0, w, h, cur->x, cur->y, cur->w,
cur->h);
imlib_context_set_image(image);
if (cur->no_cache ||
(cur->flush_interval && now % cur->flush_interval == 0)) {
if ((cur->no_cache != 0) ||
((cur->flush_interval != 0) && now % cur->flush_interval == 0)) {
imlib_free_image_and_decache();
} else {
imlib_free_image();
}
if (cur->x < *clip_x) *clip_x = cur->x;
if (cur->y < *clip_y) *clip_y = cur->y;
if (cur->x + cur->w > *clip_x2) *clip_x2 = cur->x + cur->w;
if (cur->y + cur->h > *clip_y2) *clip_y2 = cur->y + cur->h;
if (cur->x < *clip_x) {
*clip_x = cur->x;
}
if (cur->y < *clip_y) {
*clip_y = cur->y;
}
if (cur->x + cur->w > *clip_x2) {
*clip_x2 = cur->x + cur->w;
}
if (cur->y + cur->h > *clip_y2) {
*clip_y2 = cur->y + cur->h;
}
}
static void cimlib_draw_all(int *clip_x, int *clip_y, int *clip_x2,
int *clip_y2) {
struct image_list_s *cur = image_list_start;
while (cur) {
while (cur != nullptr) {
cimlib_draw_image(cur, clip_x, clip_y, clip_x2, clip_y2);
cur = cur->next;
}
@ -228,11 +238,13 @@ void cimlib_render(int x, int y, int width, int height) {
int clip_x2 = 0, clip_y2 = 0;
time_t now;
if (!image_list_start) return; /* are we actually drawing anything? */
if (image_list_start == nullptr) {
return; /* are we actually drawing anything? */
}
/* cheque if it's time to flush our cache */
now = time(NULL);
if (imlib_cache_flush_interval.get(*state) &&
now = time(nullptr);
if ((imlib_cache_flush_interval.get(*state) != 0u) &&
now - imlib_cache_flush_interval.get(*state) > cimlib_cache_flush_last) {
int size = imlib_get_cache_size();
imlib_set_cache_size(0);
@ -258,8 +270,12 @@ void cimlib_render(int x, int y, int width, int height) {
imlib_context_set_image(buffer);
/* setup our clip rect */
if (clip_x == INT_MAX) clip_x = 0;
if (clip_y == INT_MAX) clip_y = 0;
if (clip_x == INT_MAX) {
clip_x = 0;
}
if (clip_y == INT_MAX) {
clip_y = 0;
}
/* render the image at 0, 0 */
imlib_render_image_part_on_drawable_at_size(
@ -269,8 +285,9 @@ void cimlib_render(int x, int y, int width, int height) {
imlib_free_image();
}
void print_image_callback(struct text_object *obj, char *p, int p_max_size) {
(void)p;
void print_image_callback(struct text_object *obj, char *p,
int p_max_size) {
p = p; // just a trick to make the compiler happy about this being non-const
(void)p_max_size;
cimlib_add_image(obj->data.s);

View File

@ -28,7 +28,7 @@
#include <X11/Xlib.h>
void cimlib_add_image(const char *name);
void cimlib_add_image(const char *args);
void cimlib_set_cache_size(long size);
void cimlib_set_cache_flush_interval(long interval);
void cimlib_render(int x, int y, int width, int height);

View File

@ -50,7 +50,7 @@ struct ctx {
void ev_connected(irc_session_t *session, const char *event, const char *origin,
const char **params, unsigned int count) {
struct ctx *ctxptr = (struct ctx *)irc_get_ctx(session);
if (irc_cmd_join(session, ctxptr->chan, NULL) != 0) {
if (irc_cmd_join(session, ctxptr->chan, nullptr) != 0) {
NORM_ERR("irc: %s", irc_strerror(irc_errno(session)));
}
if (event || origin || params || count) {
@ -62,7 +62,7 @@ void addmessage(struct ctx *ctxptr, char *nick, const char *text) {
struct ll_text *newmsg = (struct ll_text *)malloc(sizeof(struct ll_text));
newmsg->text = (char *)malloc(strlen(nick) + strlen(text) + 4); // 4 = ": \n"
sprintf(newmsg->text, "%s: %s\n", nick, text);
newmsg->next = NULL;
newmsg->next = nullptr;
int msgcnt = 1;
if (!lastmsg) {
ctxptr->messages = newmsg;
@ -126,9 +126,9 @@ void ev_num(irc_session_t *session, unsigned int event, const char *origin,
"The correct syntax is ${irc server(:port) #channel (max_msg_lines)}"
#define IRCPORT 6667
#define IRCNICK "conky"
#define IRCSERVERPASS NULL
#define IRCUSER NULL
#define IRCREAL NULL
#define IRCSERVERPASS nullptr
#define IRCUSER nullptr
#define IRCREAL nullptr
void *ircclient(void *ptr) {
struct obj_irc *ircobj = (struct obj_irc *)ptr;
@ -145,20 +145,20 @@ void *ircclient(void *ptr) {
callbacks.event_numeric = ev_num;
ircobj->session = irc_create_session(&callbacks);
server = strtok(ircobj->arg, " ");
ctxptr->chan = strtok(NULL, " ");
ctxptr->chan = strtok(nullptr, " ");
if (!ctxptr->chan) {
NORM_ERR("irc: %s", IRCSYNTAX);
}
str_max_msg_lines = strtok(NULL, " ");
str_max_msg_lines = strtok(nullptr, " ");
if (str_max_msg_lines) {
ctxptr->max_msg_lines = strtol(str_max_msg_lines, NULL, 10);
ctxptr->max_msg_lines = strtol(str_max_msg_lines, nullptr, 10);
}
ctxptr->messages = NULL;
ctxptr->messages = nullptr;
irc_set_ctx(ircobj->session, ctxptr);
server = strtok(server, ":");
strport = strtok(NULL, ":");
strport = strtok(nullptr, ":");
if (strport) {
port = strtol(strport, NULL, 10);
port = strtol(strport, nullptr, 10);
if (port < 1 || port > 65535) port = IRCPORT;
} else {
port = IRCPORT;
@ -190,16 +190,16 @@ void *ircclient(void *ptr) {
}
free(ircobj->arg);
free(ctxptr);
return NULL;
return nullptr;
}
void parse_irc_args(struct text_object *obj, const char *arg) {
struct obj_irc *opaque = (struct obj_irc *)malloc(sizeof(struct obj_irc));
opaque->thread = (pthread_t *)malloc(sizeof(pthread_t));
srand(time(NULL));
opaque->session = NULL;
srand(time(nullptr));
opaque->session = nullptr;
opaque->arg = strdup(arg);
pthread_create(opaque->thread, NULL, ircclient, opaque);
pthread_create(opaque->thread, nullptr, ircclient, opaque);
obj->data.opaque = opaque;
}
@ -225,14 +225,14 @@ void print_irc(struct text_object *obj, char *p, int p_max_size) {
p[strlen(p) - 1] = 0;
}
if (!ctxptr->max_msg_lines) {
ctxptr->messages = NULL;
ctxptr->messages = nullptr;
}
}
void free_irc(struct text_object *obj) {
struct obj_irc *ircobj = (struct obj_irc *)obj->data.opaque;
struct ctx *ctxptr;
struct ll_text *nextmsg, *curmsg = NULL;
struct ll_text *nextmsg, *curmsg = nullptr;
if (ircobj->session) {
if (irc_is_connected(ircobj->session)) {
@ -240,7 +240,7 @@ void free_irc(struct text_object *obj) {
curmsg = ctxptr->messages;
irc_disconnect(ircobj->session);
}
pthread_join(*(ircobj->thread), NULL);
pthread_join(*(ircobj->thread), nullptr);
irc_destroy_session(ircobj->session);
}
free(ircobj->thread);

View File

@ -49,7 +49,7 @@ struct journal {
void free_journal(struct text_object *obj) {
struct journal *j = (struct journal *)obj->data.opaque;
obj->data.opaque = NULL;
obj->data.opaque = nullptr;
delete j;
}
@ -113,7 +113,7 @@ out:
void print_journal(struct text_object *obj, char *p, int p_max_size) {
size_t read = 0, length;
struct journal *j = (struct journal *)obj->data.opaque;
sd_journal *jh = NULL;
sd_journal *jh = nullptr;
struct tm *tm;
time_t time;

File diff suppressed because it is too large Load Diff

View File

@ -240,17 +240,17 @@ void mpd_freeSearchStats(mpd_SearchStats *stats);
typedef struct _mpd_Song {
/* filename of song */
char *file;
/* artist, maybe NULL if there is no tag */
/* artist, maybe nullptr if there is no tag */
char *artist;
/* albumartist, maybe NULL if there is no tag */
/* albumartist, maybe nullptr if there is no tag */
char *albumartist;
/* title, maybe NULL if there is no tag */
/* title, maybe nullptr if there is no tag */
char *title;
/* album, maybe NULL if there is no tag */
/* album, maybe nullptr if there is no tag */
char *album;
/* track, maybe NULL if there is no tag */
/* track, maybe nullptr if there is no tag */
char *track;
/* name, maybe NULL if there is no tag; it's the name of the current song,
/* name, maybe nullptr if there is no tag; it's the name of the current song,
* f.e. the icyName of the stream */
char *name;
/* date */
@ -279,7 +279,7 @@ typedef struct _mpd_Song {
/* mpd_newSong
* use to allocate memory for a new mpd_Song
* file, artist, etc all initialized to NULL
* file, artist, etc all initialized to nullptr
* if you're going to assign values to file, artist, etc., be sure to
* malloc or strdup the memory
* use mpd_freeSong to free the memory for the mpd_Song, it will also
@ -326,7 +326,7 @@ typedef struct _mpd_PlaylistFile {
} mpd_PlaylistFile;
/* mpd_newPlaylistFile
* allocates memory for new mpd_PlaylistFile, path is set to NULL
* allocates memory for new mpd_PlaylistFile, path is set to nullptr
* free this memory with mpd_freePlaylistFile */
mpd_PlaylistFile *mpd_newPlaylistFile(void);
@ -375,10 +375,10 @@ mpd_InfoEntity *mpd_getNextInfoEntity(mpd_Connection *connection);
void mpd_sendCurrentSongCommand(mpd_Connection *connection);
/* songNum of -1, means to display the whole list */
void mpd_sendPlaylistInfoCommand(mpd_Connection *connection, int songNum);
void mpd_sendPlaylistInfoCommand(mpd_Connection *connection, int songPos);
/* songId of -1, means to display the whole list */
void mpd_sendPlaylistIdCommand(mpd_Connection *connection, int songId);
void mpd_sendPlaylistIdCommand(mpd_Connection *connection, int id);
/* use this to get the changes in the playlist since version _playlist_ */
void mpd_sendPlChangesCommand(mpd_Connection *connection, long long playlist);
@ -417,7 +417,7 @@ void mpd_sendFindCommand(mpd_Connection *connection, int table,
/* use this function fetch next artist entry, be sure to free the
* returned string.
* NULL means there are no more.
* nullptr means there are no more.
* Best used with sendListArtists */
char *mpd_getNextArtist(mpd_Connection *connection);
@ -427,7 +427,7 @@ char *mpd_getNextTag(mpd_Connection *connection, int type);
/* list artist or albums by artist
* arg1 should be set to the artist if listing albums by a artist
* otherwise NULL for listing all artists or albums */
* otherwise nullptr for listing all artists or albums */
void mpd_sendListCommand(mpd_Connection *connection, int table,
const char *arg1);
@ -437,9 +437,9 @@ void mpd_sendAddCommand(mpd_Connection *connection, const char *file);
int mpd_sendAddIdCommand(mpd_Connection *connection, const char *file);
void mpd_sendDeleteCommand(mpd_Connection *connection, int songNum);
void mpd_sendDeleteCommand(mpd_Connection *connection, int songPos);
void mpd_sendDeleteIdCommand(mpd_Connection *connection, int songNum);
void mpd_sendDeleteIdCommand(mpd_Connection *connection, int id);
void mpd_sendSaveCommand(mpd_Connection *connection, const char *name);
@ -457,9 +457,9 @@ void mpd_sendClearCommand(mpd_Connection *connection);
/* use this to start playing at the beginning, useful when in random mode */
#define MPD_PLAY_AT_BEGINNING -1
void mpd_sendPlayCommand(mpd_Connection *connection, int songNum);
void mpd_sendPlayCommand(mpd_Connection *connection, int songPos);
void mpd_sendPlayIdCommand(mpd_Connection *connection, int songNum);
void mpd_sendPlayIdCommand(mpd_Connection *connection, int id);
void mpd_sendStopCommand(mpd_Connection *connection);
@ -471,15 +471,15 @@ void mpd_sendPrevCommand(mpd_Connection *connection);
void mpd_sendMoveCommand(mpd_Connection *connection, int from, int to);
void mpd_sendMoveIdCommand(mpd_Connection *connection, int from, int to);
void mpd_sendMoveIdCommand(mpd_Connection *connection, int id, int to);
void mpd_sendSwapCommand(mpd_Connection *connection, int song1, int song2);
void mpd_sendSwapIdCommand(mpd_Connection *connection, int song1, int song2);
void mpd_sendSwapIdCommand(mpd_Connection *connection, int id1, int id2);
void mpd_sendSeekCommand(mpd_Connection *connection, int song, int seek_time);
void mpd_sendSeekIdCommand(mpd_Connection *connection, int song, int seek_time);
void mpd_sendSeekIdCommand(mpd_Connection *connection, int id, int seek_time);
void mpd_sendRepeatCommand(mpd_Connection *connection, int repeatMode);

View File

@ -114,12 +114,12 @@ struct _tcp_port_monitor_t {
_tcp_port_monitor_t(int max_connections)
: hash(),
p_peek(max_connections, static_cast<const tcp_connection_t *>(NULL)) {}
p_peek(max_connections, static_cast<const tcp_connection_t *>(nullptr)) {}
_tcp_port_monitor_t(const _tcp_port_monitor_t &other)
: hash(other.hash),
p_peek(other.p_peek.size(),
static_cast<const tcp_connection_t *>(NULL)) {
static_cast<const tcp_connection_t *>(nullptr)) {
// we must rebuild the peek table because the pointers are no longer valid
rebuild_peek_table();
}
@ -131,7 +131,7 @@ struct _tcp_port_monitor_t {
/* zero out the peek array */
std::fill(p_peek.begin(), p_peek.end(),
static_cast<tcp_connection_t *>(NULL));
static_cast<tcp_connection_t *>(nullptr));
size_t i = 0;
for (connection_hash_t::iterator j = hash.begin(); j != hash.end();
@ -165,7 +165,7 @@ void age_tcp_port_monitor(monitor_hash_t::value_type &monitor, void *p_void) {
* If the age goes negative, we remove the connection from the monitor.
* Function takes O(n) time on the number of connections. */
if (p_void) { /* p_void should be NULL in this context */
if (p_void) { /* p_void should be nullptr in this context */
return;
}
@ -183,7 +183,7 @@ void age_tcp_port_monitor(monitor_hash_t::value_type &monitor, void *p_void) {
void rebuild_tcp_port_monitor_peek_table(monitor_hash_t::value_type &monitor,
void *p_void) {
if (p_void) { /* p_void should be NULL in this context */
if (p_void) { /* p_void should be nullptr in this context */
return;
}
@ -287,7 +287,7 @@ void print_host(char *p_buffer, size_t buffer_size, const struct in6_addr *addr,
slen = sizeof(sa.sa6);
}
getnameinfo(&sa.sa, slen, p_buffer, buffer_size, NULL, 0,
getnameinfo(&sa.sa, slen, p_buffer, buffer_size, nullptr, 0,
fqdn ? 0 : NI_NUMERICHOST);
}
@ -318,18 +318,18 @@ void process_file(tcp_port_monitor_collection_t *p_collection,
tcp_connection_t conn;
unsigned long inode, uid, state;
if ((fp = std::fopen(file, "r")) == NULL) {
if ((fp = std::fopen(file, "r")) == nullptr) {
return;
}
/* ignore field name line */
if (std::fgets(buf, 255, fp) == NULL) {
if (std::fgets(buf, 255, fp) == nullptr) {
std::fclose(fp);
return;
}
/* read all tcp connections */
while (std::fgets(buf, sizeof(buf), fp) != NULL) {
while (std::fgets(buf, sizeof(buf), fp) != nullptr) {
if (std::sscanf(buf,
"%*d: %39[0-9a-fA-F]:%hx %39[0-9a-fA-F]:%hx %lx %*x:%*x "
"%*x:%*x %*x %lu %*d %lu",
@ -419,7 +419,7 @@ int peek_tcp_port_monitor(const tcp_port_monitor_t *p_monitor, int item,
case REMOTESERVICE:
sa.sin_port = htons(p_monitor->p_peek[connection_index]->remote_port);
getnameinfo((struct sockaddr *)&sa, sizeof(struct sockaddr_in), NULL, 0,
getnameinfo((struct sockaddr *)&sa, sizeof(struct sockaddr_in), nullptr, 0,
p_buffer, buffer_size, NI_NUMERICHOST);
break;
@ -444,7 +444,7 @@ int peek_tcp_port_monitor(const tcp_port_monitor_t *p_monitor, int item,
case LOCALSERVICE:
sa.sin_port = htons(p_monitor->p_peek[connection_index]->local_port);
getnameinfo((struct sockaddr *)&sa, sizeof(struct sockaddr_in), NULL, 0,
getnameinfo((struct sockaddr *)&sa, sizeof(struct sockaddr_in), nullptr, 0,
p_buffer, buffer_size, NI_NUMERICHOST);
break;
@ -483,12 +483,12 @@ void update_tcp_port_monitor_collection(
/* age the connections in all port monitors. */
for_each_tcp_port_monitor_in_collection(p_collection, &age_tcp_port_monitor,
NULL);
nullptr);
/* rebuild the connection peek tables of all monitors
* so clients can peek in O(1) time */
for_each_tcp_port_monitor_in_collection(
p_collection, &rebuild_tcp_port_monitor_peek_table, NULL);
p_collection, &rebuild_tcp_port_monitor_peek_table, nullptr);
}
/* Creation of reduntant monitors is silently ignored */
@ -511,12 +511,12 @@ tcp_port_monitor_t *find_tcp_port_monitor(
tcp_port_monitor_collection_t *p_collection, in_port_t port_range_begin,
in_port_t port_range_end) {
if (!p_collection) {
return NULL;
return nullptr;
}
/* is monitor in hash? */
monitor_hash_t::iterator i =
p_collection->hash.find(port_range_t(port_range_begin, port_range_end));
return i == p_collection->hash.end() ? NULL : &i->second;
return i == p_collection->hash.end() ? nullptr : &i->second;
}

View File

@ -175,7 +175,7 @@ int update_meminfo(void) {
}
while (!feof(meminfo_fp)) {
if (fgets(buf, 255, meminfo_fp) == NULL) {
if (fgets(buf, 255, meminfo_fp) == nullptr) {
break;
}
@ -227,7 +227,7 @@ void print_laptop_mode(struct text_object *obj, char *p, int p_max_size) {
(void)obj;
if ((fp = fopen("/proc/sys/vm/laptop_mode", "r")) != NULL) {
if ((fp = fopen("/proc/sys/vm/laptop_mode", "r")) != nullptr) {
if (fscanf(fp, "%d\n", &val) <= 0) val = 0;
fclose(fp);
}
@ -245,7 +245,7 @@ void print_ioscheduler(struct text_object *obj, char *p, int p_max_size) {
if (!obj->data.s) goto out_fail;
snprintf(buf, 127, "/sys/block/%s/queue/scheduler", obj->data.s);
if ((fp = fopen(buf, "r")) == NULL) goto out_fail;
if ((fp = fopen(buf, "r")) == nullptr) goto out_fail;
while (fscanf(fp, "%127s", buf) == 1) {
if (buf[0] == '[') {
@ -276,7 +276,7 @@ static struct {
}
void update_gateway_info_failure(const char *reason) {
if (reason != NULL) {
if (reason != nullptr) {
perror(reason);
}
// 2 pointers to 1 location causes a crash when we try to free them both
@ -298,7 +298,7 @@ int update_gateway_info(void) {
free_and_zero(gw_info.ip);
gw_info.count = 0;
if ((fp = fopen("/proc/net/route", "r")) == NULL) {
if ((fp = fopen("/proc/net/route", "r")) == nullptr) {
update_gateway_info_failure("fopen()");
return 0;
}
@ -412,7 +412,7 @@ int update_net_stats(void) {
long long r, t, last_recv, last_trans;
/* quit only after all non-header lines from /proc/net/dev parsed */
if (fgets(buf, 255, net_dev_fp) == NULL) {
if (fgets(buf, 255, net_dev_fp) == nullptr) {
break;
}
p = buf;
@ -436,7 +436,7 @@ int update_net_stats(void) {
p++;
/* get pointer to interface statistics with the interface name in s */
ns = get_net_stat(s, NULL, NULL);
ns = get_net_stat(s, nullptr, NULL);
ns->up = 1;
memset(&(ns->addr.sa_data), 0, 14);
@ -498,12 +498,12 @@ int update_net_stats(void) {
if (!(((struct ifreq *)conf.ifc_buf) + k)) break;
ns2 = get_net_stat(((struct ifreq *)conf.ifc_buf)[k].ifr_ifrn.ifrn_name,
NULL, NULL);
nullptr, NULL);
ns2->addr = ((struct ifreq *)conf.ifc_buf)[k].ifr_ifru.ifru_addr;
sprintf(temp_addr, "%u.%u.%u.%u, ", ns2->addr.sa_data[2] & 255,
ns2->addr.sa_data[3] & 255, ns2->addr.sa_data[4] & 255,
ns2->addr.sa_data[5] & 255);
if (NULL == strstr(ns2->addrs, temp_addr))
if (nullptr == strstr(ns2->addrs, temp_addr))
strncpy(ns2->addrs + strlen(ns2->addrs), temp_addr, 17);
}
@ -620,17 +620,17 @@ int update_net_stats(void) {
// remove the old v6 addresses otherwise they are listed multiple times
for (unsigned int i = 0; i < MAX_NET_INTERFACES; i++) {
ns = &netstats[i];
while (ns->v6addrs != NULL) {
while (ns->v6addrs != nullptr) {
lastv6 = ns->v6addrs;
ns->v6addrs = ns->v6addrs->next;
free(lastv6);
}
}
if ((file = fopen(PROCDIR "/net/if_inet6", "r")) != NULL) {
if ((file = fopen(PROCDIR "/net/if_inet6", "r")) != nullptr) {
while (fscanf(file, "%32s %*02x %02x %02x %*02x %20s\n", v6addr, &netmask,
&scope, devname) != EOF) {
ns = get_net_stat(devname, NULL, NULL);
if (ns->v6addrs == NULL) {
ns = get_net_stat(devname, nullptr, NULL);
if (ns->v6addrs == nullptr) {
lastv6 = (struct v6addr *)malloc(sizeof(struct v6addr));
ns->v6addrs = lastv6;
} else {
@ -661,7 +661,7 @@ int update_net_stats(void) {
default:
lastv6->scope = '?';
}
lastv6->next = NULL;
lastv6->next = nullptr;
}
fclose(file);
}
@ -765,7 +765,7 @@ void determine_longstat_file(void) {
if (not(stat_fp = open_file("/proc/stat", &rep))) return;
while (not feof(stat_fp)) {
if (fgets(buf, MAX_PROCSTAT_LINELEN, stat_fp) == NULL) break;
if (fgets(buf, MAX_PROCSTAT_LINELEN, stat_fp) == nullptr) break;
if (strncmp(buf, "cpu", 3) == 0) {
determine_longstat(buf);
break;
@ -794,7 +794,7 @@ void get_cpu_count(void) {
info.cpu_count = 0;
while (!feof(stat_fp)) {
if (fgets(buf, 255, stat_fp) == NULL) {
if (fgets(buf, 255, stat_fp) == nullptr) {
break;
}
@ -803,16 +803,16 @@ void get_cpu_count(void) {
// "0,3-7". I assume that chip is really an 8-core die with two cores
// disabled... Presumably you could also get "0,3-4,6", and other
// combos too...
for (str1 = buf;; str1 = NULL) {
for (str1 = buf;; str1 = nullptr) {
token = strtok_r(str1, ",", &saveptr1);
if (token == NULL) break;
if (token == nullptr) break;
++info.cpu_count;
subtoken1 = -1;
subtoken2 = -1;
for (str2 = token;; str2 = NULL) {
for (str2 = token;; str2 = nullptr) {
subtoken = strtok_r(str2, "-", &saveptr2);
if (subtoken == NULL) break;
if (subtoken == nullptr) break;
if (subtoken1 < 0)
subtoken1 = atoi(subtoken);
else
@ -832,12 +832,12 @@ void get_cpu_count(void) {
int update_stat(void) {
FILE *stat_fp;
static int rep = 0;
static struct cpu_info *cpu = NULL;
static struct cpu_info *cpu = nullptr;
char buf[256];
int i;
unsigned int idx;
double curtmp;
const char *stat_template = NULL;
const char *stat_template = nullptr;
unsigned int malloc_cpu_size = 0;
extern void *global_cpu;
@ -884,7 +884,7 @@ int update_stat(void) {
idx = 0;
while (!feof(stat_fp)) {
if (fgets(buf, 255, stat_fp) == NULL) {
if (fgets(buf, 255, stat_fp) == nullptr) {
break;
}
@ -969,7 +969,7 @@ int fscanf_no_i18n(FILE *stream, const char *format, ...) {
va_list ap;
#ifdef BUILD_I18N
const char *oldlocale = setlocale(LC_NUMERIC, NULL);
const char *oldlocale = setlocale(LC_NUMERIC, nullptr);
setlocale(LC_NUMERIC, "C");
#endif
@ -1062,8 +1062,8 @@ static int open_sysfs_sensor(const char *dir, const char *dev, const char *type,
memset(buf, 0, sizeof(buf));
/* if device is NULL or *, get first */
if (dev == NULL || strcmp(dev, "*") == 0) {
/* if device is nullptr or *, get first */
if (dev == nullptr || strcmp(dev, "*") == 0) {
static int rep = 0;
if (!get_first_file_in_a_directory(dir, buf, &rep)) {
@ -1184,7 +1184,7 @@ static double get_sysfs_info(int *fd, int divisor, char *devtype, char *type) {
/* My dirty hack for computing CPU value
* Filedil, from forums.gentoo.org */
/* if (strstr(devtype, "temp1_input") != NULL) {
/* if (strstr(devtype, "temp1_input") != nullptr) {
return -15.096 + 1.4893 * (val / 1000.0);
} */
@ -1322,7 +1322,7 @@ char get_freq(char *p_client_buffer, size_t client_buffer_size,
* this node and divide by 1000 to get Mhz. */
if (fgets(s, sizeof(s), f)) {
s[strlen(s) - 1] = '\0';
freq = strtod(s, NULL);
freq = strtod(s, nullptr);
}
fclose(f);
snprintf(p_client_buffer, client_buffer_size, p_format,
@ -1339,7 +1339,7 @@ char get_freq(char *p_client_buffer, size_t client_buffer_size,
}
// read the file
while (fgets(s, sizeof(s), f) != NULL) {
while (fgets(s, sizeof(s), f) != nullptr) {
#if defined(__i386) || defined(__x86_64)
// and search for the cpu mhz
if (strncmp(s, "cpu MHz", 7) == 0 && cpu == 0) {
@ -1359,11 +1359,11 @@ char get_freq(char *p_client_buffer, size_t client_buffer_size,
// strip " est.\n"
frequency[strlen(frequency) - 6] = '\0';
// kernel reports in Hz
freq = strtod(frequency, NULL) / 1000000;
freq = strtod(frequency, nullptr) / 1000000;
#else
// strip \n
frequency[strlen(frequency) - 1] = '\0';
freq = strtod(frequency, NULL);
freq = strtod(frequency, nullptr);
#endif
break;
}
@ -1418,7 +1418,7 @@ static char get_voltage(char *p_client_buffer, size_t client_buffer_size,
if (f) {
if (fgets(s, sizeof(s), f)) {
s[strlen(s) - 1] = '\0';
freq = strtod(s, NULL);
freq = strtod(s, nullptr);
}
fclose(f);
} else {
@ -1441,7 +1441,7 @@ static char get_voltage(char *p_client_buffer, size_t client_buffer_size,
while (!feof(f)) {
char line[256];
if (fgets(line, 255, f) == NULL) {
if (fgets(line, 255, f) == nullptr) {
break;
}
sscanf(line, "%d %d", &freq_comp, &voltage);
@ -1558,7 +1558,7 @@ void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size,
if (fp) {
/* sysfs processing */
while (!feof(fp)) {
if (fgets(buf, sizeof(buf), fp) == NULL) break;
if (fgets(buf, sizeof(buf), fp) == nullptr) break;
if (strncmp(buf, "POWER_SUPPLY_ONLINE=", 20) == 0) {
int online = 0;
@ -1613,7 +1613,7 @@ int open_acpi_temperature(const char *name) {
char path[256];
int fd;
if (name == NULL || strcmp(name, "*") == 0) {
if (name == nullptr || strcmp(name, "*") == 0) {
snprintf(path, 255, ACPI_THERMAL_FORMAT, ACPI_THERMAL_ZONE_DEFAULT);
} else {
snprintf(path, 255, ACPI_THERMAL_FORMAT, name);
@ -1743,9 +1743,9 @@ monitori p<><70>ll<6C> mutta ilman verkkovirtaa
#define APM_PATH "/proc/apm"
#define MAX_BATTERY_COUNT 4
static FILE *sysfs_bat_fp[MAX_BATTERY_COUNT] = {NULL, NULL, NULL, NULL};
static FILE *acpi_bat_fp[MAX_BATTERY_COUNT] = {NULL, NULL, NULL, NULL};
static FILE *apm_bat_fp[MAX_BATTERY_COUNT] = {NULL, NULL, NULL, NULL};
static FILE *sysfs_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL};
static FILE *acpi_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL};
static FILE *apm_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL};
static int batteries_initialized = 0;
static char batteries[MAX_BATTERY_COUNT][32];
@ -1823,17 +1823,17 @@ void get_battery_stuff(char *buffer, unsigned int n, const char *bat,
/* first try SYSFS if that fails try ACPI */
if (sysfs_bat_fp[idx] == NULL && acpi_bat_fp[idx] == NULL &&
apm_bat_fp[idx] == NULL) {
if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL &&
apm_bat_fp[idx] == nullptr) {
sysfs_bat_fp[idx] = open_file(sysfs_path, &rep);
}
if (sysfs_bat_fp[idx] == NULL && acpi_bat_fp[idx] == NULL &&
apm_bat_fp[idx] == NULL) {
if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL &&
apm_bat_fp[idx] == nullptr) {
acpi_bat_fp[idx] = open_file(acpi_path, &rep1);
}
if (sysfs_bat_fp[idx] != NULL) {
if (sysfs_bat_fp[idx] != nullptr) {
/* SYSFS */
int present_rate = -1;
int remaining_capacity = -1;
@ -1844,7 +1844,7 @@ void get_battery_stuff(char *buffer, unsigned int n, const char *bat,
while (!feof(sysfs_bat_fp[idx])) {
char buf[256];
if (fgets(buf, 256, sysfs_bat_fp[idx]) == NULL) break;
if (fgets(buf, 256, sysfs_bat_fp[idx]) == nullptr) break;
/* let's just hope units are ok */
if (strncmp(buf, "POWER_SUPPLY_PRESENT=1", 22) == 0)
@ -1871,7 +1871,7 @@ void get_battery_stuff(char *buffer, unsigned int n, const char *bat,
}
fclose(sysfs_bat_fp[idx]);
sysfs_bat_fp[idx] = NULL;
sysfs_bat_fp[idx] = nullptr;
/* Hellf[i]re notes that remaining capacity can exceed acpi_last_full */
if (remaining_capacity > acpi_last_full[idx])
@ -1956,7 +1956,7 @@ void get_battery_stuff(char *buffer, unsigned int n, const char *bat,
else
strncpy(last_battery_str[idx], "not present", 64);
}
} else if (acpi_bat_fp[idx] != NULL) {
} else if (acpi_bat_fp[idx] != nullptr) {
/* ACPI */
int present_rate = -1;
int remaining_capacity = -1;
@ -1971,11 +1971,11 @@ void get_battery_stuff(char *buffer, unsigned int n, const char *bat,
snprintf(path, 127, ACPI_BATTERY_BASE_PATH "/%s/info", bat);
fp = open_file(path, &rep3);
if (fp != NULL) {
if (fp != nullptr) {
while (!feof(fp)) {
char b[256];
if (fgets(b, 256, fp) == NULL) {
if (fgets(b, 256, fp) == nullptr) {
break;
}
if (sscanf(b, "last full capacity: %d", &acpi_last_full[idx]) != 0) {
@ -1994,7 +1994,7 @@ void get_battery_stuff(char *buffer, unsigned int n, const char *bat,
while (!feof(acpi_bat_fp[idx])) {
char buf[256];
if (fgets(buf, 256, acpi_bat_fp[idx]) == NULL) {
if (fgets(buf, 256, acpi_bat_fp[idx]) == nullptr) {
break;
}
@ -2088,14 +2088,14 @@ void get_battery_stuff(char *buffer, unsigned int n, const char *bat,
}
}
fclose(acpi_bat_fp[idx]);
acpi_bat_fp[idx] = NULL;
acpi_bat_fp[idx] = nullptr;
} else {
/* APM */
if (apm_bat_fp[idx] == NULL) {
if (apm_bat_fp[idx] == nullptr) {
apm_bat_fp[idx] = open_file(APM_PATH, &rep2);
}
if (apm_bat_fp[idx] != NULL) {
if (apm_bat_fp[idx] != nullptr) {
unsigned int ac, status, flag;
int life;
@ -2118,7 +2118,7 @@ void get_battery_stuff(char *buffer, unsigned int n, const char *bat,
/* it seemed to buffer it so file must be closed (or could use
* syscalls directly but I don't feel like coding it now) */
fclose(apm_bat_fp[idx]);
apm_bat_fp[idx] = NULL;
apm_bat_fp[idx] = nullptr;
}
}
set_return_value(buffer, n, item, idx);
@ -2181,22 +2181,22 @@ int _get_battery_perct(const char *bat) {
/* Only check for SYSFS or ACPI */
if (sysfs_bat_fp[idx] == NULL && acpi_bat_fp[idx] == NULL &&
apm_bat_fp[idx] == NULL) {
if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL &&
apm_bat_fp[idx] == nullptr) {
sysfs_bat_fp[idx] = open_file(sysfs_path, &rep);
rep = 0;
}
if (sysfs_bat_fp[idx] == NULL && acpi_bat_fp[idx] == NULL &&
apm_bat_fp[idx] == NULL) {
if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL &&
apm_bat_fp[idx] == nullptr) {
acpi_bat_fp[idx] = open_file(acpi_path, &rep);
}
if (sysfs_bat_fp[idx] != NULL) {
if (sysfs_bat_fp[idx] != nullptr) {
/* SYSFS */
while (!feof(sysfs_bat_fp[idx])) {
char buf[256];
if (fgets(buf, 256, sysfs_bat_fp[idx]) == NULL) break;
if (fgets(buf, 256, sysfs_bat_fp[idx]) == nullptr) break;
if (strncmp(buf, "POWER_SUPPLY_CHARGE_NOW=", 24) == 0) {
sscanf(buf, "POWER_SUPPLY_CHARGE_NOW=%d", &remaining_capacity);
@ -2210,9 +2210,9 @@ int _get_battery_perct(const char *bat) {
}
fclose(sysfs_bat_fp[idx]);
sysfs_bat_fp[idx] = NULL;
sysfs_bat_fp[idx] = nullptr;
} else if (acpi_bat_fp[idx] != NULL) {
} else if (acpi_bat_fp[idx] != nullptr) {
/* ACPI */
/* read last full capacity if it's zero */
if (acpi_design_capacity[idx] == 0) {
@ -2222,11 +2222,11 @@ int _get_battery_perct(const char *bat) {
snprintf(path, 127, ACPI_BATTERY_BASE_PATH "/%s/info", bat);
fp = open_file(path, &rep2);
if (fp != NULL) {
if (fp != nullptr) {
while (!feof(fp)) {
char b[256];
if (fgets(b, 256, fp) == NULL) {
if (fgets(b, 256, fp) == nullptr) {
break;
}
if (sscanf(b, "last full capacity: %d", &acpi_design_capacity[idx]) !=
@ -2243,7 +2243,7 @@ int _get_battery_perct(const char *bat) {
while (!feof(acpi_bat_fp[idx])) {
char buf[256];
if (fgets(buf, 256, acpi_bat_fp[idx]) == NULL) {
if (fgets(buf, 256, acpi_bat_fp[idx]) == nullptr) {
break;
}
@ -2339,19 +2339,19 @@ void get_powerbook_batt_info(struct text_object *obj, char *buffer, int n) {
}
pb_battery_info_update = current_update_time;
if (pmu_battery_fp == NULL) {
if (pmu_battery_fp == nullptr) {
pmu_battery_fp = open_file(batt_path, &rep);
if (pmu_battery_fp == NULL) {
if (pmu_battery_fp == nullptr) {
return;
}
}
if (pmu_battery_fp != NULL) {
if (pmu_battery_fp != nullptr) {
rewind(pmu_battery_fp);
while (!feof(pmu_battery_fp)) {
char buf[32];
if (fgets(buf, sizeof(buf), pmu_battery_fp) == NULL) {
if (fgets(buf, sizeof(buf), pmu_battery_fp) == nullptr) {
break;
}
@ -2366,19 +2366,19 @@ void get_powerbook_batt_info(struct text_object *obj, char *buffer, int n) {
}
}
}
if (pmu_info_fp == NULL) {
if (pmu_info_fp == nullptr) {
pmu_info_fp = open_file(info_path, &rep);
if (pmu_info_fp == NULL) {
if (pmu_info_fp == nullptr) {
return;
}
}
if (pmu_info_fp != NULL) {
if (pmu_info_fp != nullptr) {
rewind(pmu_info_fp);
while (!feof(pmu_info_fp)) {
char buf[32];
if (fgets(buf, sizeof(buf), pmu_info_fp) == NULL) {
if (fgets(buf, sizeof(buf), pmu_info_fp) == nullptr) {
break;
}
if (buf[0] == 'A') {
@ -2468,7 +2468,7 @@ void print_disk_protect_queue(struct text_object *obj, char *p,
if (access(path, F_OK)) {
snprintf(path, 127, "/sys/block/%s/queue/protect", obj->data.s);
}
if ((fp = fopen(path, "r")) == NULL) {
if ((fp = fopen(path, "r")) == nullptr) {
snprintf(p, p_max_size, "n/a ");
return;
}
@ -2733,7 +2733,7 @@ static void process_parse_stat(struct process *process) {
* 3. copy string from its position
*/
char *space_ptr = strchr(cmdline, ' ');
if (space_ptr == NULL) {
if (space_ptr == nullptr) {
strcpy(tmpstr, cmdline);
} else {
long int space_pos = space_ptr - cmdline;
@ -2742,7 +2742,7 @@ static void process_parse_stat(struct process *process) {
}
char *slash_ptr = strrchr(tmpstr, '/');
if (slash_ptr == NULL) {
if (slash_ptr == nullptr) {
strncpy(cmdline_procname, cmdline, BUFFER_LEN);
} else {
long int slash_pos = slash_ptr - tmpstr;
@ -2838,7 +2838,7 @@ static void process_parse_io(struct process *process) {
}
pos = strstr(line, read_bytes_str);
if (pos == NULL) {
if (pos == nullptr) {
/* these should not happen (unless the format of the file changes) */
return;
}
@ -2849,7 +2849,7 @@ static void process_parse_io(struct process *process) {
}
pos = strstr(line, write_bytes_str);
if (pos == NULL) {
if (pos == nullptr) {
return;
}
pos += strlen(write_bytes_str);

View File

@ -22,10 +22,10 @@
*/
#include "llua.h"
#include <config.h>
#include "build.h"
#include "conky.h"
#include "logging.h"
#include <config.h>
#ifdef BUILD_LUA_EXTRAS
extern "C" {
@ -43,14 +43,14 @@ static int llua_block_notify = 0;
static void llua_load(const char *script);
lua_State *lua_L = NULL;
lua_State *lua_L = nullptr;
namespace {
class lua_load_setting : public conky::simple_config_setting<std::string> {
typedef conky::simple_config_setting<std::string> Base;
using Base = conky::simple_config_setting<std::string>;
protected:
void lua_setter(lua::state &l, bool init) {
void lua_setter(lua::state &l, bool init) override {
lua::stack_sentry s(l, -2);
Base::lua_setter(l, init);
@ -70,15 +70,17 @@ class lua_load_setting : public conky::simple_config_setting<std::string> {
++s;
}
void cleanup(lua::state &l) {
void cleanup(lua::state &l) override {
lua::stack_sentry s(l, -1);
#ifdef HAVE_SYS_INOTIFY_H
llua_rm_notifies();
#endif /* HAVE_SYS_INOTIFY_H */
if (!lua_L) return;
if (lua_L == nullptr) {
return;
}
lua_close(lua_L);
lua_L = NULL;
lua_L = nullptr;
}
public:
@ -103,13 +105,13 @@ conky::simple_config_setting<std::string> lua_draw_hook_post(
static int llua_conky_parse(lua_State *L) {
int n = lua_gettop(L); /* number of arguments */
char *str;
char *buf = (char *)calloc(1, max_user_text.get(*state));
auto *buf = static_cast<char *>(calloc(1, max_user_text.get(*state)));
if (n != 1) {
lua_pushstring(
L, "incorrect arguments, conky_parse(string) takes exactly 1 argument");
lua_error(L);
}
if (!lua_isstring(L, 1)) {
if (lua_isstring(L, 1) == 0) {
lua_pushstring(L, "incorrect argument (expecting a string)");
lua_error(L);
}
@ -129,7 +131,7 @@ static int llua_conky_set_update_interval(lua_State *L) {
"takes exactly 1 argument");
lua_error(L);
}
if (!lua_isnumber(L, 1)) {
if (lua_isnumber(L, 1) == 0) {
lua_pushstring(L, "incorrect argument (expecting a number)");
lua_error(L);
}
@ -138,10 +140,12 @@ static int llua_conky_set_update_interval(lua_State *L) {
return 0; /* number of results */
}
void llua_init(void) {
void llua_init() {
const char *libs = PACKAGE_LIBDIR "/lib?.so;";
char *old_path, *new_path;
if (lua_L) return;
if (lua_L != nullptr) {
return;
}
lua_L = luaL_newstate();
/* add our library path to the lua package.cpath global var */
@ -149,7 +153,7 @@ void llua_init(void) {
lua_getglobal(lua_L, "package");
lua_getfield(lua_L, -1, "cpath");
old_path = strdup(lua_tostring(lua_L, -1));
new_path = (char *)malloc(strlen(old_path) + strlen(libs) + 1);
new_path = static_cast<char *>(malloc(strlen(old_path) + strlen(libs) + 1));
strcpy(new_path, libs);
strcat(new_path, old_path);
lua_pushstring(lua_L, new_path);
@ -196,7 +200,7 @@ void llua_load(const char *script) {
std::string path = to_real_path(script);
error = luaL_dofile(lua_L, path.c_str());
if (error) {
if (error != 0) {
NORM_ERR("llua_load: %s", lua_tostring(lua_L, -1));
lua_pop(lua_L, 1);
#ifdef HAVE_SYS_INOTIFY_H
@ -216,10 +220,12 @@ void llua_load(const char *script) {
static const char *tokenize(const char *str, size_t *len) {
str += *len;
*len = 0;
while (str && isspace(*str)) ++str;
while ((str != nullptr) && (isspace(*str) != 0)) {
++str;
}
size_t level = 0;
while (str[*len] && (level > 0 || !isspace(str[*len]))) {
while ((str[*len] != 0) && (level > 0 || (isspace(str[*len]) == 0))) {
switch (str[*len]) {
case '{':
++level;
@ -231,8 +237,9 @@ static const char *tokenize(const char *str, size_t *len) {
++*len;
}
if (!str[*len] && level > 0)
if ((str[*len] == 0) && level > 0) {
NORM_ERR("tokenize: improperly nested token: %s", str);
}
return str;
}
@ -251,22 +258,23 @@ static char *llua_do_call(const char *string, int retc) {
const char *ptr = tokenize(string, &len);
/* proceed only if the function name is present */
if (!len) {
return NULL;
if (len == 0u) {
return nullptr;
}
/* call only conky_ prefixed functions */
if (strncmp(ptr, LUAPREFIX, strlen(LUAPREFIX)) != 0) {
snprintf(func, sizeof func, "%s", LUAPREFIX);
} else
} else {
*func = 0;
}
strncat(func, ptr, std::min(len, sizeof(func) - strlen(func) - 1));
/* push the function name to stack */
lua_getglobal(lua_L, func);
/* parse all function parameters from args and push them to the stack */
while (ptr = tokenize(ptr, &len), len) {
while (ptr = tokenize(ptr, &len), len != 0u) {
lua_pushlstring(lua_L, ptr, len);
argc++;
}
@ -275,7 +283,7 @@ static char *llua_do_call(const char *string, int retc) {
NORM_ERR("llua_do_call: function %s execution failed: %s", func,
lua_tostring(lua_L, -1));
lua_pop(lua_L, -1);
return NULL;
return nullptr;
}
return func;
@ -299,7 +307,7 @@ static char *llua_do_read_call(const char *function, const char *arg, int retc)
if (lua_pcall(lua_L, 1, retc, 0) != 0) {
NORM_ERR("llua_do_call: function %s execution failed: %s", func, lua_tostring(lua_L, -1));
lua_pop(lua_L, -1);
return NULL;
return nullptr;
}
return func;
@ -309,13 +317,15 @@ static char *llua_do_read_call(const char *function, const char *arg, int retc)
/* call a function with args, and return a string from it (must be free'd) */
static char *llua_getstring(const char *args) {
char *func;
char *ret = NULL;
char *ret = nullptr;
if (!lua_L) return NULL;
if (lua_L == nullptr) {
return nullptr;
}
func = llua_do_call(args, 1);
if (func) {
if (!lua_isstring(lua_L, -1)) {
if (func != nullptr) {
if (lua_isstring(lua_L, -1) == 0) {
NORM_ERR(
"llua_getstring: function %s didn't return a string, result "
"discarded",
@ -334,9 +344,9 @@ static char *llua_getstring(const char *args) {
static char *llua_getstring_read(const char *function, const char *arg)
{
char *func;
char *ret = NULL;
char *ret = nullptr;
if(!lua_L) return NULL;
if(!lua_L) return nullptr;
func = llua_do_read_call(function, arg, 1);
if (func) {
@ -356,11 +366,13 @@ static char *llua_getstring_read(const char *function, const char *arg)
static int llua_getnumber(const char *args, double *ret) {
char *func;
if (!lua_L) return 0;
if (lua_L == nullptr) {
return 0;
}
func = llua_do_call(args, 1);
if (func) {
if (!lua_isnumber(lua_L, -1)) {
if (func != nullptr) {
if (lua_isnumber(lua_L, -1) == 0) {
NORM_ERR(
"llua_getnumber: function %s didn't return a number, result "
"discarded",
@ -454,24 +466,32 @@ void llua_set_number(const char *key, double value) {
lua_setfield(lua_L, -2, key);
}
void llua_startup_hook(void) {
if (!lua_L || lua_startup_hook.get(*state).empty()) return;
void llua_startup_hook() {
if ((lua_L == nullptr) || lua_startup_hook.get(*state).empty()) {
return;
}
llua_do_call(lua_startup_hook.get(*state).c_str(), 0);
}
void llua_shutdown_hook(void) {
if (!lua_L || lua_shutdown_hook.get(*state).empty()) return;
void llua_shutdown_hook() {
if ((lua_L == nullptr) || lua_shutdown_hook.get(*state).empty()) {
return;
}
llua_do_call(lua_shutdown_hook.get(*state).c_str(), 0);
}
#ifdef BUILD_X11
void llua_draw_pre_hook(void) {
if (!lua_L || lua_draw_hook_pre.get(*state).empty()) return;
void llua_draw_pre_hook() {
if ((lua_L == nullptr) || lua_draw_hook_pre.get(*state).empty()) {
return;
}
llua_do_call(lua_draw_hook_pre.get(*state).c_str(), 0);
}
void llua_draw_post_hook(void) {
if (!lua_L || lua_draw_hook_post.get(*state).empty()) return;
void llua_draw_post_hook() {
if ((lua_L == nullptr) || lua_draw_hook_post.get(*state).empty()) {
return;
}
llua_do_call(lua_draw_hook_post.get(*state).c_str(), 0);
}
@ -484,7 +504,9 @@ void llua_set_userdata(const char *key, const char *type, void *value) {
void llua_setup_window_table(int text_start_x, int text_start_y, int text_width,
int text_height) {
if (!lua_L) return;
if (lua_L == nullptr) {
return;
}
lua_newtable(lua_L);
if (out_to_x.get(*state)) {
@ -511,7 +533,9 @@ void llua_setup_window_table(int text_start_x, int text_start_y, int text_width,
void llua_update_window_table(int text_start_x, int text_start_y,
int text_width, int text_height) {
if (!lua_L) return;
if (lua_L == nullptr) {
return;
}
lua_getglobal(lua_L, "conky_window");
if (lua_isnil(lua_L, -1)) {
@ -533,7 +557,9 @@ void llua_update_window_table(int text_start_x, int text_start_y,
#endif /* BUILD_X11 */
void llua_setup_info(struct information *i, double u_interval) {
if (!lua_L) return;
if (lua_L == nullptr) {
return;
}
lua_newtable(lua_L);
llua_set_number("update_interval", u_interval);
@ -543,7 +569,9 @@ void llua_setup_info(struct information *i, double u_interval) {
}
void llua_update_info(struct information *i, double u_interval) {
if (!lua_L) return;
if (lua_L == nullptr) {
return;
}
lua_getglobal(lua_L, "conky_info");
if (lua_isnil(lua_L, -1)) {
@ -560,7 +588,7 @@ void llua_update_info(struct information *i, double u_interval) {
void print_lua(struct text_object *obj, char *p, int p_max_size) {
char *str = llua_getstring(obj->data.s);
if (str) {
if (str != nullptr) {
snprintf(p, p_max_size, "%s", str);
free(str);
}
@ -568,7 +596,7 @@ void print_lua(struct text_object *obj, char *p, int p_max_size) {
void print_lua_parse(struct text_object *obj, char *p, int p_max_size) {
char *str = llua_getstring(obj->data.s);
if (str) {
if (str != nullptr) {
evaluate(str, p, p_max_size);
free(str);
}
@ -576,7 +604,7 @@ void print_lua_parse(struct text_object *obj, char *p, int p_max_size) {
double lua_barval(struct text_object *obj) {
double per;
if (llua_getnumber(obj->data.s, &per)) {
if (llua_getnumber(obj->data.s, &per) != 0) {
return per;
}
return 0;

View File

@ -49,8 +49,7 @@ const char this_cpp_object[] = "lua::this_cpp_object";
// converts C++ exceptions to strings, so lua can do something with them
int exception_to_string(lua_State *l) {
std::exception_ptr *ptr =
static_cast<std::exception_ptr *>(lua_touserdata(l, -1));
auto *ptr = static_cast<std::exception_ptr *>(lua_touserdata(l, -1));
assert(ptr);
try {
std::rethrow_exception(*ptr);
@ -71,7 +70,7 @@ int exception_to_string(lua_State *l) {
return 1;
}
int absindex(lua_State *l, int index) throw() {
int absindex(lua_State *l, int index) {
return index < 0 && -index <= lua_gettop(l) ? lua_gettop(l) + 1 + index
: index;
}
@ -79,9 +78,11 @@ int absindex(lua_State *l, int index) throw() {
// Just like getfield(), only without calling metamethods (or throwing random
// exceptions)
inline void rawgetfield(lua_State *l, int index,
const char *k) throw(std::bad_alloc) {
const char *k) {
index = absindex(l, index);
if (not lua_checkstack(l, 1)) throw std::bad_alloc();
if (lua_checkstack(l, 1) == 0) {
throw std::bad_alloc();
}
lua_pushstring(l, k);
lua_rawget(l, index);
@ -90,9 +91,11 @@ inline void rawgetfield(lua_State *l, int index,
// Just like setfield(), only without calling metamethods (or throwing random
// exceptions)
inline void rawsetfield(lua_State *l, int index,
const char *k) throw(std::bad_alloc) {
const char *k) {
index = absindex(l, index);
if (not lua_checkstack(l, 2)) throw std::bad_alloc();
if (lua_checkstack(l, 2) == 0) {
throw std::bad_alloc();
}
lua_pushstring(l, k);
lua_insert(l, -2);
@ -103,12 +106,11 @@ int closure_trampoline(lua_State *l) {
lua_checkstack(l, 2);
rawgetfield(l, REGISTRYINDEX, this_cpp_object);
assert(lua_islightuserdata(l, -1));
state *L = static_cast<state *>(lua_touserdata(l, -1));
auto *L = static_cast<state *>(lua_touserdata(l, -1));
lua_pop(l, 1);
try {
cpp_function *fn =
static_cast<cpp_function *>(L->touserdata(lua_upvalueindex(1)));
auto *fn = static_cast<cpp_function *>(L->touserdata(lua_upvalueindex(1)));
assert(fn);
return (*fn)(L);
} catch (lua::exception &e) {
@ -137,11 +139,13 @@ int closure_trampoline(lua_State *l) {
* execute everything in protected mode).
*/
int panic_throw(lua_State *l) {
if (not lua_checkstack(l, 1)) throw std::bad_alloc();
if (lua_checkstack(l, 1) == 0) {
throw std::bad_alloc();
}
rawgetfield(l, REGISTRYINDEX, this_cpp_object);
assert(lua_islightuserdata(l, -1));
state *L = static_cast<state *>(lua_touserdata(l, -1));
auto *L = static_cast<state *>(lua_touserdata(l, -1));
lua_pop(l, 1);
throw lua::exception(L);
@ -186,7 +190,7 @@ int safe_next_trampoline(lua_State *l) {
int r = lua_next(l, 1);
lua_checkstack(l, 1);
lua_pushinteger(l, r);
return r ? 3 : 1;
return r != 0 ? 3 : 1;
}
} // namespace
@ -210,8 +214,10 @@ exception::exception(state *l) : std::runtime_error(get_error_msg(l)), L(l) {
L->pop(1);
}
exception::~exception() throw() {
if (not L) return;
exception::~exception() {
if (L == nullptr) {
return;
}
L->checkstack(1);
L->rawgetfield(REGISTRYINDEX, lua_exception_namespace);
@ -220,9 +226,10 @@ exception::~exception() throw() {
}
void exception::push_lua_error(state *l) {
if (l != L)
if (l != L) {
throw std::runtime_error(
"Cannot transfer exceptions between different lua contexts");
}
l->checkstack(2);
l->rawgetfield(REGISTRYINDEX, lua_exception_namespace);
@ -231,9 +238,9 @@ void exception::push_lua_error(state *l) {
}
state::state() {
if (lua_State *l = luaL_newstate())
if (lua_State *l = luaL_newstate()) {
cobj.reset(l, &lua_close);
else {
} else {
// docs say this can happen only in case of a memory allocation error
throw std::bad_alloc();
}
@ -274,7 +281,9 @@ state::state() {
void state::call(int nargs, int nresults, int errfunc) {
int r = lua_pcall(cobj.get(), nargs, nresults, errfunc);
if (r == 0) return;
if (r == 0) {
return;
}
if (r == LUA_ERRMEM) {
// memory allocation error, cross your fingers
@ -286,8 +295,7 @@ void state::call(int nargs, int nresults, int errfunc) {
if (getmetatable(-2)) {
if (rawequal(-1, -2)) {
// it's a C++ exception, rethrow it
std::exception_ptr *ptr =
static_cast<std::exception_ptr *>(touserdata(-3));
auto *ptr = static_cast<std::exception_ptr *>(touserdata(-3));
assert(ptr);
/*
@ -295,21 +303,23 @@ void state::call(int nargs, int nresults, int errfunc) {
* exception will be collected by lua's GC
*/
std::exception_ptr t(*ptr);
ptr = NULL;
ptr = nullptr;
pop(3);
std::rethrow_exception(t);
}
pop(2);
}
// it's a lua exception, wrap it
if (r == LUA_ERRERR)
if (r == LUA_ERRERR) {
throw lua::errfunc_error(this);
else
throw lua::exception(this);
}
{ throw lua::exception(this); }
}
void state::checkstack(int extra) throw(std::bad_alloc) {
if (not lua_checkstack(cobj.get(), extra)) throw std::bad_alloc();
void state::checkstack(int extra) {
if (lua_checkstack(cobj.get(), extra) == 0) {
throw std::bad_alloc();
}
}
void state::concat(int n) {
@ -322,7 +332,9 @@ void state::concat(int n) {
bool state::equal(int index1, int index2) {
// avoid pcall overhead in trivial cases
if (rawequal(index1, index2)) return true;
if (rawequal(index1, index2)) {
return true;
}
return safe_compare(&safe_compare_trampoline<lua_equal>, index1, index2);
}
@ -371,9 +383,7 @@ bool state::lessthan(int index1, int index2) {
return safe_compare(&safe_compare_trampoline<&lua_lessthan>, index1, index2);
}
void state::loadfile(const char *filename) throw(lua::syntax_error,
lua::file_error,
std::bad_alloc) {
void state::loadfile(const char *filename) {
switch (luaL_loadfile(cobj.get(), filename)) {
case 0:
return;
@ -388,7 +398,7 @@ void state::loadfile(const char *filename) throw(lua::syntax_error,
}
}
void state::loadstring(const char *s) throw(lua::syntax_error, std::bad_alloc) {
void state::loadstring(const char *s) {
switch (luaL_loadstring(cobj.get(), s)) {
case 0:
return;
@ -413,7 +423,7 @@ bool state::next(int index) {
assert(isnumber(-1));
int r = tointeger(-1);
pop();
return r;
return r != 0;
}
void state::pushclosure(const cpp_function &fn, int n) {
@ -427,17 +437,19 @@ void state::pushclosure(const cpp_function &fn, int n) {
lua_pushcclosure(cobj.get(), &closure_trampoline, n + 1);
}
void state::rawgetfield(int index, const char *k) throw(std::bad_alloc) {
void state::rawgetfield(int index, const char *k) {
lua::rawgetfield(cobj.get(), index, k);
}
void state::rawsetfield(int index, const char *k) throw(std::bad_alloc) {
void state::rawsetfield(int index, const char *k) {
lua::rawsetfield(cobj.get(), index, k);
}
bool state::safe_compare(lua_CFunction trampoline, int index1, int index2) {
// if one of the indexes is invalid, return false
if (isnone(index1) || isnone(index2)) return false;
if (isnone(index1) || isnone(index2)) {
return false;
}
// convert relative indexes into absolute
index1 = absindex(index1);
@ -451,7 +463,7 @@ bool state::safe_compare(lua_CFunction trampoline, int index1, int index2) {
assert(isnumber(-1));
int r = tointeger(-1);
pop();
return r;
return r != 0;
}
void state::setfield(int index, const char *k) {
@ -485,10 +497,12 @@ void state::settable(int index) {
call(3, 0, 0);
}
std::string state::tostring(int index) throw(lua::not_string_error) {
std::string state::tostring(int index) {
size_t len;
const char *str = lua_tolstring(cobj.get(), index, &len);
if (not str) throw not_string_error();
if (str == nullptr) {
throw not_string_error();
}
return std::string(str, len);
}
} // namespace lua

View File

@ -91,11 +91,11 @@ class exception : public std::runtime_error {
public:
exception(exception &&other)
: std::runtime_error(std::move(other)), L(other.L), key(other.key) {
other.L = NULL;
other.L = nullptr;
}
explicit exception(state *l);
virtual ~exception() throw();
virtual ~exception();
void push_lua_error(state *l);
};
@ -246,7 +246,7 @@ class state : private std::mutex {
// type b, throw only on memory allocation errors
// checkstack correctly throws bad_alloc, because lua_checkstack kindly
// informs us of that sitution
void checkstack(int extra) throw(std::bad_alloc);
void checkstack(int extra);
const char *gsub(const char *s, const char *p, const char *r) {
return luaL_gsub(cobj.get(), s, p, r);
}
@ -266,12 +266,12 @@ class state : private std::mutex {
void pushstring(const std::string &s) {
lua_pushlstring(cobj.get(), s.c_str(), s.size());
}
void rawgetfield(int index, const char *k) throw(std::bad_alloc);
void rawgetfield(int index, const char *k);
void rawset(int index) { lua_rawset(cobj.get(), index); }
void rawsetfield(int index, const char *k) throw(std::bad_alloc);
void rawsetfield(int index, const char *k);
int ref(int t) { return luaL_ref(cobj.get(), t); }
// len recieves length, if not null. Returned value may contain '\0'
const char *tocstring(int index, size_t *len = NULL) {
const char *tocstring(int index, size_t *len = nullptr) {
return lua_tolstring(cobj.get(), index, len);
}
// Don't use pushclosure() to create a __gc function. The problem is that lua
@ -294,9 +294,8 @@ class state : private std::mutex {
void getglobal(const char *name);
void gettable(int index);
bool lessthan(int index1, int index2);
void loadfile(const char *filename) throw(lua::syntax_error, lua::file_error,
std::bad_alloc);
void loadstring(const char *s) throw(lua::syntax_error, std::bad_alloc);
void loadfile(const char *filename);
void loadstring(const char *s);
bool next(int index);
// register is a reserved word :/
void register_fn(const char *name, const cpp_function &f) {
@ -306,10 +305,10 @@ class state : private std::mutex {
void setfield(int index, const char *k);
void setglobal(const char *name);
void settable(int index);
// lua_tostring uses NULL to indicate conversion error, since there is no such
// thing as a NULL std::string, we throw an exception. Returned value may
// lua_tostring uses nullptr to indicate conversion error, since there is no such
// thing as a nullptr std::string, we throw an exception. Returned value may
// contain '\0'
std::string tostring(int index) throw(lua::not_string_error);
std::string tostring(int index);
// allocate a new lua userdata of appropriate size, and create a object in it
// pushes the userdata on stack and returns the pointer
template <typename T, typename... Args>
@ -344,23 +343,23 @@ class stack_sentry {
const stack_sentry &operator=(const stack_sentry &) = delete;
public:
explicit stack_sentry(state &l, int n_ = 0) throw()
explicit stack_sentry(state &l, int n_ = 0)
: L(&l), n(l.gettop() + n_) {
assert(n >= 0);
}
~stack_sentry() throw() {
~stack_sentry() {
assert(L->gettop() >= n);
L->settop(n);
}
void operator++() throw() { ++n; }
void operator--() throw() {
void operator++() { ++n; }
void operator--() {
--n;
assert(n >= 0);
}
void operator+=(int n_) throw() { n += n_; }
void operator-=(int n_) throw() {
void operator+=(int n_) { n += n_; }
void operator-=(int n_) {
n -= n_;
assert(n >= 0);
}

View File

@ -36,13 +36,13 @@
#include "logging.h"
#include "text_object.h"
#include <errno.h>
#include <inttypes.h>
#include <limits.h>
#include <cerrno>
#include <cinttypes>
#include <climits>
#include <cstdio>
#include <cstring>
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/stat.h>
@ -53,6 +53,7 @@
#include <termios.h>
#include <cmath>
#include <memory>
#include <mutex>
#include <sstream>
@ -81,7 +82,9 @@ struct local_mail_s {
std::pair<std::string, bool> priv::current_mail_spool_setting::do_convert(
lua::state &l, int index) {
auto ret = Base::do_convert(l, index);
if (ret.second) ret.first = variable_substitute(ret.first);
if (ret.second) {
ret.first = variable_substitute(ret.first);
}
return ret;
}
@ -93,11 +96,11 @@ enum { DEFAULT_MAIL_INTERVAL = 300 /*seconds*/ };
enum { MP_USER, MP_PASS, MP_FOLDER, MP_COMMAND, MP_HOST, MP_PORT };
struct mail_result {
unsigned long unseen;
unsigned long used;
unsigned long messages;
unsigned long unseen{0};
unsigned long used{0};
unsigned long messages{0};
mail_result() : unseen(0), used(0), messages(0) {}
mail_result() = default;
};
class mail_cb
@ -114,7 +117,7 @@ class mail_cb
uint16_t retries;
void resolve_host() {
struct addrinfo hints;
struct addrinfo hints {};
char portbuf[8];
memset(&hints, 0, sizeof(struct addrinfo));
@ -123,13 +126,14 @@ class mail_cb
hints.ai_protocol = IPPROTO_TCP;
snprintf(portbuf, 8, "%" SCNu16, get<MP_PORT>());
if (int res = getaddrinfo(get<MP_HOST>().c_str(), portbuf, &hints, &ai))
if (int res = getaddrinfo(get<MP_HOST>().c_str(), portbuf, &hints, &ai)) {
throw std::runtime_error(std::string("IMAP getaddrinfo: ") +
gai_strerror(res));
}
}
int connect() {
for (struct addrinfo *rp = ai; rp != NULL; rp = rp->ai_next) {
for (struct addrinfo *rp = ai; rp != nullptr; rp = rp->ai_next) {
int sockfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sockfd == -1) {
continue;
@ -142,8 +146,8 @@ class mail_cb
throw std::runtime_error("Unable to connect to mail server");
}
virtual void merge(callback_base &&other) {
mail_cb &&o = dynamic_cast<mail_cb &&>(other);
void merge(callback_base &&other) override {
auto &&o = dynamic_cast<mail_cb &&>(other);
if (retries < o.retries) {
retries = o.retries;
fail = 0;
@ -154,30 +158,32 @@ class mail_cb
mail_cb(uint32_t period, const Tuple &tuple, uint16_t retries_)
: Base(period, false, tuple, true),
ai(NULL),
ai(nullptr),
fail(0),
retries(retries_) {}
~mail_cb() {
if (ai) freeaddrinfo(ai);
~mail_cb() override {
if (ai != nullptr) {
freeaddrinfo(ai);
}
}
};
struct mail_param_ex : public mail_cb::Tuple {
uint16_t retries;
uint32_t period;
uint16_t retries{0};
uint32_t period{1};
mail_param_ex() : retries(0), period(1) {}
mail_param_ex() = default;
};
class imap_cb : public mail_cb {
typedef mail_cb Base;
using Base = mail_cb;
void check_status(char *recvbuf);
void unseen_command(unsigned long old_unseen, unsigned long old_messages);
protected:
virtual void work();
void work() override;
public:
imap_cb(uint32_t period, const Tuple &tuple, uint16_t retries_)
@ -185,10 +191,10 @@ class imap_cb : public mail_cb {
};
class pop3_cb : public mail_cb {
typedef mail_cb Base;
using Base = mail_cb;
protected:
virtual void work();
void work() override;
public:
pop3_cb(uint32_t period, const Tuple &tuple, uint16_t retries_)
@ -199,9 +205,9 @@ struct mail_param_ex *global_mail;
} // namespace
static void update_mail_count(struct local_mail_s *mail) {
struct stat st;
struct stat st {};
if (mail == NULL) {
if (mail == nullptr) {
return;
}
@ -210,18 +216,17 @@ static void update_mail_count(struct local_mail_s *mail) {
/* don't check mail so often (9.5s is minimum interval) */
if (current_update_time - mail->last_update < 9.5) {
return;
} else {
mail->last_update = current_update_time;
}
mail->last_update = current_update_time;
if (stat(mail->mbox, &st)) {
static int rep = 0;
if (stat(mail->mbox, &st) != 0) {
static int rep = 0;
if (!rep) {
NORM_ERR("can't stat %s: %s", mail->mbox, strerror(errno));
rep = 1;
}
return;
if (rep == 0) {
NORM_ERR("can't stat %s: %s", mail->mbox, strerror(errno));
rep = 1;
}
return;
}
#if HAVE_DIRENT_H
/* maildir format */
@ -237,8 +242,9 @@ static void update_mail_count(struct local_mail_s *mail) {
mail->forwarded_mail_count = mail->unforwarded_mail_count = 0;
mail->replied_mail_count = mail->unreplied_mail_count = 0;
mail->draft_mail_count = mail->trashed_mail_count = 0;
dirname = (char *)malloc(sizeof(char) * (strlen(mail->mbox) + 5));
if (!dirname) {
dirname =
static_cast<char *>(malloc(sizeof(char) * (strlen(mail->mbox) + 5)));
if (dirname == nullptr) {
NORM_ERR("malloc");
return;
}
@ -248,46 +254,49 @@ static void update_mail_count(struct local_mail_s *mail) {
strcat(dirname, "cur");
dir = opendir(dirname);
if (!dir) {
if (dir == nullptr) {
NORM_ERR("cannot open directory");
free(dirname);
return;
}
dirent = readdir(dir);
while (dirent) {
while (dirent != nullptr) {
/* . and .. are skipped */
if (dirent->d_name[0] != '.') {
mail->mail_count++;
mailflags =
(char *)malloc(sizeof(char) * strlen(strrchr(dirent->d_name, ',')));
if (!mailflags) {
mailflags = static_cast<char *>(
malloc(sizeof(char) * strlen(strrchr(dirent->d_name, ','))));
if (mailflags == nullptr) {
NORM_ERR("malloc");
free(dirname);
return;
}
strcpy(mailflags, strrchr(dirent->d_name, ','));
if (!strchr(mailflags, 'T')) { /* The message is not in the trash */
if (strchr(mailflags, 'S')) { /*The message has been seen */
if (strchr(mailflags, 'T') ==
nullptr) { /* The message is not in the trash */
if (strchr(mailflags, 'S') !=
nullptr) { /*The message has been seen */
mail->seen_mail_count++;
} else {
mail->unseen_mail_count++;
}
if (strchr(mailflags, 'F')) { /*The message was flagged */
if (strchr(mailflags, 'F') != nullptr) { /*The message was flagged */
mail->flagged_mail_count++;
} else {
mail->unflagged_mail_count++;
}
if (strchr(mailflags, 'P')) { /*The message was forwarded */
if (strchr(mailflags, 'P') !=
nullptr) { /*The message was forwarded */
mail->forwarded_mail_count++;
} else {
mail->unforwarded_mail_count++;
}
if (strchr(mailflags, 'R')) { /*The message was replied */
if (strchr(mailflags, 'R') != nullptr) { /*The message was replied */
mail->replied_mail_count++;
} else {
mail->unreplied_mail_count++;
}
if (strchr(mailflags, 'D')) { /*The message is a draft */
if (strchr(mailflags, 'D') != nullptr) { /*The message is a draft */
mail->draft_mail_count++;
}
} else {
@ -303,13 +312,13 @@ static void update_mail_count(struct local_mail_s *mail) {
strcat(dirname, "new");
dir = opendir(dirname);
if (!dir) {
if (dir == nullptr) {
NORM_ERR("cannot open directory");
free(dirname);
return;
}
dirent = readdir(dir);
while (dirent) {
while (dirent != nullptr) {
/* . and .. are skipped */
if (dirent->d_name[0] != '.') {
mail->new_mail_count++;
@ -344,17 +353,17 @@ static void update_mail_count(struct local_mail_s *mail) {
mail->draft_mail_count = mail->trashed_mail_count = -1;
fp = open_file(mail->mbox, &rep);
if (!fp) {
if (fp == nullptr) {
return;
}
/* NOTE: adds mail as new if there isn't Status-field at all */
while (!feof(fp)) {
while (feof(fp) == 0) {
char buf[128];
int was_new = 0;
if (fgets(buf, 128, fp) == NULL) {
if (fgets(buf, 128, fp) == nullptr) {
break;
}
@ -372,16 +381,16 @@ static void update_mail_count(struct local_mail_s *mail) {
}
} else {
if (reading_status == 1 && strncmp(buf, "X-Mozilla-Status:", 17) == 0) {
int xms = strtol(buf + 17, NULL, 16);
int xms = strtol(buf + 17, nullptr, 16);
/* check that mail isn't marked for deletion */
if (xms & 0x0008) {
if ((xms & 0x0008) != 0) {
mail->trashed_mail_count++;
reading_status = 0;
/* Don't check whether the trashed email is unread */
continue;
}
/* check that mail isn't already read */
if (!(xms & 0x0001)) {
if ((xms & 0x0001) == 0) {
mail->new_mail_count++;
was_new = 1;
}
@ -392,7 +401,7 @@ static void update_mail_count(struct local_mail_s *mail) {
}
if (reading_status == 1 && strncmp(buf, "Status:", 7) == 0) {
/* check that mail isn't already read */
if (strchr(buf + 7, 'R') == NULL) {
if (strchr(buf + 7, 'R') == nullptr) {
mail->new_mail_count++;
was_new = 1;
}
@ -402,11 +411,13 @@ static void update_mail_count(struct local_mail_s *mail) {
}
if (reading_status >= 1 && strncmp(buf, "X-Status:", 9) == 0) {
/* check that mail isn't marked for deletion */
if (strchr(buf + 9, 'D') != NULL) {
if (strchr(buf + 9, 'D') != nullptr) {
mail->trashed_mail_count++;
/* If the mail was previously detected as new,
subtract it from the new mail count */
if (was_new) mail->new_mail_count--;
if (was_new != 0) {
mail->new_mail_count--;
}
}
reading_status = 0;
@ -415,14 +426,16 @@ static void update_mail_count(struct local_mail_s *mail) {
}
/* skip until \n */
while (strchr(buf, '\n') == NULL && !feof(fp)) {
if (!fgets(buf, 128, fp)) break;
while (strchr(buf, '\n') == nullptr && (feof(fp) == 0)) {
if (fgets(buf, 128, fp) == nullptr) {
break;
}
}
}
fclose(fp);
if (reading_status) {
if (reading_status != 0) {
mail->new_mail_count++;
}
@ -436,7 +449,7 @@ void parse_local_mail_args(struct text_object *obj, const char *arg) {
char mbox[256];
struct local_mail_s *locmail;
if (!arg) {
if (arg == nullptr) {
n1 = 9.5;
strncpy(mbox, current_mail_spool.get(*state).c_str(), sizeof(mbox));
} else {
@ -448,7 +461,8 @@ void parse_local_mail_args(struct text_object *obj, const char *arg) {
std::string dst = variable_substitute(mbox);
locmail = (struct local_mail_s *)malloc(sizeof(struct local_mail_s));
locmail =
static_cast<struct local_mail_s *>(malloc(sizeof(struct local_mail_s)));
memset(locmail, 0, sizeof(struct local_mail_s));
locmail->mbox = strndup(dst.c_str(), text_buffer_size.get(*state));
locmail->interval = n1;
@ -477,9 +491,11 @@ PRINT_MAILS_GENERATOR(draft_)
PRINT_MAILS_GENERATOR(trashed_)
void free_local_mails(struct text_object *obj) {
struct local_mail_s *locmail = (struct local_mail_s *)obj->data.opaque;
auto *locmail = static_cast<struct local_mail_s *>(obj->data.opaque);
if (!locmail) return;
if (locmail == nullptr) {
return;
}
free_and_zero(locmail->mbox);
free_and_zero(obj->data.opaque);
@ -489,7 +505,7 @@ void free_local_mails(struct text_object *obj) {
namespace {
enum mail_type { POP3_TYPE, IMAP_TYPE };
}
} // namespace
std::unique_ptr<mail_param_ex> parse_mail_args(mail_type type,
const char *arg) {
@ -513,26 +529,28 @@ std::unique_ptr<mail_param_ex> parse_mail_args(mail_type type,
// see if password needs prompting
if (pass[0] == '*' && pass[1] == '\0') {
int fp = fileno(stdin);
struct termios term;
struct termios term {};
tcgetattr(fp, &term);
term.c_lflag &= ~ECHO;
tcsetattr(fp, TCSANOW, &term);
printf("Enter mailbox password (%s@%s): ", user, host);
if (scanf("%128s", pass) != 1) pass[0] = 0;
if (scanf("%128s", pass) != 1) {
pass[0] = 0;
}
printf("\n");
term.c_lflag |= ECHO;
tcsetattr(fp, TCSANOW, &term);
}
mail.reset(new mail_param_ex);
mail = std::make_unique<mail_param_ex>();
get<MP_HOST>(*mail) = host;
get<MP_USER>(*mail) = user;
get<MP_PASS>(*mail) = pass;
// now we check for optional args
tmp = (char *)strstr(arg, "-r ");
if (tmp) {
tmp = const_cast<char *>(strstr(arg, "-r "));
if (tmp != nullptr) {
tmp += 3;
sscanf(tmp, "%" SCNu16, &mail->retries);
} else {
@ -540,15 +558,15 @@ std::unique_ptr<mail_param_ex> parse_mail_args(mail_type type,
}
float interval = DEFAULT_MAIL_INTERVAL;
tmp = (char *)strstr(arg, "-i ");
if (tmp) {
tmp = const_cast<char *>(strstr(arg, "-i "));
if (tmp != nullptr) {
tmp += 3;
sscanf(tmp, "%f", &interval);
}
mail->period = std::max(lround(interval / active_update_interval()), 1l);
tmp = (char *)strstr(arg, "-p ");
if (tmp) {
tmp = const_cast<char *>(strstr(arg, "-p "));
if (tmp != nullptr) {
tmp += 3;
sscanf(tmp, "%" SCNu16, &get<MP_PORT>(*mail));
} else {
@ -559,12 +577,12 @@ std::unique_ptr<mail_param_ex> parse_mail_args(mail_type type,
}
}
if (type == IMAP_TYPE) {
tmp = (char *)strstr(arg, "-f ");
if (tmp) {
tmp = const_cast<char *>(strstr(arg, "-f "));
if (tmp != nullptr) {
int len = 0;
tmp += 3;
if (tmp[0] == '\'') {
len = (char *)strstr(tmp + 1, "'") - tmp - 1;
len = strstr(tmp + 1, "'") - tmp - 1;
tmp++;
}
get<MP_FOLDER>(*mail).assign(tmp, len);
@ -572,13 +590,13 @@ std::unique_ptr<mail_param_ex> parse_mail_args(mail_type type,
get<MP_FOLDER>(*mail) = "INBOX"; // default imap inbox
}
}
tmp = (char *)strstr(arg, "-e ");
if (tmp) {
tmp = const_cast<char *>(strstr(arg, "-e "));
if (tmp != nullptr) {
int len = 0;
tmp += 3;
if (tmp[0] == '\'') {
len = (char *)strstr(tmp + 1, "'") - tmp - 1;
len = strstr(tmp + 1, "'") - tmp - 1;
}
get<MP_COMMAND>(*mail).assign(tmp + 1, len);
}
@ -589,8 +607,8 @@ std::unique_ptr<mail_param_ex> parse_mail_args(mail_type type,
void parse_imap_mail_args(struct text_object *obj, const char *arg) {
static int rep = 0;
if (!arg) {
if (!global_mail && !rep) {
if (arg == nullptr) {
if ((global_mail == nullptr) && (rep == 0)) {
// something is wrong, warn once then stop
NORM_ERR(
"There's a problem with your mail settings. "
@ -610,8 +628,8 @@ void parse_imap_mail_args(struct text_object *obj, const char *arg) {
void parse_pop3_mail_args(struct text_object *obj, const char *arg) {
static int rep = 0;
if (!arg) {
if (!global_mail && !rep) {
if (arg == nullptr) {
if ((global_mail == nullptr) && (rep == 0)) {
// something is wrong, warn once then stop
NORM_ERR(
"There's a problem with your mail settings. "
@ -630,29 +648,31 @@ void parse_pop3_mail_args(struct text_object *obj, const char *arg) {
namespace {
class mail_setting : public conky::simple_config_setting<std::string> {
typedef conky::simple_config_setting<std::string> Base;
using Base = conky::simple_config_setting<std::string>;
mail_type type;
protected:
virtual void lua_setter(lua::state &l, bool init) {
void lua_setter(lua::state &l, bool init) override {
lua::stack_sentry s(l, -2);
Base::lua_setter(l, init);
if (init && !global_mail) {
if (init && (global_mail == nullptr)) {
const std::string &t = do_convert(l, -1).first;
if (t.size()) global_mail = parse_mail_args(type, t.c_str()).release();
if (static_cast<unsigned int>(!t.empty()) != 0u) {
global_mail = parse_mail_args(type, t.c_str()).release();
}
}
++s;
}
virtual void cleanup(lua::state &l) {
void cleanup(lua::state &l) override {
lua::stack_sentry s(l, -1);
delete global_mail;
global_mail = NULL;
global_mail = nullptr;
l.pop();
}
@ -667,24 +687,27 @@ mail_setting pop3("pop3", POP3_TYPE);
} // namespace
void free_mail_obj(struct text_object *obj) {
if (!obj->data.opaque) return;
if (obj->data.opaque == nullptr) {
return;
}
if (obj->data.opaque != global_mail) {
mail_param_ex *mail = static_cast<mail_param_ex *>(obj->data.opaque);
auto *mail = static_cast<mail_param_ex *>(obj->data.opaque);
delete mail;
obj->data.opaque = 0;
obj->data.opaque = nullptr;
}
}
static void command(int sockfd, const std::string &cmd, char *response,
const char *verify) {
struct timeval fetchtimeout;
struct timeval fetchtimeout {};
fd_set fdset;
ssize_t total = 0;
int numbytes = 0;
if (send(sockfd, cmd.c_str(), cmd.length(), 0) == -1)
if (send(sockfd, cmd.c_str(), cmd.length(), 0) == -1) {
throw std::runtime_error("send: " + strerror_r(errno));
}
DBGP2("command() command: %s", cmd.c_str());
while (1) {
@ -693,37 +716,44 @@ static void command(int sockfd, const std::string &cmd, char *response,
FD_ZERO(&fdset);
FD_SET(sockfd, &fdset);
if (select(sockfd + 1, &fdset, NULL, NULL, &fetchtimeout) == 0)
if (select(sockfd + 1, &fdset, nullptr, nullptr, &fetchtimeout) == 0) {
throw std::runtime_error("select: read timeout");
}
if ((numbytes =
recv(sockfd, response + total, MAXDATASIZE - 1 - total, 0)) == -1)
if ((numbytes = recv(sockfd, response + total, MAXDATASIZE - 1 - total,
0)) == -1) {
throw std::runtime_error("recv: " + strerror_r(errno));
}
total += numbytes;
response[total] = '\0';
DBGP2("command() received: %s", response);
if (strstr(response, verify) != NULL) return;
if (strstr(response, verify) != nullptr) {
return;
}
if (numbytes == 0)
if (numbytes == 0) {
throw std::runtime_error("Unexpected response from server");
}
}
}
void imap_cb::check_status(char *recvbuf) {
char *reply;
reply = (char *)strstr(recvbuf, " (MESSAGES ");
if (!reply || strlen(reply) < 2)
reply = strstr(recvbuf, " (MESSAGES ");
if ((reply == nullptr) || strlen(reply) < 2) {
std::runtime_error("Unexpected response from server");
}
reply += 2;
*strchr(reply, ')') = '\0';
std::lock_guard<std::mutex> lock(result_mutex);
if (sscanf(reply, "MESSAGES %lu UNSEEN %lu", &result.messages,
&result.unseen) != 2)
&result.unseen) != 2) {
throw std::runtime_error(std::string("Error parsing response: ") + recvbuf);
}
}
void imap_cb::unseen_command(unsigned long old_unseen,
@ -745,11 +775,13 @@ void imap_cb::work() {
bool has_idle = false;
while (fail < retries) {
struct timeval fetchtimeout;
struct timeval fetchtimeout {};
int res;
fd_set fdset;
if (not ai) resolve_host();
if (ai == nullptr) {
resolve_host();
}
try {
sockfd = connect();
@ -757,7 +789,9 @@ void imap_cb::work() {
command(sockfd, "", recvbuf, "* OK");
command(sockfd, "abc CAPABILITY\r\n", recvbuf, "abc OK");
if (strstr(recvbuf, " IDLE ") != NULL) has_idle = true;
if (strstr(recvbuf, " IDLE ") != nullptr) {
has_idle = true;
}
std::ostringstream str;
str << "a1 login " << get<MP_USER>() << " {" << get<MP_PASS>().length()
@ -802,7 +836,7 @@ void imap_cb::work() {
FD_ZERO(&fdset);
FD_SET(sockfd, &fdset);
FD_SET(donefd(), &fdset);
res = select(std::max(sockfd, donefd()) + 1, &fdset, NULL, NULL,
res = select(std::max(sockfd, donefd()) + 1, &fdset, nullptr, nullptr,
&fetchtimeout);
if ((res == -1 && errno == EINTR) || FD_ISSET(donefd(), &fdset)) {
try {
@ -812,11 +846,14 @@ void imap_cb::work() {
}
close(sockfd);
return;
} else if (res > 0) {
if ((numbytes = recv(sockfd, recvbuf, MAXDATASIZE - 1, 0)) == -1)
}
if (res > 0) {
if ((numbytes = recv(sockfd, recvbuf, MAXDATASIZE - 1, 0)) == -1) {
throw std::runtime_error("recv idling");
} else
}
} else {
throw std::runtime_error("");
}
recvbuf[numbytes] = '\0';
DBGP2("imap_thread() received: %s", recvbuf);
@ -824,11 +861,12 @@ void imap_cb::work() {
bool force_check = 0;
if (strlen(recvbuf) > 2) {
char *buf = recvbuf;
buf = (char *)strstr(buf, "EXISTS");
while (buf && strlen(buf) > 1 && strstr(buf + 1, "EXISTS")) {
buf = (char *)strstr(buf + 1, "EXISTS");
buf = strstr(buf, "EXISTS");
while ((buf != nullptr) && strlen(buf) > 1 &&
(strstr(buf + 1, "EXISTS") != nullptr)) {
buf = strstr(buf + 1, "EXISTS");
}
if (buf) {
if (buf != nullptr) {
// back up until we reach '*'
while (buf >= recvbuf && buf[0] != '*') {
buf--;
@ -842,11 +880,12 @@ void imap_cb::work() {
}
}
buf = recvbuf;
buf = (char *)strstr(buf, "RECENT");
while (buf && strlen(buf) > 1 && strstr(buf + 1, "RECENT")) {
buf = (char *)strstr(buf + 1, "RECENT");
buf = strstr(buf, "RECENT");
while ((buf != nullptr) && strlen(buf) > 1 &&
(strstr(buf + 1, "RECENT") != nullptr)) {
buf = strstr(buf + 1, "RECENT");
}
if (buf) {
if (buf != nullptr) {
// back up until we reach '*'
while (buf >= recvbuf && buf[0] != '*') {
buf--;
@ -857,7 +896,7 @@ void imap_cb::work() {
}
}
/* check if we got a BYE from server */
if (strstr(recvbuf, "* BYE")) {
if (strstr(recvbuf, "* BYE") != nullptr) {
// need to re-connect
throw std::runtime_error("");
}
@ -866,7 +905,7 @@ void imap_cb::work() {
* check if we got a FETCH from server, recent was
* something other than 0, or we had a timeout
*/
if (recent > 0 || strstr(recvbuf, " FETCH ") ||
if (recent > 0 || (strstr(recvbuf, " FETCH ") != nullptr) ||
fetchtimeout.tv_sec == 0 || force_check) {
// re-check messages and unseen
command(sockfd, "DONE\r\n", recvbuf, "a5 OK");
@ -886,27 +925,34 @@ void imap_cb::work() {
old_messages = result.messages;
}
} catch (std::runtime_error &e) {
if (sockfd != -1) close(sockfd);
if (sockfd != -1) {
close(sockfd);
}
freeaddrinfo(ai);
ai = NULL;
ai = nullptr;
++fail;
if (*e.what())
if (*e.what() != 0) {
NORM_ERR("Error while communicating with IMAP server: %s", e.what());
}
NORM_ERR("Trying IMAP connection again for %s@%s (try %u/%u)",
get<MP_USER>().c_str(), get<MP_HOST>().c_str(), fail + 1,
retries);
sleep(fail); /* sleep more for the more failures we have */
}
if (is_done()) return;
if (is_done()) {
return;
}
}
}
void print_imap_unseen(struct text_object *obj, char *p, int p_max_size) {
struct mail_param_ex *mail = (struct mail_param_ex *)obj->data.opaque;
auto *mail = static_cast<struct mail_param_ex *>(obj->data.opaque);
if (!mail) return;
if (mail == nullptr) {
return;
}
auto cb = conky::register_cb<imap_cb>(mail->period, *mail, mail->retries);
@ -914,9 +960,11 @@ void print_imap_unseen(struct text_object *obj, char *p, int p_max_size) {
}
void print_imap_messages(struct text_object *obj, char *p, int p_max_size) {
struct mail_param_ex *mail = (struct mail_param_ex *)obj->data.opaque;
auto *mail = static_cast<struct mail_param_ex *>(obj->data.opaque);
if (!mail) return;
if (mail == nullptr) {
return;
}
auto cb = conky::register_cb<imap_cb>(mail->period, *mail, mail->retries);
@ -930,7 +978,9 @@ void pop3_cb::work() {
unsigned long old_unseen = ULONG_MAX;
while (fail < retries) {
if (not ai) resolve_host();
if (ai == nullptr) {
resolve_host();
}
try {
sockfd = connect();
@ -959,27 +1009,34 @@ void pop3_cb::work() {
old_unseen = result.unseen;
return;
} catch (std::runtime_error &e) {
if (sockfd != -1) close(sockfd);
if (sockfd != -1) {
close(sockfd);
}
freeaddrinfo(ai);
ai = NULL;
ai = nullptr;
++fail;
if (*e.what())
if (*e.what() != 0) {
NORM_ERR("Error while communicating with POP3 server: %s", e.what());
}
NORM_ERR("Trying POP3 connection again for %s@%s (try %u/%u)",
get<MP_USER>().c_str(), get<MP_HOST>().c_str(), fail + 1,
retries);
sleep(fail); /* sleep more for the more failures we have */
}
if (is_done()) return;
if (is_done()) {
return;
}
}
}
void print_pop3_unseen(struct text_object *obj, char *p, int p_max_size) {
struct mail_param_ex *mail = (struct mail_param_ex *)obj->data.opaque;
auto *mail = static_cast<struct mail_param_ex *>(obj->data.opaque);
if (!mail) return;
if (mail == nullptr) {
return;
}
auto cb = conky::register_cb<pop3_cb>(mail->period, *mail, mail->retries);
@ -987,9 +1044,11 @@ void print_pop3_unseen(struct text_object *obj, char *p, int p_max_size) {
}
void print_pop3_used(struct text_object *obj, char *p, int p_max_size) {
struct mail_param_ex *mail = (struct mail_param_ex *)obj->data.opaque;
auto *mail = static_cast<struct mail_param_ex *>(obj->data.opaque);
if (!mail) return;
if (mail == nullptr) {
return;
}
auto cb = conky::register_cb<pop3_cb>(mail->period, *mail, mail->retries);

View File

@ -27,9 +27,9 @@
*
*/
#include <errno.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <cerrno>
#include <memory>
#include "conky.h"
#include "logging.h"
@ -65,8 +65,8 @@ static void mbox_scan(char *args, char *output, size_t max_len) {
int force_rescan = 0;
std::unique_ptr<char[]> buf_(new char[text_buffer_size.get(*state)]);
char *buf = buf_.get();
struct stat statbuf;
struct ring_list *curr = 0, *prev = 0, *startlist = 0;
struct stat statbuf {};
struct ring_list *curr = nullptr, *prev = nullptr, *startlist = nullptr;
FILE *fp;
/* output was set to 1 after malloc'ing in conky.c */
@ -76,10 +76,10 @@ static void mbox_scan(char *args, char *output, size_t max_len) {
output[0] = '\0';
}
if (!args_ok || force_rescan) {
if ((args_ok == 0) || (force_rescan != 0)) {
char *substr = strstr(args, "-n");
if (substr) {
if (substr != nullptr) {
if (sscanf(substr, "-n %i", &print_num_mails) != 1) {
print_num_mails = PRINT_MAILS;
}
@ -91,7 +91,7 @@ static void mbox_scan(char *args, char *output, size_t max_len) {
}
substr = strstr(args, "-t");
if (substr) {
if (substr != nullptr) {
if (sscanf(substr, "-t %i", &time_delay) != 1) {
time_delay = TIME_DELAY;
}
@ -100,7 +100,7 @@ static void mbox_scan(char *args, char *output, size_t max_len) {
}
substr = strstr(args, "-fw");
if (substr) {
if (substr != nullptr) {
if (sscanf(substr, "-fw %i", &from_width) != 1) {
from_width = FROM_WIDTH;
}
@ -109,7 +109,7 @@ static void mbox_scan(char *args, char *output, size_t max_len) {
}
substr = strstr(args, "-sw");
if (substr) {
if (substr != nullptr) {
if (sscanf(substr, "-sw %i", &subject_width) != 1) {
subject_width = SUBJECT_WIDTH;
}
@ -122,16 +122,16 @@ static void mbox_scan(char *args, char *output, size_t max_len) {
strncpy(mbox_mail_spool, args, DEFAULT_TEXT_BUFFER_SIZE);
start = strchr(mbox_mail_spool, '"') + 1;
start[(long)(strrchr(mbox_mail_spool, '"') - start)] = '\0';
start[(strrchr(mbox_mail_spool, '"') - start)] = '\0';
strncpy(mbox_mail_spool, start, DEFAULT_TEXT_BUFFER_SIZE);
} else {
char *copy_args = strndup(args, text_buffer_size.get(*state));
char *tmp = strtok(copy_args, " ");
char *start = tmp;
while (tmp) {
tmp = strtok(NULL, " ");
if (tmp) {
while (tmp != nullptr) {
tmp = strtok(nullptr, " ");
if (tmp != nullptr) {
start = tmp;
}
}
@ -139,33 +139,33 @@ static void mbox_scan(char *args, char *output, size_t max_len) {
free(copy_args);
}
if (strlen(mbox_mail_spool) < 1) {
CRIT_ERR(NULL, NULL,
CRIT_ERR(nullptr, nullptr,
"Usage: ${mboxscan [-n <number of messages to print>] "
"[-fw <from width>] [-sw <subject width>] "
"[-t <delay in sec> mbox]}");
}
/* allowing $MAIL in the config */
if (!strcmp(mbox_mail_spool, "$MAIL")) {
if (strcmp(mbox_mail_spool, "$MAIL") == 0) {
strcpy(mbox_mail_spool, current_mail_spool.get(*state).c_str());
}
if (stat(mbox_mail_spool, &statbuf)) {
CRIT_ERR(NULL, NULL, "can't stat %s: %s", mbox_mail_spool,
if (stat(mbox_mail_spool, &statbuf) != 0) {
CRIT_ERR(nullptr, nullptr, "can't stat %s: %s", mbox_mail_spool,
strerror(errno));
}
args_ok = 1; /* args-computing necessary only once */
}
/* if time_delay not yet reached, then return */
if (current_update_time - last_update < time_delay && !force_rescan) {
if (current_update_time - last_update < time_delay && (force_rescan == 0)) {
return;
}
last_update = current_update_time;
/* mbox still exists? and get stat-infos */
if (stat(mbox_mail_spool, &statbuf)) {
if (stat(mbox_mail_spool, &statbuf) != 0) {
NORM_ERR("can't stat %s: %s", mbox_mail_spool, strerror(errno));
output[0] = '\0'; /* delete any output */
return;
@ -173,7 +173,7 @@ static void mbox_scan(char *args, char *output, size_t max_len) {
/* modification time has not changed, so skip scanning the box */
if (statbuf.st_ctime == last_ctime && statbuf.st_mtime == last_mtime &&
!force_rescan) {
(force_rescan == 0)) {
return;
}
@ -183,9 +183,9 @@ static void mbox_scan(char *args, char *output, size_t max_len) {
/* build up double-linked ring-list to hold data, while scanning down the
* mbox */
for (i = 0; i < print_num_mails; i++) {
curr = (struct ring_list *)malloc(sizeof(struct ring_list));
curr->from = (char *)malloc(from_width + 1);
curr->subject = (char *)malloc(subject_width + 1);
curr = static_cast<struct ring_list *>(malloc(sizeof(struct ring_list)));
curr->from = static_cast<char *>(malloc(from_width + 1));
curr->subject = static_cast<char *>(malloc(subject_width + 1));
curr->from[0] = '\0';
curr->subject[0] = '\0';
@ -204,15 +204,15 @@ static void mbox_scan(char *args, char *output, size_t max_len) {
curr->next = startlist;
/* mbox */
fp = fopen(mbox_mail_spool, "r");
if (!fp) {
fp = fopen(mbox_mail_spool, "re");
if (fp == nullptr) {
return;
}
/* first find a "From " to set it to 0 for header-sarchings */
flag = 1;
while (!feof(fp)) {
if (fgets(buf, text_buffer_size.get(*state), fp) == NULL) {
while (feof(fp) == 0) {
if (fgets(buf, text_buffer_size.get(*state), fp) == nullptr) {
break;
}
@ -220,8 +220,10 @@ static void mbox_scan(char *args, char *output, size_t max_len) {
curr = curr->next;
/* skip until \n */
while (strchr(buf, '\n') == NULL && !feof(fp)) {
if (!fgets(buf, text_buffer_size.get(*state), fp)) break;
while (strchr(buf, '\n') == nullptr && (feof(fp) == 0)) {
if (fgets(buf, text_buffer_size.get(*state), fp) == nullptr) {
break;
}
}
flag = 0; /* in the headers now */
@ -236,8 +238,10 @@ static void mbox_scan(char *args, char *output, size_t max_len) {
/* beyond the headers now (empty line), skip until \n */
/* then search for new mail ("From ") */
while (strchr(buf, '\n') == NULL && !feof(fp)) {
if (!fgets(buf, text_buffer_size.get(*state), fp)) break;
while (strchr(buf, '\n') == nullptr && (feof(fp) == 0)) {
if (fgets(buf, text_buffer_size.get(*state), fp) == nullptr) {
break;
}
}
flag = 1; /* in the body now */
continue;
@ -252,8 +256,10 @@ static void mbox_scan(char *args, char *output, size_t max_len) {
/* (will get current again on new 'From ' finding) */
curr = curr->previous;
/* Skip until \n */
while (strchr(buf, '\n') == NULL && !feof(fp)) {
if (!fgets(buf, text_buffer_size.get(*state), fp)) break;
while (strchr(buf, '\n') == nullptr && (feof(fp) == 0)) {
if (fgets(buf, text_buffer_size.get(*state), fp) == nullptr) {
break;
}
}
continue;
}
@ -272,8 +278,10 @@ static void mbox_scan(char *args, char *output, size_t max_len) {
if (buf[u] == '<' && i > 1) {
curr->from[i] = '\0';
/* skip until \n */
while (strchr(buf, '\n') == NULL && !feof(fp)) {
if (!fgets(buf, text_buffer_size.get(*state), fp)) break;
while (strchr(buf, '\n') == nullptr && (feof(fp) == 0)) {
if (fgets(buf, text_buffer_size.get(*state), fp) == nullptr) {
break;
}
}
break;
}
@ -291,8 +299,10 @@ static void mbox_scan(char *args, char *output, size_t max_len) {
if (i >= from_width) {
curr->from[i] = '\0';
/* skip until \n */
while (strchr(buf, '\n') == NULL && !feof(fp)) {
if (!fgets(buf, text_buffer_size.get(*state), fp)) break;
while (strchr(buf, '\n') == nullptr && (feof(fp) == 0)) {
if (fgets(buf, text_buffer_size.get(*state), fp) == nullptr) {
break;
}
}
break;
}
@ -319,8 +329,10 @@ static void mbox_scan(char *args, char *output, size_t max_len) {
curr->subject[i] = '\0';
/* skip until \n */
while (strchr(buf, '\n') == NULL && !feof(fp)) {
if (!fgets(buf, text_buffer_size.get(*state), fp)) break;
while (strchr(buf, '\n') == nullptr && (feof(fp) == 0)) {
if (fgets(buf, text_buffer_size.get(*state), fp) == nullptr) {
break;
}
}
break;
}
@ -336,7 +348,7 @@ static void mbox_scan(char *args, char *output, size_t max_len) {
output[0] = '\0';
i = print_num_mails;
while (i) {
while (i != 0) {
struct ring_list *tmp;
if (curr->from[0] != '\0') {
if (i != print_num_mails) {
@ -369,11 +381,11 @@ struct mboxscan_data {
void parse_mboxscan_arg(struct text_object *obj, const char *arg) {
struct mboxscan_data *msd;
msd = (mboxscan_data *)malloc(sizeof(struct mboxscan_data));
msd = static_cast<mboxscan_data *>(malloc(sizeof(struct mboxscan_data)));
memset(msd, 0, sizeof(struct mboxscan_data));
msd->args = strndup(arg, text_buffer_size.get(*state));
msd->output = (char *)malloc(text_buffer_size.get(*state));
msd->output = static_cast<char *>(malloc(text_buffer_size.get(*state)));
/* if '1' (in mboxscan.c) then there was SIGUSR1, hmm */
msd->output[0] = 1;
@ -381,18 +393,22 @@ void parse_mboxscan_arg(struct text_object *obj, const char *arg) {
}
void print_mboxscan(struct text_object *obj, char *p, int p_max_size) {
struct mboxscan_data *msd = (mboxscan_data *)obj->data.opaque;
auto *msd = static_cast<mboxscan_data *>(obj->data.opaque);
if (!msd) return;
if (msd == nullptr) {
return;
}
mbox_scan(msd->args, msd->output, text_buffer_size.get(*state));
snprintf(p, p_max_size, "%s", msd->output);
}
void free_mboxscan(struct text_object *obj) {
struct mboxscan_data *msd = (mboxscan_data *)obj->data.opaque;
auto *msd = static_cast<mboxscan_data *>(obj->data.opaque);
if (!msd) return;
if (msd == nullptr) {
return;
}
free_and_zero(msd->args);
free_and_zero(msd->output);
free_and_zero(obj->data.opaque);

View File

@ -139,7 +139,7 @@ void scan_mixer_bar(struct text_object *obj, const char *arg) {
obj->data.i = mixer_init(buf1);
scan_bar(obj, arg + n, 100);
} else {
obj->data.i = mixer_init(NULL);
obj->data.i = mixer_init(nullptr);
scan_bar(obj, arg, 100);
}
}

View File

@ -24,10 +24,10 @@
#include "logging.h"
#include "text_object.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include "update-cb.hh"
@ -48,13 +48,13 @@ struct moc_result {
};
class moc_cb : public conky::callback<moc_result> {
typedef conky::callback<moc_result> Base;
using Base = conky::callback<moc_result>;
protected:
virtual void work();
void work() override;
public:
moc_cb(uint32_t period) : Base(period, false, Tuple()) {}
explicit moc_cb(uint32_t period) : Base(period, false, Tuple()) {}
};
void moc_cb::work() {
@ -62,7 +62,7 @@ void moc_cb::work() {
FILE *fp;
fp = popen("mocp -i", "r");
if (!fp) {
if (fp == nullptr) {
moc.state = "Can't run 'mocp -i'";
} else {
while (1) {
@ -70,32 +70,37 @@ void moc_cb::work() {
char *p;
/* Read a line from the pipe and strip the possible '\n'. */
if (!fgets(line, 100, fp)) break;
if ((p = strrchr(line, '\n'))) *p = '\0';
if (fgets(line, 100, fp) == nullptr) {
break;
}
if ((p = strrchr(line, '\n')) != nullptr) {
*p = '\0';
}
/* Parse infos. */
if (strncmp(line, "State:", 6) == 0)
if (strncmp(line, "State:", 6) == 0) {
moc.state = line + 7;
else if (strncmp(line, "File:", 5) == 0)
} else if (strncmp(line, "File:", 5) == 0) {
moc.file = line + 6;
else if (strncmp(line, "Title:", 6) == 0)
} else if (strncmp(line, "Title:", 6) == 0) {
moc.title = line + 7;
else if (strncmp(line, "Artist:", 7) == 0)
} else if (strncmp(line, "Artist:", 7) == 0) {
moc.artist = line + 8;
else if (strncmp(line, "SongTitle:", 10) == 0)
} else if (strncmp(line, "SongTitle:", 10) == 0) {
moc.song = line + 11;
else if (strncmp(line, "Album:", 6) == 0)
} else if (strncmp(line, "Album:", 6) == 0) {
moc.album = line + 7;
else if (strncmp(line, "TotalTime:", 10) == 0)
} else if (strncmp(line, "TotalTime:", 10) == 0) {
moc.totaltime = line + 11;
else if (strncmp(line, "TimeLeft:", 9) == 0)
} else if (strncmp(line, "TimeLeft:", 9) == 0) {
moc.timeleft = line + 10;
else if (strncmp(line, "CurrentTime:", 12) == 0)
} else if (strncmp(line, "CurrentTime:", 12) == 0) {
moc.curtime = line + 13;
else if (strncmp(line, "Bitrate:", 8) == 0)
} else if (strncmp(line, "Bitrate:", 8) == 0) {
moc.bitrate = line + 9;
else if (strncmp(line, "Rate:", 5) == 0)
} else if (strncmp(line, "Rate:", 5) == 0) {
moc.rate = line + 6;
}
}
}
@ -115,7 +120,7 @@ void moc_cb::work() {
const moc_result &moc = \
conky::register_cb<moc_cb>(period)->get_result_copy(); \
snprintf(p, p_max_size, "%s", \
(moc.type.length() ? moc.type.c_str() : alt)); \
(moc.type.length() ? moc.type.c_str() : (alt))); \
}
MOC_PRINT_GENERATOR(state, "??")

View File

@ -27,13 +27,13 @@
*/
#include "mpd.h"
#include <cmath>
#include <mutex>
#include "conky.h"
#include "libmpdclient.h"
#include "logging.h"
#include "timeinfo.h"
#include "update-cb.hh"
#include <cmath>
#include <mutex>
namespace {
@ -41,10 +41,10 @@ namespace {
bool mpd_environment_host = false;
class mpd_host_setting : public conky::simple_config_setting<std::string> {
typedef conky::simple_config_setting<std::string> Base;
using Base = conky::simple_config_setting<std::string>;
protected:
virtual void lua_setter(lua::state &l, bool init);
void lua_setter(lua::state &l, bool init) override;
public:
mpd_host_setting() : Base("mpd_host", "localhost", false) {}
@ -57,13 +57,16 @@ void mpd_host_setting::lua_setter(lua::state &l, bool init) {
// get the value from environment
mpd_environment_host = true;
const char *t = getenv("MPD_HOST");
if (t) {
if (t != nullptr) {
l.checkstack(1);
const char *h = strchr(t, '@');
if (h) {
if (h[1]) l.pushstring(h + 1);
} else
if (h != nullptr) {
if (h[1] != 0) {
l.pushstring(h + 1);
}
} else {
l.pushstring(t);
}
l.replace(-3);
}
}
@ -74,10 +77,10 @@ void mpd_host_setting::lua_setter(lua::state &l, bool init) {
}
class mpd_password_setting : public conky::simple_config_setting<std::string> {
typedef conky::simple_config_setting<std::string> Base;
using Base = conky::simple_config_setting<std::string>;
protected:
virtual void lua_setter(lua::state &l, bool init);
void lua_setter(lua::state &l, bool init) override;
public:
mpd_password_setting() : Base("mpd_password", std::string(), false) {}
@ -91,9 +94,9 @@ void mpd_password_setting::lua_setter(lua::state &l, bool init) {
if (l.isnil(-2) && mpd_environment_host) {
// get the value from environment
const char *t = getenv("MPD_HOST");
if (t) {
if (t != nullptr) {
const char *p = strchr(t, '@');
if (p) {
if (p != nullptr) {
l.checkstack(1);
l.pushstring(t, p - t);
l.replace(-3);
@ -123,27 +126,30 @@ struct mpd_result {
std::string track;
std::string name;
std::string file;
int is_playing;
int vol;
float progress;
int bitrate;
int length;
int elapsed;
int is_playing{};
int vol{};
float progress{};
int bitrate{};
int length{};
int elapsed{};
};
class mpd_cb : public conky::callback<mpd_result> {
typedef conky::callback<mpd_result> Base;
using Base = conky::callback<mpd_result>;
mpd_Connection *conn;
protected:
virtual void work();
void work() override;
public:
mpd_cb(uint32_t period) : Base(period, false, Tuple()), conn(NULL) {}
explicit mpd_cb(uint32_t period)
: Base(period, false, Tuple()), conn(nullptr) {}
~mpd_cb() {
if (conn) mpd_closeConnection(conn);
~mpd_cb() override {
if (conn != nullptr) {
mpd_closeConnection(conn);
}
}
};
@ -153,37 +159,38 @@ void mpd_cb::work() {
mpd_result mpd_info;
do {
if (!conn)
if (conn == nullptr) {
conn = mpd_newConnection(mpd_host.get(*state).c_str(),
mpd_port.get(*state), 10);
}
if (mpd_password.get(*state).size()) {
if (static_cast<unsigned int>(!mpd_password.get(*state).empty()) != 0u) {
mpd_sendPasswordCommand(conn, mpd_password.get(*state).c_str());
mpd_finishCommand(conn);
}
if (conn->error) {
if (conn->error != 0) {
NORM_ERR("MPD error: %s\n", conn->errorStr);
mpd_closeConnection(conn);
conn = 0;
conn = nullptr;
mpd_info.status = "MPD not responding";
break;
}
mpd_sendStatusCommand(conn);
if ((status = mpd_getStatus(conn)) == NULL) {
if ((status = mpd_getStatus(conn)) == nullptr) {
NORM_ERR("MPD error: %s\n", conn->errorStr);
mpd_closeConnection(conn);
conn = 0;
conn = nullptr;
mpd_info.status = "MPD not responding";
}
mpd_finishCommand(conn);
if (!conn || conn->error) {
if ((conn == nullptr) || (conn->error != 0)) {
// fprintf(stderr, "%s\n", conn->errorStr);
mpd_closeConnection(conn);
conn = 0;
conn = nullptr;
break;
}
@ -225,7 +232,8 @@ void mpd_cb::work() {
status->state == MPD_STATUS_STATE_PAUSE) {
mpd_info.is_playing = 1;
mpd_info.bitrate = status->bitRate;
mpd_info.progress = (float)status->elapsedTime / status->totalTime;
mpd_info.progress =
static_cast<float>(status->elapsedTime) / status->totalTime;
mpd_info.elapsed = status->elapsedTime;
mpd_info.length = status->totalTime;
} else {
@ -234,15 +242,15 @@ void mpd_cb::work() {
mpd_info.elapsed = 0;
}
if (conn->error) {
if (conn->error != 0) {
// fprintf(stderr, "%s\n", conn->errorStr);
mpd_closeConnection(conn);
conn = 0;
conn = nullptr;
break;
}
mpd_sendCurrentSongCommand(conn);
while ((entity = mpd_getNextInfoEntity(conn))) {
while ((entity = mpd_getNextInfoEntity(conn)) != nullptr) {
mpd_Song *song = entity->info.song;
if (entity->type != MPD_INFO_ENTITY_TYPE_SONG) {
@ -251,9 +259,9 @@ void mpd_cb::work() {
}
#define SETSTRING(a, b) \
if (b) \
a = b; \
(a) = b; \
else \
a = "";
(a) = "";
SETSTRING(mpd_info.artist, song->artist);
SETSTRING(mpd_info.albumartist, song->albumartist);
SETSTRING(mpd_info.album, song->album);
@ -262,23 +270,23 @@ void mpd_cb::work() {
SETSTRING(mpd_info.track, song->track);
SETSTRING(mpd_info.name, song->name);
SETSTRING(mpd_info.file, song->file);
if (entity != NULL) {
if (entity != nullptr) {
mpd_freeInfoEntity(entity);
entity = NULL;
entity = nullptr;
}
}
mpd_finishCommand(conn);
if (conn && conn->error) {
if ((conn != nullptr) && (conn->error != 0)) {
// fprintf(stderr, "%s\n", conn->errorStr);
mpd_closeConnection(conn);
conn = 0;
conn = nullptr;
break;
}
if (conn->error) {
if (conn->error != 0) {
// fprintf(stderr, "%s\n", conn->errorStr);
mpd_closeConnection(conn);
conn = 0;
conn = nullptr;
break;
}
@ -347,17 +355,20 @@ double mpd_barval(struct text_object *obj) {
void print_mpd_smart(struct text_object *obj, char *p, int p_max_size) {
const mpd_result &mpd_info = get_mpd();
int len = obj->data.i;
if (len == 0 || len > p_max_size) len = p_max_size;
if (len == 0 || len > p_max_size) {
len = p_max_size;
}
memset(p, 0, p_max_size);
if (mpd_info.artist.size() && mpd_info.title.size()) {
if ((static_cast<unsigned int>(!mpd_info.artist.empty()) != 0u) &&
(static_cast<unsigned int>(!mpd_info.title.empty()) != 0u)) {
snprintf(p, len, "%s - %s", mpd_info.artist.c_str(),
mpd_info.title.c_str());
} else if (get_mpd().title.size()) {
} else if (static_cast<unsigned int>(!get_mpd().title.empty()) != 0u) {
snprintf(p, len, "%s", mpd_info.title.c_str());
} else if (mpd_info.artist.size()) {
} else if (static_cast<unsigned int>(!mpd_info.artist.empty()) != 0u) {
snprintf(p, len, "%s", mpd_info.artist.c_str());
} else if (mpd_info.file.size()) {
} else if (static_cast<unsigned int>(!mpd_info.file.empty()) != 0u) {
snprintf(p, len, "%s", mpd_info.file.c_str());
} else {
*p = 0;

View File

@ -45,9 +45,9 @@ conky::simple_config_setting<std::string> db("mysql_db", "mysql", false);
} // namespace
void print_mysql(struct text_object *obj, char *p, int p_max_size) {
MYSQL *conn = mysql_init(NULL);
MYSQL *conn = mysql_init(nullptr);
if (conn == NULL) {
if (conn == nullptr) {
NORM_ERR("Can't initialize MySQL");
mysql_library_end();
return;
@ -55,7 +55,7 @@ void print_mysql(struct text_object *obj, char *p, int p_max_size) {
if (!mysql_real_connect(conn, host.get(*state).c_str(),
user.get(*state).c_str(),
password.get(*state).c_str(), db.get(*state).c_str(),
port.get(*state), NULL, 0)) {
port.get(*state), nullptr, 0)) {
NORM_ERR("MySQL: %s", mysql_error(conn));
mysql_close(conn);
mysql_library_end();
@ -68,7 +68,7 @@ void print_mysql(struct text_object *obj, char *p, int p_max_size) {
return;
}
MYSQL_RES *res = mysql_use_result(conn);
if (res == NULL) {
if (res == nullptr) {
NORM_ERR("MySQL: %s", mysql_error(conn));
mysql_close(conn);
mysql_library_end();

View File

@ -52,7 +52,9 @@ void out_to_ncurses_setting::lua_setter(lua::state &l, bool init) {
void out_to_ncurses_setting::cleanup(lua::state &l) {
lua::stack_sentry s(l, -1);
if (do_convert(l, -1).first) endwin();
if (do_convert(l, -1).first) {
endwin();
}
l.pop();
}

View File

@ -28,10 +28,10 @@
*/
#include "net_stat.h"
#include <errno.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <cerrno>
#include <cstring>
#include "conky.h"
#include "logging.h"
#include "net/if.h"
@ -44,6 +44,9 @@
#include <sys/sockio.h>
#define IFF_RUNNING IFF_LINK
#endif
#ifndef SOCK_CLOEXEC
# define SOCK_CLOEXEC O_CLOEXEC
#endif /* SOCK_CLOEXEC */
/* network interface stuff */
@ -68,26 +71,26 @@ struct net_stat foo_netstats;
* The added interface will have all its members initialized to 0,
* because clear_net_stats() is called from main() in conky.cc!
*
* @param[in] dev device / interface name. Silently ignores char * == NULL
* @param[in] dev device / interface name. Silently ignores char * == nullptr
**/
struct net_stat *get_net_stat(const char *dev, void *free_at_crash1,
void *free_at_crash2) {
struct net_stat *get_net_stat(const char *dev, void * /*free_at_crash1*/,
void * /*free_at_crash2*/) {
unsigned int i;
if (!dev) {
return 0;
if (dev == nullptr) {
return nullptr;
}
/* find interface stat */
for (i = 0; i < MAX_NET_INTERFACES; i++) {
if (netstats[i].dev && strcmp(netstats[i].dev, dev) == 0) {
if ((netstats[i].dev != nullptr) && strcmp(netstats[i].dev, dev) == 0) {
return &netstats[i];
}
}
/* wasn't found? add it */
for (i = 0; i < MAX_NET_INTERFACES; i++) {
if (netstats[i].dev == 0) {
if (netstats[i].dev == nullptr) {
netstats[i].dev = strndup(dev, text_buffer_size.get(*state));
/* initialize last_read_recv and last_read_trans to -1 denoting
* that they were never read before */
@ -112,28 +115,37 @@ void parse_net_stat_arg(struct text_object *obj, const char *arg,
bool showscope = false;
char nextarg[21]; // longest arg possible is a devname (max 20 chars)
int i = 0;
struct net_stat *netstat = NULL;
struct net_stat *netstat = nullptr;
if (!arg) arg = DEFAULTNETDEV;
if (arg == nullptr) {
arg = DEFAULTNETDEV;
}
while (sscanf(arg + i, " %20s", nextarg) == 1) {
if (strcmp(nextarg, "-n") == 0 || strcmp(nextarg, "--netmask") == 0)
if (strcmp(nextarg, "-n") == 0 || strcmp(nextarg, "--netmask") == 0) {
shownetmask = true;
else if (strcmp(nextarg, "-s") == 0 || strcmp(nextarg, "--scope") == 0)
} else if (strcmp(nextarg, "-s") == 0 || strcmp(nextarg, "--scope") == 0) {
showscope = true;
else if (nextarg[0] == '-') { // multiple flags in 1 arg
} else if (nextarg[0] == '-') { // multiple flags in 1 arg
for (int j = 1; nextarg[j] != 0; j++) {
if (nextarg[j] == 'n') shownetmask = true;
if (nextarg[j] == 's') showscope = true;
if (nextarg[j] == 'n') {
shownetmask = true;
}
if (nextarg[j] == 's') {
showscope = true;
}
}
} else
} else {
netstat = get_net_stat(nextarg, obj, free_at_crash);
}
i += strlen(nextarg); // skip this arg
while (!(isspace(arg[i]) || arg[i] == 0))
while (!((isspace(arg[i]) != 0) || arg[i] == 0)) {
i++; // and skip the spaces in front of it
}
}
if (netstat == NULL)
if (netstat == nullptr) {
netstat = get_net_stat(DEFAULTNETDEV, obj, free_at_crash);
}
#ifdef BUILD_IPV6
netstat->v6show_nm = shownetmask;
@ -144,7 +156,7 @@ void parse_net_stat_arg(struct text_object *obj, const char *arg,
void parse_net_stat_bar_arg(struct text_object *obj, const char *arg,
void *free_at_crash) {
if (arg) {
if (arg != nullptr) {
arg = scan_bar(obj, arg, 1);
obj->data.opaque = get_net_stat(arg, obj, free_at_crash);
} else {
@ -156,57 +168,71 @@ void parse_net_stat_bar_arg(struct text_object *obj, const char *arg,
}
void print_downspeed(struct text_object *obj, char *p, int p_max_size) {
struct net_stat *ns = (struct net_stat *)obj->data.opaque;
auto *ns = static_cast<struct net_stat *>(obj->data.opaque);
if (!ns) return;
if (ns == nullptr) {
return;
}
human_readable(ns->recv_speed, p, p_max_size);
}
void print_downspeedf(struct text_object *obj, char *p, int p_max_size) {
struct net_stat *ns = (struct net_stat *)obj->data.opaque;
auto *ns = static_cast<struct net_stat *>(obj->data.opaque);
if (!ns) return;
if (ns == nullptr) {
return;
}
spaced_print(p, p_max_size, "%.1f", 8, ns->recv_speed / 1024.0);
}
void print_upspeed(struct text_object *obj, char *p, int p_max_size) {
struct net_stat *ns = (struct net_stat *)obj->data.opaque;
auto *ns = static_cast<struct net_stat *>(obj->data.opaque);
if (!ns) return;
if (ns == nullptr) {
return;
}
human_readable(ns->trans_speed, p, p_max_size);
}
void print_upspeedf(struct text_object *obj, char *p, int p_max_size) {
struct net_stat *ns = (struct net_stat *)obj->data.opaque;
auto *ns = static_cast<struct net_stat *>(obj->data.opaque);
if (!ns) return;
if (ns == nullptr) {
return;
}
spaced_print(p, p_max_size, "%.1f", 8, ns->trans_speed / 1024.0);
}
void print_totaldown(struct text_object *obj, char *p, int p_max_size) {
struct net_stat *ns = (struct net_stat *)obj->data.opaque;
auto *ns = static_cast<struct net_stat *>(obj->data.opaque);
if (!ns) return;
if (ns == nullptr) {
return;
}
human_readable(ns->recv, p, p_max_size);
}
void print_totalup(struct text_object *obj, char *p, int p_max_size) {
struct net_stat *ns = (struct net_stat *)obj->data.opaque;
auto *ns = static_cast<struct net_stat *>(obj->data.opaque);
if (!ns) return;
if (ns == nullptr) {
return;
}
human_readable(ns->trans, p, p_max_size);
}
void print_addr(struct text_object *obj, char *p, int p_max_size) {
struct net_stat *ns = (struct net_stat *)obj->data.opaque;
auto *ns = static_cast<struct net_stat *>(obj->data.opaque);
if (!ns) return;
if (ns == nullptr) {
return;
}
if ((ns->addr.sa_data[2] & 255) == 0 && (ns->addr.sa_data[3] & 255) == 0 &&
(ns->addr.sa_data[4] & 255) == 0 && (ns->addr.sa_data[5] & 255) == 0) {
@ -224,7 +250,7 @@ void print_addrs(struct text_object *obj, char *p, int p_max_size) {
if (!ns) return;
if (NULL != ns->addrs && strlen(ns->addrs) > 2) {
if (nullptr != ns->addrs && strlen(ns->addrs) > 2) {
ns->addrs[strlen(ns->addrs) - 2] = 0; /* remove ", " from end of string */
strncpy(p, ns->addrs, p_max_size);
} else {
@ -284,11 +310,11 @@ void print_v6addrs(struct text_object *obj, char *p, int p_max_size) {
void parse_net_stat_graph_arg(struct text_object *obj, const char *arg,
void *free_at_crash) {
/* scan arguments and get interface name back */
char *buf = 0;
char *buf = nullptr;
buf = scan_graph(obj, arg, 0);
// default to DEFAULTNETDEV
if (buf) {
if (buf != nullptr) {
obj->data.opaque = get_net_stat(buf, obj, free_at_crash);
free(buf);
return;
@ -303,15 +329,15 @@ void parse_net_stat_graph_arg(struct text_object *obj, const char *arg,
* containing a void * to a net_stat struct
**/
double downspeedgraphval(struct text_object *obj) {
struct net_stat *ns = (struct net_stat *)obj->data.opaque;
auto *ns = static_cast<struct net_stat *>(obj->data.opaque);
return (ns ? (ns->recv_speed / 1024.0) : 0);
return (ns != nullptr ? (ns->recv_speed / 1024.0) : 0);
}
double upspeedgraphval(struct text_object *obj) {
struct net_stat *ns = (struct net_stat *)obj->data.opaque;
auto *ns = static_cast<struct net_stat *>(obj->data.opaque);
return (ns ? (ns->trans_speed / 1024.0) : 0);
return (ns != nullptr ? (ns->trans_speed / 1024.0) : 0);
}
#endif /* BUILD_X11 */
@ -417,7 +443,7 @@ double wireless_link_barval(struct text_object *obj) {
* Clears the global array of net_stat structs which contains networks
* statistics for every interface.
**/
void clear_net_stats(void) {
void clear_net_stats() {
#ifdef BUILD_IPV6
struct v6addr *nextv6;
#endif /* BUILD_IPV6 */
@ -458,36 +484,50 @@ void free_if_up(struct text_object *obj) { free_and_zero(obj->data.opaque); }
/* We should check if this is ok with OpenBSD and NetBSD as well. */
int interface_up(struct text_object *obj) {
int fd;
struct ifreq ifr;
char *dev = (char *)obj->data.opaque;
struct ifreq ifr {};
auto *dev = static_cast<char *>(obj->data.opaque);
if (!dev) return 0;
if (dev == nullptr) {
return 0;
}
if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
CRIT_ERR(NULL, NULL, "could not create sockfd");
if ((fd = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0)) < 0) {
CRIT_ERR(nullptr, nullptr, "could not create sockfd");
return 0;
}
strncpy(ifr.ifr_name, dev, IFNAMSIZ);
if (ioctl(fd, SIOCGIFFLAGS, &ifr)) {
if (ioctl(fd, SIOCGIFFLAGS, &ifr) != 0) {
/* if device does not exist, treat like not up */
if (errno != ENODEV && errno != ENXIO) perror("SIOCGIFFLAGS");
if (errno != ENODEV && errno != ENXIO) {
perror("SIOCGIFFLAGS");
}
goto END_FALSE;
}
if (!(ifr.ifr_flags & IFF_UP)) /* iface is not up */
if ((ifr.ifr_flags & IFF_UP) == 0) { /* iface is not up */
goto END_FALSE;
if (if_up_strictness.get(*state) == IFUP_UP) goto END_TRUE;
}
if (if_up_strictness.get(*state) == IFUP_UP) {
goto END_TRUE;
}
#ifdef IFF_RUNNING
if (!(ifr.ifr_flags & IFF_RUNNING)) goto END_FALSE;
if ((ifr.ifr_flags & IFF_RUNNING) == 0) {
goto END_FALSE;
}
#endif
if (if_up_strictness.get(*state) == IFUP_LINK) goto END_TRUE;
if (if_up_strictness.get(*state) == IFUP_LINK) {
goto END_TRUE;
}
if (ioctl(fd, SIOCGIFADDR, &ifr)) {
if (ioctl(fd, SIOCGIFADDR, &ifr) != 0) {
perror("SIOCGIFADDR");
goto END_FALSE;
}
if (((struct sockaddr_in *)&(ifr.ifr_addr))->sin_addr.s_addr) goto END_TRUE;
if ((reinterpret_cast<struct sockaddr_in *>(&(ifr.ifr_addr)))
->sin_addr.s_addr != 0u) {
goto END_TRUE;
}
END_FALSE:
close(fd);
@ -498,9 +538,9 @@ END_TRUE:
}
struct _dns_data {
_dns_data() : nscount(0), ns_list(0) {}
int nscount;
char **ns_list;
_dns_data() = default;
int nscount{0};
char **ns_list{nullptr};
};
static _dns_data dns_data;
@ -510,12 +550,14 @@ void free_dns_data(struct text_object *obj) {
(void)obj;
for (i = 0; i < dns_data.nscount; i++) free(dns_data.ns_list[i]);
for (i = 0; i < dns_data.nscount; i++) {
free(dns_data.ns_list[i]);
}
free(dns_data.ns_list);
memset(&dns_data, 0, sizeof(dns_data));
}
int update_dns_data(void) {
int update_dns_data() {
FILE *fp;
char line[256];
// static double last_dns_update = 0.0;
@ -526,18 +568,20 @@ int update_dns_data(void) {
last_dns_update = current_update_time;
*/
free_dns_data(NULL);
free_dns_data(nullptr);
if ((fp = fopen("/etc/resolv.conf", "r")) == NULL) return 0;
while (!feof(fp)) {
if (fgets(line, 255, fp) == NULL) {
if ((fp = fopen("/etc/resolv.conf", "re")) == nullptr) {
return 0;
}
while (feof(fp) == 0) {
if (fgets(line, 255, fp) == nullptr) {
break;
}
if (!strncmp(line, "nameserver ", 11)) {
if (strncmp(line, "nameserver ", 11) == 0) {
line[strlen(line) - 1] = '\0'; // remove trailing newline
dns_data.nscount++;
dns_data.ns_list =
(char **)realloc(dns_data.ns_list, dns_data.nscount * sizeof(char *));
dns_data.ns_list = static_cast<char **>(
realloc(dns_data.ns_list, dns_data.nscount * sizeof(char *)));
dns_data.ns_list[dns_data.nscount - 1] =
strndup(line + 11, text_buffer_size.get(*state));
}
@ -547,10 +591,11 @@ int update_dns_data(void) {
}
void parse_nameserver_arg(struct text_object *obj, const char *arg) {
obj->data.l = arg ? atoi(arg) : 0;
obj->data.l = arg != nullptr ? atoi(arg) : 0;
}
void print_nameserver(struct text_object *obj, char *p, int p_max_size) {
if (dns_data.nscount > obj->data.l)
if (dns_data.nscount > obj->data.l) {
snprintf(p, p_max_size, "%s", dns_data.ns_list[obj->data.l]);
}
}

View File

@ -30,7 +30,7 @@
#include "netbsd.h"
#include "net_stat.h"
static kvm_t *kd = NULL;
static kvm_t *kd = nullptr;
int kd_init = 0, nkd_init = 0;
u_int32_t sensvalue;
char errbuf[_POSIX2_LINE_MAX];
@ -40,8 +40,8 @@ static int init_kvm(void) {
return 0;
}
kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf);
if (kd == NULL) {
kd = kvm_openfiles(nullptr, NULL, NULL, KVM_NO_FILES, errbuf);
if (kd == nullptr) {
warnx("cannot kvm_openfiles: %s", errbuf);
return -1;
}
@ -65,7 +65,7 @@ static int swapmode(int *retavail, int *retfree) {
sep = (struct swapent *)malloc(n * (sizeof(*sep)));
if (sep == NULL) {
if (sep == nullptr) {
warn("memory allocation failed");
return 0;
}
@ -92,7 +92,7 @@ void update_uptime() {
time_t now;
int size = sizeof(boottime);
if ((sysctl(mib, 2, &boottime, &size, NULL, 0) != -1) &&
if ((sysctl(mib, 2, &boottime, &size, nullptr, 0) != -1) &&
(boottime.tv_sec != 0)) {
time(&now);
info.uptime = now - boottime.tv_sec;
@ -116,7 +116,7 @@ void update_meminfo() {
struct uvmexp_sysctl uvmexp;
size_t size = sizeof(uvmexp);
if (sysctl(mib, 2, &uvmexp, &size, NULL, 0) < 0) {
if (sysctl(mib, 2, &uvmexp, &size, nullptr, 0) < 0) {
warn("could not get memory info");
return;
}
@ -143,12 +143,12 @@ void update_net_stats() {
struct ifnet ifnet;
struct ifnet_head ifhead; /* interfaces are in a tail queue */
u_long ifnetaddr;
static struct nlist namelist[] = {{"_ifnet"}, {NULL}};
static struct nlist namelist[] = {{"_ifnet"}, {nullptr}};
static kvm_t *nkd;
if (!nkd_init) {
nkd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
if (nkd == NULL) {
nkd = kvm_openfiles(nullptr, NULL, NULL, O_RDONLY, errbuf);
if (nkd == nullptr) {
warnx("cannot kvm_openfiles: %s", errbuf);
warnx("maybe you need to setgid kmem this program?");
return;
@ -179,7 +179,7 @@ void update_net_stats() {
long long last_recv, last_trans;
kvm_read(nkd, (u_long)ifnetaddr, (void *)&ifnet, sizeof(ifnet));
ns = get_net_stat(ifnet.if_xname, NULL, NULL);
ns = get_net_stat(ifnet.if_xname, nullptr, NULL);
ns->up = 1;
last_recv = ns->recv;
last_trans = ns->trans;
@ -267,7 +267,7 @@ void update_cpu_usage() {
info.cpu_usage = 0;
if (sysctlbyname("kern.cp_time", &cp_time, &len, NULL, 0) < 0) {
if (sysctlbyname("kern.cp_time", &cp_time, &len, nullptr, 0) < 0) {
warn("cannot get kern.cp_time");
}

View File

@ -367,8 +367,8 @@ void nvidia_display_setting::lua_setter(lua::state &l, bool init) {
std::string str = do_convert(l, -1).first;
if (str.size()) {
if ((nvdisplay = XOpenDisplay(str.c_str())) == NULL) {
CRIT_ERR(NULL, NULL, "can't open nvidia display: %s",
if ((nvdisplay = XOpenDisplay(str.c_str())) == nullptr) {
CRIT_ERR(nullptr, NULL, "can't open nvidia display: %s",
XDisplayName(str.c_str()));
}
}
@ -381,7 +381,7 @@ void nvidia_display_setting::cleanup(lua::state &l) {
if (nvdisplay) {
XCloseDisplay(nvdisplay);
nvdisplay = NULL;
nvdisplay = nullptr;
}
l.pop();
@ -443,7 +443,7 @@ int set_nvidia_query(struct text_object *obj, const char *arg,
}
// free the string buffer after arg is not anymore needed
if (strbuf != NULL) free(strbuf);
if (strbuf != nullptr) free(strbuf);
// Save pointers to the arg and command strings for debugging and printing
nvs->arg = translate_module_argument[aid];
@ -654,7 +654,7 @@ static inline int get_nvidia_target_count(Display *dpy, TARGET_ID tid) {
if (num_tgts < 1) {
// Print error and exit if there's no NVIDIA's GPU
CRIT_ERR(NULL, NULL,
CRIT_ERR(nullptr, NULL,
"%s:"
"\n Trying to query Nvidia target failed (using the "
"propietary drivers)."
@ -747,7 +747,7 @@ static char *get_nvidia_string(TARGET_ID tid, ATTR_ID aid, int gid) {
"%s: Something went wrong running nvidia string query (tid: %d, aid: "
"%d, GPU %d)",
__func__, tid, aid, gid);
return NULL;
return nullptr;
}
// fprintf(stderr, "checking get_nvidia_string-> '%s'", str);
return str;
@ -839,9 +839,9 @@ static int get_nvidia_string_value(TARGET_ID tid, ATTR_ID aid, char *token,
kvp = strtok_r(str, NV_KVPAIR_SEPARATORS, &saveptr1);
while (kvp) {
key = strtok_r(kvp, NV_KEYVAL_SEPARATORS, &saveptr2);
val = strtok_r(NULL, NV_KEYVAL_SEPARATORS, &saveptr2);
val = strtok_r(nullptr, NV_KEYVAL_SEPARATORS, &saveptr2);
if (key && val && (strcmp(token, key) == 0)) {
temp = (int)strtol(val, NULL, 0);
temp = (int)strtol(val, nullptr, 0);
if (search == SEARCH_FIRST) {
value = temp;
break;
@ -856,7 +856,7 @@ static int get_nvidia_string_value(TARGET_ID tid, ATTR_ID aid, char *token,
break;
}
}
kvp = strtok_r(NULL, NV_KVPAIR_SEPARATORS, &saveptr1);
kvp = strtok_r(nullptr, NV_KVPAIR_SEPARATORS, &saveptr1);
}
// This call updated the cache for the cacheable values;
@ -888,10 +888,10 @@ void print_nvidia_value(struct text_object *obj, char *p, int p_max_size) {
// Assume failure
value = -1;
str = NULL;
str = nullptr;
// Perform query
if (nvs != NULL) {
if (nvs != nullptr) {
// Reduce overcommitted GPU number to last GPU
if (nvs->gpu_id > num_GPU) nvs->gpu_id = num_GPU;
@ -946,7 +946,7 @@ void print_nvidia_value(struct text_object *obj, char *p, int p_max_size) {
// Print result
if (value != -1) {
snprintf(p, p_max_size, "%d", value);
} else if (str != NULL) {
} else if (str != nullptr) {
snprintf(p, p_max_size, "%s", str);
free(str);
} else {
@ -964,7 +964,7 @@ double get_nvidia_barval(struct text_object *obj) {
// Convert query_result to a percentage using ((val-min)÷(max-min)×100)+0.5 if
// needed.
if (nvs != NULL) {
if (nvs != nullptr) {
switch (nvs->attribute) {
case ATTR_UTILS_STRING: // one of the percentage utils (gpuutil,
// membwutil, videoutil and pcieutil)
@ -1020,7 +1020,7 @@ double get_nvidia_barval(struct text_object *obj) {
case ATTR_FREQS_STRING: // mtrfreq (calculate out of memfreqmax)
if (nvs->token == "memTransferRate") {
// Just in case error for silly devs
CRIT_ERR(NULL, NULL,
CRIT_ERR(nullptr, NULL,
"%s: attribute is 'ATTR_FREQS_STRING' but token is not "
"\"memTransferRate\" (arg: '%s')",
nvs->command, nvs->arg);
@ -1039,7 +1039,7 @@ double get_nvidia_barval(struct text_object *obj) {
break;
default: // Throw error if unsupported args are used
CRIT_ERR(NULL, NULL, "%s: invalid argument specified: '%s'",
CRIT_ERR(nullptr, NULL, "%s: invalid argument specified: '%s'",
nvs->command, nvs->arg);
}
}

View File

@ -74,7 +74,7 @@ inline void proc_find_top(struct process **cpu, struct process **mem);
static short cpu_setup = 0;
static kvm_t *kd = 0;
struct ifmibdata *data = NULL;
struct ifmibdata *data = nullptr;
size_t len = 0;
int init_kvm = 0;
@ -85,8 +85,8 @@ static int kvm_init() {
return 1;
}
kd = kvm_open(NULL, NULL, NULL, KVM_NO_FILES, NULL);
if (kd == NULL) {
kd = kvm_open(nullptr, NULL, NULL, KVM_NO_FILES, NULL);
if (kd == nullptr) {
NORM_ERR("error opening kvm");
} else {
init_kvm = 1;
@ -108,7 +108,7 @@ static int swapmode(int *used, int *total) {
}
swdev = malloc(nswap * sizeof(*swdev));
if (swdev == NULL) {
if (swdev == nullptr) {
return 0;
}
@ -144,7 +144,7 @@ void update_uptime() {
time_t now;
size_t size = sizeof(boottime);
if ((sysctl(mib, 2, &boottime, &size, NULL, 0) != -1) &&
if ((sysctl(mib, 2, &boottime, &size, nullptr, 0) != -1) &&
(boottime.tv_sec != 0)) {
time(&now);
info.uptime = now - boottime.tv_sec;
@ -172,7 +172,7 @@ void update_meminfo() {
/* get total -- systemwide main memory usage structure */
size = sizeof(vmtotal);
if (sysctl(mib, 2, &vmtotal, &size, NULL, 0) < 0) {
if (sysctl(mib, 2, &vmtotal, &size, nullptr, 0) < 0) {
warn("sysctl failed");
bzero(&vmtotal, sizeof(vmtotal));
}
@ -210,7 +210,7 @@ void update_net_stats() {
}
for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
ns = get_net_stat((const char *)ifa->ifa_name, NULL, NULL);
ns = get_net_stat((const char *)ifa->ifa_name, nullptr, NULL);
if (ifa->ifa_flags & IFF_UP) {
struct ifaddrs *iftmp;
@ -224,7 +224,7 @@ void update_net_stats() {
}
for (iftmp = ifa->ifa_next;
iftmp != NULL && strcmp(ifa->ifa_name, iftmp->ifa_name) == 0;
iftmp != nullptr && strcmp(ifa->ifa_name, iftmp->ifa_name) == 0;
iftmp = iftmp->ifa_next) {
if (iftmp->ifa_addr->sa_family == AF_INET) {
memcpy(&(ns->addr), iftmp->ifa_addr, iftmp->ifa_addr->sa_len);
@ -301,7 +301,7 @@ struct cpu_load_struct fresh = {{0, 0, 0, 0, 0}};
long cpu_used, oldtotal, oldused;
#else
#include <assert.h>
int64_t *fresh = NULL;
int64_t *fresh = nullptr;
/* XXX is 8 enough? - What's the constant for MAXCPU? */
/* allocate this with malloc would be better */
@ -314,22 +314,22 @@ void get_cpu_count() {
int mib[2] = {CTL_HW, HW_NCPU};
size_t len = sizeof(cpu_count);
if (sysctl(mib, 2, &cpu_count, &len, NULL, 0) != 0) {
if (sysctl(mib, 2, &cpu_count, &len, nullptr, 0) != 0) {
NORM_ERR("error getting cpu count, defaulting to 1");
}
#endif
info.cpu_count = cpu_count;
info.cpu_usage = malloc(info.cpu_count * sizeof(float));
if (info.cpu_usage == NULL) {
CRIT_ERR(NULL, NULL, "malloc");
if (info.cpu_usage == nullptr) {
CRIT_ERR(nullptr, NULL, "malloc");
}
#ifndef OLDCPU
assert(fresh == NULL); /* XXX Is this leaking memory? */
assert(fresh == nullptr); /* XXX Is this leaking memory? */
/* XXX Where shall I free this? */
if (NULL == (fresh = calloc(cpu_count, sizeof(int64_t) * CPUSTATES))) {
CRIT_ERR(NULL, NULL, "calloc");
if (nullptr == (fresh = calloc(cpu_count, sizeof(int64_t) * CPUSTATES))) {
CRIT_ERR(nullptr, NULL, "calloc");
}
#endif
}
@ -352,7 +352,7 @@ void update_cpu_usage() {
}
#ifdef OLDCPU
if (sysctl(mib, 2, &cp_time, &len, NULL, 0) < 0) {
if (sysctl(mib, 2, &cp_time, &len, nullptr, 0) < 0) {
NORM_ERR("Cannot get kern.cp_time");
}
@ -378,7 +378,7 @@ void update_cpu_usage() {
size = CPUSTATES * sizeof(int64_t);
for (i = 0; i < info.cpu_count; i++) {
int cp_time_mib[] = {CTL_KERN, KERN_CPTIME2, i};
if (sysctl(cp_time_mib, 3, &(fresh[i * CPUSTATES]), &size, NULL, 0) < 0) {
if (sysctl(cp_time_mib, 3, &(fresh[i * CPUSTATES]), &size, nullptr, 0) < 0) {
NORM_ERR("sysctl kern.cp_time2 failed");
}
}
@ -387,7 +387,7 @@ void update_cpu_usage() {
long cp_time_tmp[CPUSTATES];
size = sizeof(cp_time_tmp);
if (sysctl(cp_time_mib, 2, cp_time_tmp, &size, NULL, 0) < 0) {
if (sysctl(cp_time_mib, 2, cp_time_tmp, &size, nullptr, 0) < 0) {
NORM_ERR("sysctl kern.cp_time failed");
}
@ -455,7 +455,7 @@ void update_obsd_sensors() {
/* for (dev = 0; dev < MAXSENSORDEVICES; dev++) { */
mib[2] = dev;
if (sysctl(mib, 3, &sensordev, &sdlen, NULL, 0) == -1) {
if (sysctl(mib, 3, &sensordev, &sdlen, nullptr, 0) == -1) {
if (errno != ENOENT) {
warn("sysctl");
}
@ -466,7 +466,7 @@ void update_obsd_sensors() {
mib[3] = type;
for (numt = 0; numt < sensordev.maxnumt[type]; numt++) {
mib[4] = numt;
if (sysctl(mib, 5, &sensor, &slen, NULL, 0) == -1) {
if (sysctl(mib, 5, &sensor, &slen, nullptr, 0) == -1) {
if (errno != ENOENT) {
warn("sysctl");
}
@ -541,7 +541,7 @@ void get_obsd_vendor(struct text_object *obj, char *buf,
mib[0] = CTL_HW;
mib[1] = HW_VENDOR;
if (sysctl(mib, 2, vendor, &size, NULL, 0) == -1) {
if (sysctl(mib, 2, vendor, &size, nullptr, 0) == -1) {
NORM_ERR("error reading vendor");
snprintf(buf, client_buffer_size, "unknown");
} else {
@ -561,7 +561,7 @@ void get_obsd_product(struct text_object *obj, char *buf,
mib[0] = CTL_HW;
mib[1] = HW_PRODUCT;
if (sysctl(mib, 2, product, &size, NULL, 0) == -1) {
if (sysctl(mib, 2, product, &size, nullptr, 0) == -1) {
NORM_ERR("error reading product");
snprintf(buf, client_buffer_size, "unknown");
} else {
@ -582,7 +582,7 @@ char get_freq(char *p_client_buffer, size_t client_buffer_size,
size_t size = sizeof(freq);
if (sysctl(mib, 2, &freq, &size, NULL, 0) == 0) {
if (sysctl(mib, 2, &freq, &size, nullptr, 0) == 0) {
snprintf(p_client_buffer, client_buffer_size, p_format,
(float)freq / divisor);
} else {
@ -665,7 +665,7 @@ void get_top_info(void) {
&n_processes);
for (i = 0; i < n_processes; i++) {
if (!((p[i].p_flag & P_SYSTEM)) && p[i].p_comm != NULL) {
if (!((p[i].p_flag & P_SYSTEM)) && p[i].p_comm != nullptr) {
proc = find_process(p[i].p_pid);
if (!proc) proc = new_process(p[i].p_pid);

View File

@ -31,9 +31,9 @@
*
*/
#include <limits.h> /* INT_MAX */
#include <stdlib.h>
#include <string.h>
#include <climits> /* INT_MAX */
#include <cstdlib>
#include <cstring>
#include "conky.h"
struct prio_elem {
@ -65,10 +65,10 @@ struct prio_queue {
/* nop callback to save us from conditional calling */
static void pq_free_nop(void *a) { (void)a; }
struct prio_queue *init_prio_queue(void) {
struct prio_queue *init_prio_queue() {
struct prio_queue *retval;
retval = (struct prio_queue *)malloc(sizeof(struct prio_queue));
retval = static_cast<struct prio_queue *>(malloc(sizeof(struct prio_queue)));
memset(retval, 0, sizeof(struct prio_queue));
/* use pq_free_nop by default */
@ -84,15 +84,21 @@ struct prio_queue *init_prio_queue(void) {
void pq_set_compare(struct prio_queue *queue,
int (*pqcompare)(void *a, void *b)) {
if (pqcompare) queue->compare = pqcompare;
if (pqcompare != nullptr) {
queue->compare = pqcompare;
}
}
void pq_set_free(struct prio_queue *queue, void (*pqfree)(void *a)) {
if (pqfree) queue->free = pqfree;
if (pqfree != nullptr) {
queue->free = pqfree;
}
}
void pq_set_max_size(struct prio_queue *queue, int max_size) {
if (max_size >= 0) queue->max_size = max_size;
if (max_size >= 0) {
queue->max_size = max_size;
}
}
int pq_get_cur_size(struct prio_queue *queue) { return queue->cur_size; }
@ -100,7 +106,7 @@ int pq_get_cur_size(struct prio_queue *queue) { return queue->cur_size; }
static struct prio_elem *init_prio_elem(void *data) {
struct prio_elem *retval;
retval = (struct prio_elem *)malloc(sizeof(struct prio_elem));
retval = static_cast<struct prio_elem *>(malloc(sizeof(struct prio_elem)));
memset(retval, 0, sizeof(struct prio_elem));
retval->data = data;
@ -111,10 +117,12 @@ void insert_prio_elem(struct prio_queue *queue, void *data) {
struct prio_elem *cur;
/* queue->compare is a must-have */
if (!queue->compare) return;
if (queue->compare == nullptr) {
return;
}
/* empty queue, insert the first item */
if (!queue->cur_size) {
if (queue->cur_size == 0) {
queue->cur_size++;
queue->head = queue->tail = init_prio_elem(data);
return;
@ -127,8 +135,9 @@ void insert_prio_elem(struct prio_queue *queue, void *data) {
queue->tail->next = init_prio_elem(data);
queue->tail->next->prev = queue->tail;
queue->tail = queue->tail->next;
} else /* list was already full */
} else { /* list was already full */
(*queue->free)(data);
}
return;
}
@ -142,7 +151,7 @@ void insert_prio_elem(struct prio_queue *queue, void *data) {
}
/* find the actual position if short-cuts failed */
for (cur = queue->head->next; cur; cur = cur->next) {
for (cur = queue->head->next; cur != nullptr; cur = cur->next) {
if (queue->compare(cur->data, data) >= 0) {
queue->cur_size++;
cur->prev->next = init_prio_elem(data);
@ -167,17 +176,20 @@ void *pop_prio_elem(struct prio_queue *queue) {
struct prio_elem *tmp;
void *data;
if (queue->cur_size <= 0) return NULL;
if (queue->cur_size <= 0) {
return nullptr;
}
tmp = queue->head;
data = tmp->data;
queue->head = queue->head->next;
queue->cur_size--;
if (queue->head)
queue->head->prev = NULL;
else /* list is now empty */
queue->tail = NULL;
if (queue->head != nullptr) {
queue->head->prev = nullptr;
} else { /* list is now empty */
queue->tail = nullptr;
}
free(tmp);
return data;
@ -185,6 +197,8 @@ void *pop_prio_elem(struct prio_queue *queue) {
void free_prio_queue(struct prio_queue *queue) {
void *data;
while ((data = pop_prio_elem(queue))) (*queue->free)(data);
while ((data = pop_prio_elem(queue)) != nullptr) {
(*queue->free)(data);
}
free(queue);
}

View File

@ -56,7 +56,7 @@ void insert_prio_elem(prio_queue_t, void *);
int pq_get_cur_size(prio_queue_t queue);
/* pop the top-most element from the queue
* returns NULL if queue is empty */
* returns nullptr if queue is empty */
void *pop_prio_elem(prio_queue_t);
/* clear and free the given queue */

View File

@ -28,9 +28,9 @@
*/
#include "proc.h"
#include <ctype.h>
#include <dirent.h>
#include <unistd.h>
#include <cctype>
#include <memory>
#include "conky.h"
#include "core.h"
@ -38,20 +38,22 @@
pid_t strtopid(const char *s) {
long t;
if (sscanf(s, "%ld", &t) != 1) return -1;
if (sscanf(s, "%ld", &t) != 1) {
return -1;
}
return t;
}
char *readfile(const char *filename, int *total_read, char showerror) {
FILE *file;
char *buf = NULL;
char *buf = nullptr;
int bytes_read;
*total_read = 0;
file = fopen(filename, "r");
if (file) {
file = fopen(filename, "re");
if (file != nullptr) {
do {
buf = (char *)realloc(buf, *total_read + READSIZE + 1);
buf = static_cast<char *>(realloc(buf, *total_read + READSIZE + 1));
bytes_read = fread(buf + *total_read, 1, READSIZE, file);
*total_read += bytes_read;
buf[*total_read] = 0;
@ -80,18 +82,20 @@ struct ll_string {
};
struct ll_string *addnode(struct ll_string *end, char *string) {
struct ll_string *current =
(struct ll_string *)malloc(sizeof(struct ll_string));
auto *current =
static_cast<struct ll_string *>(malloc(sizeof(struct ll_string)));
current->string = strdup(string);
current->next = NULL;
if (end != NULL) end->next = current;
current->next = nullptr;
if (end != nullptr) {
end->next = current;
}
return current;
}
void freelist(struct ll_string *front) {
if (front != NULL) {
if (front != nullptr) {
free(front->string);
if (front->next != NULL) {
if (front->next != nullptr) {
freelist(front->next);
}
free(front);
@ -101,7 +105,7 @@ void freelist(struct ll_string *front) {
int inlist(struct ll_string *front, char *string) {
struct ll_string *current;
for (current = front; current != NULL; current = current->next) {
for (current = front; current != nullptr; current = current->next) {
if (strcmp(current->string, string) == 0) {
return 1;
}
@ -129,7 +133,7 @@ void print_pid_cmdline(struct text_object *obj, char *p, int p_max_size) {
if (*(objbuf.get()) != 0) {
snprintf(pathbuf, 64, PROCDIR "/%d/cmdline", strtopid(objbuf.get()));
buf = readfile(pathbuf, &bytes_read, 1);
if (buf != NULL) {
if (buf != nullptr) {
for (i = 0; i < bytes_read - 1; i++) {
if (buf[i] == 0) {
buf[i] = ' ';
@ -175,7 +179,7 @@ void print_pid_environ(struct text_object *obj, char *p, int p_max_size) {
}
snprintf(pathbuf, 64, PROCDIR "/%d/environ", pid);
buf = readfile(pathbuf, &total_read, 1);
if (buf != NULL) {
if (buf != nullptr) {
for (i = 0; i < total_read; i += strlen(buf + i) + 1) {
if (strncmp(buf + i, var, strlen(var)) == 0 &&
*(buf + i + strlen(var)) == '=') {
@ -193,7 +197,7 @@ void print_pid_environ(struct text_object *obj, char *p, int p_max_size) {
}
void print_pid_environ_list(struct text_object *obj, char *p, int p_max_size) {
char *buf = NULL;
char *buf = nullptr;
char *buf2;
int bytes_read, total_read;
int i = 0;
@ -204,7 +208,7 @@ void print_pid_environ_list(struct text_object *obj, char *p, int p_max_size) {
snprintf(pathbuf, 64, PROCDIR "/%d/environ", strtopid(objbuf.get()));
buf = readfile(pathbuf, &total_read, 1);
if (buf != NULL) {
if (buf != nullptr) {
for (bytes_read = 0; bytes_read < total_read; buf[i - 1] = ';') {
buf2 = strdup(buf + bytes_read);
bytes_read += strlen(buf2) + 1;
@ -228,7 +232,7 @@ void print_pid_exe(struct text_object *obj, char *p, int p_max_size) {
}
void print_pid_nice(struct text_object *obj, char *p, int p_max_size) {
char *buf = NULL;
char *buf = nullptr;
int bytes_read;
long int nice_value;
char pathbuf[64];
@ -239,7 +243,7 @@ void print_pid_nice(struct text_object *obj, char *p, int p_max_size) {
if (*(obj->data.s) != 0) {
snprintf(pathbuf, 64, PROCDIR "/%d/stat", strtopid(objbuf.get()));
buf = readfile(pathbuf, &bytes_read, 1);
if (buf != NULL) {
if (buf != nullptr) {
sscanf(buf,
"%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %*u %*u %*d "
"%*d %*d %ld",
@ -257,15 +261,15 @@ void print_pid_openfiles(struct text_object *obj, char *p, int p_max_size) {
struct dirent *entry;
std::unique_ptr<char[]> buf(new char[p_max_size]);
int length, totallength = 0;
struct ll_string *files_front = NULL;
struct ll_string *files_back = NULL;
struct ll_string *files_front = nullptr;
struct ll_string *files_back = nullptr;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
dir = opendir(objbuf.get());
if (dir != NULL) {
while ((entry = readdir(dir))) {
if (dir != nullptr) {
while ((entry = readdir(dir)) != nullptr) {
if (entry->d_name[0] != '.') {
snprintf(buf.get(), p_max_size, "%d/%s", strtopid(objbuf.get()),
entry->d_name);
@ -277,7 +281,7 @@ void print_pid_openfiles(struct text_object *obj, char *p, int p_max_size) {
buf.get());
totallength += length + strlen("; ");
}
if (files_front == NULL) {
if (files_front == nullptr) {
files_front = files_back;
}
}
@ -293,7 +297,7 @@ void print_pid_openfiles(struct text_object *obj, char *p, int p_max_size) {
void print_pid_parent(struct text_object *obj, char *p, int p_max_size) {
#define PARENT_ENTRY "PPid:\t"
#define PARENTNOTFOUND "Can't find the process parent in '%s'"
char *begin, *end, *buf = NULL;
char *begin, *end, *buf = nullptr;
int bytes_read;
char pathbuf[64];
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
@ -302,12 +306,12 @@ void print_pid_parent(struct text_object *obj, char *p, int p_max_size) {
snprintf(pathbuf, 64, PROCDIR "/%d/status", strtopid(objbuf.get()));
buf = readfile(pathbuf, &bytes_read, 1);
if (buf != NULL) {
if (buf != nullptr) {
begin = strstr(buf, PARENT_ENTRY);
if (begin != NULL) {
if (begin != nullptr) {
begin += strlen(PARENT_ENTRY);
end = strchr(begin, '\n');
if (end != NULL) {
if (end != nullptr) {
*(end) = 0;
}
snprintf(p, p_max_size, "%s", begin);
@ -319,7 +323,7 @@ void print_pid_parent(struct text_object *obj, char *p, int p_max_size) {
}
void print_pid_priority(struct text_object *obj, char *p, int p_max_size) {
char *buf = NULL;
char *buf = nullptr;
int bytes_read;
long int priority;
char pathbuf[64];
@ -330,7 +334,7 @@ void print_pid_priority(struct text_object *obj, char *p, int p_max_size) {
if (*(objbuf.get()) != 0) {
snprintf(pathbuf, 64, PROCDIR "/%d/stat", strtopid(objbuf.get()));
buf = readfile(pathbuf, &bytes_read, 1);
if (buf != NULL) {
if (buf != nullptr) {
sscanf(buf,
"%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %*u %*u %*d "
"%*d %ld",
@ -346,7 +350,7 @@ void print_pid_priority(struct text_object *obj, char *p, int p_max_size) {
void print_pid_state(struct text_object *obj, char *p, int p_max_size) {
#define STATE_ENTRY "State:\t"
#define STATENOTFOUND "Can't find the process state in '%s'"
char *begin, *end, *buf = NULL;
char *begin, *end, *buf = nullptr;
int bytes_read;
char pathbuf[64];
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
@ -355,14 +359,14 @@ void print_pid_state(struct text_object *obj, char *p, int p_max_size) {
snprintf(pathbuf, 64, PROCDIR "/%d/status", strtopid(objbuf.get()));
buf = readfile(pathbuf, &bytes_read, 1);
if (buf != NULL) {
if (buf != nullptr) {
begin = strstr(buf, STATE_ENTRY);
if (begin != NULL) {
if (begin != nullptr) {
begin += strlen(STATE_ENTRY) +
3; // +3 will strip the char representing the short state and
// the space and '(' that follow
end = strchr(begin, '\n');
if (end != NULL) {
if (end != nullptr) {
*(end - 1) = 0; // -1 strips the ')'
}
snprintf(p, p_max_size, "%s", begin);
@ -374,7 +378,7 @@ void print_pid_state(struct text_object *obj, char *p, int p_max_size) {
}
void print_pid_state_short(struct text_object *obj, char *p, int p_max_size) {
char *begin, *buf = NULL;
char *begin, *buf = nullptr;
int bytes_read;
char pathbuf[64];
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
@ -384,9 +388,9 @@ void print_pid_state_short(struct text_object *obj, char *p, int p_max_size) {
snprintf(pathbuf, 64, PROCDIR "/%d/status", strtopid(objbuf.get()));
buf = readfile(pathbuf, &bytes_read, 1);
if (buf != NULL) {
if (buf != nullptr) {
begin = strstr(buf, STATE_ENTRY);
if (begin != NULL) {
if (begin != nullptr) {
snprintf(p, p_max_size, "%c", *begin);
} else {
NORM_ERR(STATENOTFOUND, pathbuf);
@ -457,16 +461,18 @@ void print_cmdline_to_pid(struct text_object *obj, char *p, int p_max_size) {
char pathbuf[64];
dir = opendir(PROCDIR);
if (dir != NULL) {
while ((entry = readdir(dir))) {
if (dir != nullptr) {
while ((entry = readdir(dir)) != nullptr) {
snprintf(pathbuf, 64, PROCDIR "/%s/cmdline", entry->d_name);
buf = readfile(pathbuf, &bytes_read, 0);
if (buf != NULL) {
if (buf != nullptr) {
for (i = 0; i < bytes_read - 1; i++) {
if (buf[i] == 0) buf[i] = ' ';
if (buf[i] == 0) {
buf[i] = ' ';
}
}
if (strstr(buf, obj->data.s) != NULL) {
if (strstr(buf, obj->data.s) != nullptr) {
snprintf(p, p_max_size, "%s", entry->d_name);
free(buf);
closedir(dir);
@ -485,7 +491,7 @@ void print_pid_threads(struct text_object *obj, char *p, int p_max_size) {
#define THREADS_ENTRY "Threads:\t"
#define THREADSNOTFOUND \
"Can't find the number of the threads of the process in '%s'"
char *begin, *end, *buf = NULL;
char *begin, *end, *buf = nullptr;
int bytes_read;
char pathbuf[64];
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
@ -494,12 +500,12 @@ void print_pid_threads(struct text_object *obj, char *p, int p_max_size) {
snprintf(pathbuf, 64, PROCDIR "/%d/status", strtopid(objbuf.get()));
buf = readfile(pathbuf, &bytes_read, 1);
if (buf != NULL) {
if (buf != nullptr) {
begin = strstr(buf, THREADS_ENTRY);
if (begin != NULL) {
if (begin != nullptr) {
begin += strlen(THREADS_ENTRY);
end = strchr(begin, '\n');
if (end != NULL) {
if (end != nullptr) {
*(end) = 0;
}
snprintf(p, p_max_size, "%s", begin);
@ -521,8 +527,8 @@ void print_pid_thread_list(struct text_object *obj, char *p, int p_max_size) {
snprintf(pathbuf, 64, PROCDIR "/%d/task", strtopid(objbuf.get()));
dir = opendir(pathbuf);
if (dir != NULL) {
while ((entry = readdir(dir))) {
if (dir != nullptr) {
while ((entry = readdir(dir)) != nullptr) {
if (entry->d_name[0] != '.') {
snprintf(p + totallength, p_max_size - totallength, "%s,",
entry->d_name);
@ -530,7 +536,9 @@ void print_pid_thread_list(struct text_object *obj, char *p, int p_max_size) {
}
}
closedir(dir);
if (p[totallength - 1] == ',') p[totallength - 1] = 0;
if (p[totallength - 1] == ',') {
p[totallength - 1] = 0;
}
} else {
p[0] = 0;
}
@ -538,7 +546,7 @@ void print_pid_thread_list(struct text_object *obj, char *p, int p_max_size) {
void print_pid_time_kernelmode(struct text_object *obj, char *p,
int p_max_size) {
char *buf = NULL;
char *buf = nullptr;
int bytes_read;
unsigned long int umtime;
char pathbuf[64];
@ -549,10 +557,10 @@ void print_pid_time_kernelmode(struct text_object *obj, char *p,
if (*(objbuf.get()) != 0) {
snprintf(pathbuf, 64, PROCDIR "/%d/stat", strtopid(objbuf.get()));
buf = readfile(pathbuf, &bytes_read, 1);
if (buf != NULL) {
if (buf != nullptr) {
sscanf(buf, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu",
&umtime);
snprintf(p, p_max_size, "%.2f", (float)umtime / 100);
snprintf(p, p_max_size, "%.2f", static_cast<float>(umtime) / 100);
free(buf);
}
} else {
@ -561,7 +569,7 @@ void print_pid_time_kernelmode(struct text_object *obj, char *p,
}
void print_pid_time_usermode(struct text_object *obj, char *p, int p_max_size) {
char *buf = NULL;
char *buf = nullptr;
int bytes_read;
unsigned long int kmtime;
char pathbuf[64];
@ -572,10 +580,10 @@ void print_pid_time_usermode(struct text_object *obj, char *p, int p_max_size) {
if (*(objbuf.get()) != 0) {
snprintf(pathbuf, 64, PROCDIR "/%d/stat", strtopid(objbuf.get()));
buf = readfile(pathbuf, &bytes_read, 1);
if (buf != NULL) {
if (buf != nullptr) {
sscanf(buf, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %*u %lu",
&kmtime);
snprintf(p, p_max_size, "%.2f", (float)kmtime / 100);
snprintf(p, p_max_size, "%.2f", static_cast<float>(kmtime) / 100);
free(buf);
}
} else {
@ -584,7 +592,7 @@ void print_pid_time_usermode(struct text_object *obj, char *p, int p_max_size) {
}
void print_pid_time(struct text_object *obj, char *p, int p_max_size) {
char *buf = NULL;
char *buf = nullptr;
int bytes_read;
unsigned long int umtime, kmtime;
char pathbuf[64];
@ -595,10 +603,11 @@ void print_pid_time(struct text_object *obj, char *p, int p_max_size) {
if (*(objbuf.get()) != 0) {
snprintf(pathbuf, 64, PROCDIR "/%d/stat", strtopid(objbuf.get()));
buf = readfile(pathbuf, &bytes_read, 1);
if (buf != NULL) {
if (buf != nullptr) {
sscanf(buf, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu %lu",
&umtime, &kmtime);
snprintf(p, p_max_size, "%.2f", (float)(umtime + kmtime) / 100);
snprintf(p, p_max_size, "%.2f",
static_cast<float>(umtime + kmtime) / 100);
free(buf);
}
} else {
@ -609,7 +618,7 @@ void print_pid_time(struct text_object *obj, char *p, int p_max_size) {
#define UID_ENTRY "Uid:\t"
void print_pid_uid(struct text_object *obj, char *p, int p_max_size) {
#define UIDNOTFOUND "Can't find the process real uid in '%s'"
char *begin, *end, *buf = NULL;
char *begin, *end, *buf = nullptr;
int bytes_read;
char pathbuf[64];
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
@ -618,12 +627,12 @@ void print_pid_uid(struct text_object *obj, char *p, int p_max_size) {
snprintf(pathbuf, 64, PROCDIR "/%d/status", strtopid(objbuf.get()));
buf = readfile(pathbuf, &bytes_read, 1);
if (buf != NULL) {
if (buf != nullptr) {
begin = strstr(buf, UID_ENTRY);
if (begin != NULL) {
if (begin != nullptr) {
begin += strlen(UID_ENTRY);
end = strchr(begin, '\t');
if (end != NULL) {
if (end != nullptr) {
*(end) = 0;
}
snprintf(p, p_max_size, "%s", begin);
@ -636,7 +645,7 @@ void print_pid_uid(struct text_object *obj, char *p, int p_max_size) {
void print_pid_euid(struct text_object *obj, char *p, int p_max_size) {
#define EUIDNOTFOUND "Can't find the process effective uid in '%s'"
char *begin, *end, *buf = NULL;
char *begin, *end, *buf = nullptr;
int bytes_read;
char pathbuf[64];
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
@ -645,15 +654,15 @@ void print_pid_euid(struct text_object *obj, char *p, int p_max_size) {
snprintf(pathbuf, 64, PROCDIR "/%d/status", strtopid(objbuf.get()));
buf = readfile(pathbuf, &bytes_read, 1);
if (buf != NULL) {
if (buf != nullptr) {
begin = strstr(buf, UID_ENTRY);
if (begin != NULL) {
if (begin != nullptr) {
begin = strchr(begin, '\t');
begin++;
begin = strchr(begin, '\t');
begin++;
end = strchr(begin, '\t');
if (end != NULL) {
if (end != nullptr) {
*(end) = 0;
}
snprintf(p, p_max_size, "%s", begin);
@ -666,7 +675,7 @@ void print_pid_euid(struct text_object *obj, char *p, int p_max_size) {
void print_pid_suid(struct text_object *obj, char *p, int p_max_size) {
#define SUIDNOTFOUND "Can't find the process saved set uid in '%s'"
char *begin, *end, *buf = NULL;
char *begin, *end, *buf = nullptr;
int bytes_read;
char pathbuf[64];
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
@ -675,9 +684,9 @@ void print_pid_suid(struct text_object *obj, char *p, int p_max_size) {
snprintf(pathbuf, 64, PROCDIR "/%d/status", strtopid(objbuf.get()));
buf = readfile(pathbuf, &bytes_read, 1);
if (buf != NULL) {
if (buf != nullptr) {
begin = strstr(buf, UID_ENTRY);
if (begin != NULL) {
if (begin != nullptr) {
begin = strchr(begin, '\t');
begin++;
begin = strchr(begin, '\t');
@ -685,7 +694,7 @@ void print_pid_suid(struct text_object *obj, char *p, int p_max_size) {
begin = strchr(begin, '\t');
begin++;
end = strchr(begin, '\t');
if (end != NULL) {
if (end != nullptr) {
*(end) = 0;
}
snprintf(p, p_max_size, "%s", begin);
@ -698,7 +707,7 @@ void print_pid_suid(struct text_object *obj, char *p, int p_max_size) {
void print_pid_fsuid(struct text_object *obj, char *p, int p_max_size) {
#define FSUIDNOTFOUND "Can't find the process file system uid in '%s'"
char *begin, *end, *buf = NULL;
char *begin, *end, *buf = nullptr;
int bytes_read;
char pathbuf[64];
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
@ -707,9 +716,9 @@ void print_pid_fsuid(struct text_object *obj, char *p, int p_max_size) {
snprintf(pathbuf, 64, PROCDIR "/%d/status", strtopid(objbuf.get()));
buf = readfile(pathbuf, &bytes_read, 1);
if (buf != NULL) {
if (buf != nullptr) {
begin = strstr(buf, UID_ENTRY);
if (begin != NULL) {
if (begin != nullptr) {
begin = strchr(begin, '\t');
begin++;
begin = strchr(begin, '\t');
@ -719,7 +728,7 @@ void print_pid_fsuid(struct text_object *obj, char *p, int p_max_size) {
begin = strchr(begin, '\t');
begin++;
end = strchr(begin, '\n');
if (end != NULL) {
if (end != nullptr) {
*(end) = 0;
}
snprintf(p, p_max_size, "%s", begin);
@ -733,7 +742,7 @@ void print_pid_fsuid(struct text_object *obj, char *p, int p_max_size) {
#define GID_ENTRY "Gid:\t"
void print_pid_gid(struct text_object *obj, char *p, int p_max_size) {
#define GIDNOTFOUND "Can't find the process real gid in '%s'"
char *begin, *end, *buf = NULL;
char *begin, *end, *buf = nullptr;
int bytes_read;
char pathbuf[64];
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
@ -742,12 +751,12 @@ void print_pid_gid(struct text_object *obj, char *p, int p_max_size) {
snprintf(pathbuf, 64, PROCDIR "/%d/status", strtopid(objbuf.get()));
buf = readfile(pathbuf, &bytes_read, 1);
if (buf != NULL) {
if (buf != nullptr) {
begin = strstr(buf, GID_ENTRY);
if (begin != NULL) {
if (begin != nullptr) {
begin += strlen(GID_ENTRY);
end = strchr(begin, '\t');
if (end != NULL) {
if (end != nullptr) {
*(end) = 0;
}
snprintf(p, p_max_size, "%s", begin);
@ -760,7 +769,7 @@ void print_pid_gid(struct text_object *obj, char *p, int p_max_size) {
void print_pid_egid(struct text_object *obj, char *p, int p_max_size) {
#define EGIDNOTFOUND "Can't find the process effective gid in '%s'"
char *begin, *end, *buf = NULL;
char *begin, *end, *buf = nullptr;
int bytes_read;
char pathbuf[64];
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
@ -769,15 +778,15 @@ void print_pid_egid(struct text_object *obj, char *p, int p_max_size) {
snprintf(pathbuf, 64, PROCDIR "/%d/status", strtopid(objbuf.get()));
buf = readfile(pathbuf, &bytes_read, 1);
if (buf != NULL) {
if (buf != nullptr) {
begin = strstr(buf, GID_ENTRY);
if (begin != NULL) {
if (begin != nullptr) {
begin = strchr(begin, '\t');
begin++;
begin = strchr(begin, '\t');
begin++;
end = strchr(begin, '\t');
if (end != NULL) {
if (end != nullptr) {
*(end) = 0;
}
snprintf(p, p_max_size, "%s", begin);
@ -790,7 +799,7 @@ void print_pid_egid(struct text_object *obj, char *p, int p_max_size) {
void print_pid_sgid(struct text_object *obj, char *p, int p_max_size) {
#define SGIDNOTFOUND "Can't find the process saved set gid in '%s'"
char *begin, *end, *buf = NULL;
char *begin, *end, *buf = nullptr;
int bytes_read;
char pathbuf[64];
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
@ -799,9 +808,9 @@ void print_pid_sgid(struct text_object *obj, char *p, int p_max_size) {
snprintf(pathbuf, 64, PROCDIR "/%d/status", strtopid(objbuf.get()));
buf = readfile(pathbuf, &bytes_read, 1);
if (buf != NULL) {
if (buf != nullptr) {
begin = strstr(buf, GID_ENTRY);
if (begin != NULL) {
if (begin != nullptr) {
begin = strchr(begin, '\t');
begin++;
begin = strchr(begin, '\t');
@ -809,7 +818,7 @@ void print_pid_sgid(struct text_object *obj, char *p, int p_max_size) {
begin = strchr(begin, '\t');
begin++;
end = strchr(begin, '\t');
if (end != NULL) {
if (end != nullptr) {
*(end) = 0;
}
snprintf(p, p_max_size, "%s", begin);
@ -822,7 +831,7 @@ void print_pid_sgid(struct text_object *obj, char *p, int p_max_size) {
void print_pid_fsgid(struct text_object *obj, char *p, int p_max_size) {
#define FSGIDNOTFOUND "Can't find the process file system gid in '%s'"
char *begin, *end, *buf = NULL;
char *begin, *end, *buf = nullptr;
int bytes_read;
char pathbuf[64];
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
@ -831,9 +840,9 @@ void print_pid_fsgid(struct text_object *obj, char *p, int p_max_size) {
snprintf(pathbuf, 64, PROCDIR "/%d/status", strtopid(objbuf.get()));
buf = readfile(pathbuf, &bytes_read, 1);
if (buf != NULL) {
if (buf != nullptr) {
begin = strstr(buf, GID_ENTRY);
if (begin != NULL) {
if (begin != nullptr) {
begin = strchr(begin, '\t');
begin++;
begin = strchr(begin, '\t');
@ -843,7 +852,7 @@ void print_pid_fsgid(struct text_object *obj, char *p, int p_max_size) {
begin = strchr(begin, '\t');
begin++;
end = strchr(begin, '\n');
if (end != NULL) {
if (end != nullptr) {
*(end) = 0;
}
snprintf(p, p_max_size, "%s", begin);
@ -856,7 +865,7 @@ void print_pid_fsgid(struct text_object *obj, char *p, int p_max_size) {
void internal_print_pid_vm(struct text_object *obj, char *p, int p_max_size,
const char *entry, const char *errorstring) {
char *begin, *end, *buf = NULL;
char *begin, *end, *buf = nullptr;
int bytes_read;
char pathbuf[64];
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
@ -865,15 +874,15 @@ void internal_print_pid_vm(struct text_object *obj, char *p, int p_max_size,
snprintf(pathbuf, 64, PROCDIR "/%d/status", strtopid(objbuf.get()));
buf = readfile(pathbuf, &bytes_read, 1);
if (buf != NULL) {
if (buf != nullptr) {
begin = strstr(buf, entry);
if (begin != NULL) {
if (begin != nullptr) {
begin += strlen(entry);
while (*begin == '\t' || *begin == ' ') {
begin++;
}
end = strchr(begin, '\n');
if (end != NULL) {
if (end != nullptr) {
*(end) = 0;
}
snprintf(p, p_max_size, "%s", begin);
@ -941,7 +950,7 @@ void print_pid_vmpte(struct text_object *obj, char *p, int p_max_size) {
#define READ_ENTRY "read_bytes: "
#define READNOTFOUND "Can't find the amount of bytes read in '%s'"
void print_pid_read(struct text_object *obj, char *p, int p_max_size) {
char *begin, *end, *buf = NULL;
char *begin, *end, *buf = nullptr;
int bytes_read;
char pathbuf[64];
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
@ -950,11 +959,11 @@ void print_pid_read(struct text_object *obj, char *p, int p_max_size) {
snprintf(pathbuf, 64, PROCDIR "/%d/io", strtopid(objbuf.get()));
buf = readfile(pathbuf, &bytes_read, 1);
if (buf != NULL) {
if (buf != nullptr) {
begin = strstr(buf, READ_ENTRY);
if (begin != NULL) {
if (begin != nullptr) {
end = strchr(begin, '\n');
if (end != NULL) {
if (end != nullptr) {
*(end) = 0;
}
snprintf(p, p_max_size, "%s", begin);
@ -968,7 +977,7 @@ void print_pid_read(struct text_object *obj, char *p, int p_max_size) {
#define WRITE_ENTRY "write_bytes: "
#define WRITENOTFOUND "Can't find the amount of bytes written in '%s'"
void print_pid_write(struct text_object *obj, char *p, int p_max_size) {
char *begin, *end, *buf = NULL;
char *begin, *end, *buf = nullptr;
int bytes_read;
char pathbuf[64];
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
@ -977,11 +986,11 @@ void print_pid_write(struct text_object *obj, char *p, int p_max_size) {
snprintf(pathbuf, 64, PROCDIR "/%d/io", strtopid(objbuf.get()));
buf = readfile(pathbuf, &bytes_read, 1);
if (buf != NULL) {
if (buf != nullptr) {
begin = strstr(buf, WRITE_ENTRY);
if (begin != NULL) {
if (begin != nullptr) {
end = strchr(begin, '\n');
if (end != NULL) {
if (end != nullptr) {
*(end) = 0;
}
snprintf(p, p_max_size, "%s", begin);

View File

@ -30,23 +30,23 @@
void prss_parse_doc(PRSS *result, xmlDocPtr doc);
PRSS::PRSS(const std::string &xml_data)
: version(NULL),
title(NULL),
link(NULL),
description(NULL),
language(NULL),
generator(NULL),
managingEditor(NULL),
webMaster(NULL),
docs(NULL),
lastBuildDate(NULL),
pubDate(NULL),
copyright(NULL),
ttl(NULL),
items(NULL),
: version(nullptr),
title(nullptr),
link(nullptr),
description(nullptr),
language(nullptr),
generator(nullptr),
managingEditor(nullptr),
webMaster(nullptr),
docs(nullptr),
lastBuildDate(nullptr),
pubDate(nullptr),
copyright(nullptr),
ttl(nullptr),
items(nullptr),
item_count(0) {
std::unique_ptr<xmlDoc, void (*)(xmlDoc *)> doc(
xmlReadMemory(xml_data.c_str(), xml_data.length(), "", NULL,
xmlReadMemory(xml_data.c_str(), xml_data.length(), "", nullptr,
PARSE_OPTIONS),
xmlFreeDoc);

View File

@ -51,11 +51,11 @@ const struct pulseaudio_default_results pulseaudio_result0 = {std::string(),
std::string(),
std::string(),
0};
pulseaudio_c *pulseaudio = NULL;
pulseaudio_c *pulseaudio = nullptr;
void pa_sink_info_callback(pa_context *c, const pa_sink_info *i, int eol,
void *data) {
if (i != NULL && data) {
if (i != nullptr && data) {
struct pulseaudio_default_results *pdr =
(struct pulseaudio_default_results *)data;
pdr->sink_description.assign(i->description);
@ -74,7 +74,7 @@ void pa_sink_info_callback(pa_context *c, const pa_sink_info *i, int eol,
void pa_server_info_callback(pa_context *c, const pa_server_info *i,
void *userdata) {
if (i != NULL) {
if (i != nullptr) {
struct pulseaudio_default_results *pdr =
(struct pulseaudio_default_results *)userdata;
pdr->sink_name.assign(i->default_sink_name);
@ -85,7 +85,7 @@ void pa_server_info_callback(pa_context *c, const pa_server_info *i,
void pa_server_sink_info_callback(pa_context *c, const pa_server_info *i,
void *userdata) {
if (i != NULL) {
if (i != nullptr) {
struct pulseaudio_default_results *pdr =
(struct pulseaudio_default_results *)userdata;
pdr->sink_name.assign(i->default_sink_name);
@ -188,7 +188,7 @@ void subscribe_cb(pa_context *c, pa_subscription_event_type_t t, uint32_t index,
void init_pulseaudio(struct text_object *obj) {
// already initialized
(void)obj;
if (pulseaudio != NULL && pulseaudio->cstate == PULSE_CONTEXT_READY) {
if (pulseaudio != nullptr && pulseaudio->cstate == PULSE_CONTEXT_READY) {
pulseaudio->ninits++;
obj->data.opaque = (void *)pulseaudio;
return;
@ -212,9 +212,9 @@ void init_pulseaudio(struct text_object *obj) {
pulseaudio);
// This function connects to the pulse server
if (pa_context_connect(pulseaudio->context, NULL, (pa_context_flags_t)0,
NULL) < 0) {
CRIT_ERR(NULL, NULL, "Cannot connect to pulseaudio");
if (pa_context_connect(pulseaudio->context, nullptr, (pa_context_flags_t)0,
nullptr) < 0) {
CRIT_ERR(nullptr, NULL, "Cannot connect to pulseaudio");
return;
}
pa_threaded_mainloop_start(pulseaudio->mainloop);
@ -254,7 +254,7 @@ void init_pulseaudio(struct text_object *obj) {
(pa_subscription_mask_t)(PA_SUBSCRIPTION_MASK_SINK |
PA_SUBSCRIPTION_MASK_SERVER |
PA_SUBSCRIPTION_MASK_CARD),
NULL, NULL))) {
nullptr, NULL))) {
NORM_ERR("pa_context_subscribe() failed");
return;
}
@ -267,14 +267,14 @@ void free_pulseaudio(struct text_object *obj) {
if (!puau_int) return;
if (--puau_int->ninits > 0) {
obj->data.opaque = NULL;
obj->data.opaque = nullptr;
return;
}
puau_int->cstate = PULSE_CONTEXT_FINISHED;
if (puau_int->context) {
pa_context_set_state_callback(puau_int->context, NULL, NULL);
pa_context_set_state_callback(puau_int->context, nullptr, NULL);
pa_context_disconnect(puau_int->context);
pa_context_unref(puau_int->context);
}
@ -283,7 +283,7 @@ void free_pulseaudio(struct text_object *obj) {
pa_threaded_mainloop_free(puau_int->mainloop);
}
delete puau_int;
puau_int = NULL;
puau_int = nullptr;
}
struct pulseaudio_default_results get_pulseaudio(struct text_object *obj) {

View File

@ -80,9 +80,9 @@ class pulseaudio_c {
int ninits;
struct pulseaudio_default_results result;
pulseaudio_c()
: mainloop(NULL),
mainloop_api(NULL),
context(NULL),
: mainloop(nullptr),
mainloop_api(nullptr),
context(nullptr),
cstate(PULSE_CONTEXT_INITIALIZING),
ninits(0),
result({std::string(), std::string(), std::string(), std::string(), 0,

View File

@ -27,19 +27,23 @@
*
*/
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#include <cerrno>
#include <cinttypes>
#include <cstdlib>
#include <string>
#include "conky.h"
#include "logging.h"
#include "text_object.h"
#ifndef SOCK_CLOEXEC
# define SOCK_CLOEXEC O_CLOEXEC
#endif /* SOCK_CLOEXEC */
struct read_tcpip_data {
char *host;
unsigned int port;
@ -49,10 +53,11 @@ void parse_read_tcpip_arg(struct text_object *obj, const char *arg,
void *free_at_crash) {
struct read_tcpip_data *rtd;
rtd = (struct read_tcpip_data *)malloc(sizeof(struct read_tcpip_data));
rtd = static_cast<struct read_tcpip_data *>(
malloc(sizeof(struct read_tcpip_data)));
memset(rtd, 0, sizeof(struct read_tcpip_data));
rtd->host = (char *)malloc(text_buffer_size.get(*state));
rtd->host = static_cast<char *>(malloc(text_buffer_size.get(*state)));
sscanf(arg, "%s", rtd->host);
sscanf(arg + strlen(rtd->host), "%u", &(rtd->port));
if (rtd->port == 0) {
@ -73,10 +78,10 @@ void parse_tcp_ping_arg(struct text_object *obj, const char *arg,
char *hostname;
struct hostent *he;
addr = (struct sockaddr_in *)malloc(sizeof(struct sockaddr_in));
addr = static_cast<struct sockaddr_in *>(malloc(sizeof(struct sockaddr_in)));
obj->data.opaque = addr;
memset(addr, 0, sizeof(struct sockaddr_in));
hostname = (char *)malloc(strlen(arg) + 1);
hostname = static_cast<char *>(malloc(strlen(arg) + 1));
switch (sscanf(arg, "%s %" SCNu16, hostname, &(addr->sin_port))) {
case 1:
addr->sin_port = DEFAULT_TCP_PING_PORT;
@ -87,10 +92,10 @@ void parse_tcp_ping_arg(struct text_object *obj, const char *arg,
free(hostname);
CRIT_ERR(obj, free_at_crash, "tcp_ping: Reading arguments failed");
}
if (!(he = gethostbyname(hostname))) {
if ((he = gethostbyname(hostname)) == nullptr) {
NORM_ERR("tcp_ping: Problem with resolving '%s', using 'localhost' instead",
hostname);
if (!(he = gethostbyname("localhost"))) {
if ((he = gethostbyname("localhost")) == nullptr) {
free(hostname);
CRIT_ERR(obj, free_at_crash,
"tcp_ping: Resolving 'localhost' also failed");
@ -103,10 +108,11 @@ void parse_tcp_ping_arg(struct text_object *obj, const char *arg,
}
void print_tcp_ping(struct text_object *obj, char *p, int p_max_size) {
struct timeval tv1, tv2, timeout;
struct sockaddr_in *addr = (struct sockaddr_in *)obj->data.opaque;
struct timeval tv1 {
}, tv2{}, timeout{};
auto *addr = static_cast<struct sockaddr_in *>(obj->data.opaque);
int addrlen = sizeof(struct sockaddr);
int sock = socket(addr->sin_family, SOCK_STREAM, IPPROTO_TCP);
int sock = socket(addr->sin_family, SOCK_STREAM | SOCK_CLOEXEC, IPPROTO_TCP);
unsigned long long usecdiff;
fd_set writefds;
@ -116,14 +122,14 @@ void print_tcp_ping(struct text_object *obj, char *p, int p_max_size) {
FD_ZERO(&writefds);
FD_SET(sock, &writefds);
#define TCP_PING_TIMEOUT 10
timeout.tv_sec = (int)TCP_PING_TIMEOUT;
timeout.tv_sec = TCP_PING_TIMEOUT;
timeout.tv_usec = (TCP_PING_TIMEOUT - timeout.tv_sec) * 1000000;
connect(sock, (struct sockaddr *)addr,
connect(sock, reinterpret_cast<struct sockaddr *>(addr),
addrlen); // this will "fail" because sock is non-blocking
if (errno == EINPROGRESS) { // but EINPROGRESS is only a "false fail"
gettimeofday(&tv1, 0);
if (select(sock + 1, NULL, &writefds, NULL, &timeout) != -1) {
gettimeofday(&tv2, 0);
gettimeofday(&tv1, nullptr);
if (select(sock + 1, nullptr, &writefds, nullptr, &timeout) != -1) {
gettimeofday(&tv2, nullptr);
usecdiff =
((tv2.tv_sec - tv1.tv_sec) * 1000000) + tv2.tv_usec - tv1.tv_usec;
if (usecdiff <= TCP_PING_TIMEOUT * 1000000) {
@ -148,13 +154,15 @@ void print_read_tcpip(struct text_object *obj, char *p, int p_max_size,
int protocol) {
int sock, received;
fd_set readfds;
struct timeval tv;
struct read_tcpip_data *rtd = (struct read_tcpip_data *)obj->data.opaque;
struct addrinfo hints;
struct timeval tv {};
auto *rtd = static_cast<struct read_tcpip_data *>(obj->data.opaque);
struct addrinfo hints {};
struct addrinfo *airesult, *rp;
char portbuf[8];
if (!rtd) return;
if (rtd == nullptr) {
return;
}
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
@ -162,12 +170,12 @@ void print_read_tcpip(struct text_object *obj, char *p, int p_max_size,
hints.ai_flags = 0;
hints.ai_protocol = protocol;
snprintf(portbuf, 8, "%d", rtd->port);
if (getaddrinfo(rtd->host, portbuf, &hints, &airesult)) {
if (getaddrinfo(rtd->host, portbuf, &hints, &airesult) != 0) {
NORM_ERR("%s: Problem with resolving the hostname",
protocol == IPPROTO_TCP ? "read_tcp" : "read_udp");
return;
}
for (rp = airesult; rp != NULL; rp = rp->ai_next) {
for (rp = airesult; rp != nullptr; rp = rp->ai_next) {
sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sock == -1) {
continue;
@ -179,7 +187,7 @@ void print_read_tcpip(struct text_object *obj, char *p, int p_max_size,
return;
}
freeaddrinfo(airesult);
if (rp == NULL) {
if (rp == nullptr) {
if (protocol == IPPROTO_TCP) {
NORM_ERR("read_tcp: Couldn't create a connection");
} else {
@ -191,7 +199,7 @@ void print_read_tcpip(struct text_object *obj, char *p, int p_max_size,
if (protocol == IPPROTO_UDP) {
// when using udp send a zero-length packet to let the other end know of our
// existence
if (write(sock, NULL, 0) < 0) {
if (write(sock, nullptr, 0) < 0) {
NORM_ERR("read_udp: Couldn't create a empty package");
}
}
@ -199,12 +207,13 @@ void print_read_tcpip(struct text_object *obj, char *p, int p_max_size,
FD_SET(sock, &readfds);
tv.tv_sec = 1;
tv.tv_usec = 0;
if (select(sock + 1, &readfds, NULL, NULL, &tv) > 0) {
if (select(sock + 1, &readfds, nullptr, nullptr, &tv) > 0) {
received = recv(sock, p, p_max_size, 0);
if (received != -1)
if (received != -1) {
p[received] = 0;
else
} else {
p[0] = 0;
}
}
close(sock);
}
@ -218,18 +227,22 @@ void print_read_udp(struct text_object *obj, char *p, int p_max_size) {
}
void free_read_tcpip(struct text_object *obj) {
struct read_tcpip_data *rtd = (struct read_tcpip_data *)obj->data.opaque;
auto *rtd = static_cast<struct read_tcpip_data *>(obj->data.opaque);
if (!rtd) return;
if (rtd == nullptr) {
return;
}
free_and_zero(rtd->host);
free_and_zero(obj->data.opaque);
}
void free_tcp_ping(struct text_object *obj) {
struct sockaddr_in *addr = (struct sockaddr_in *)obj->data.opaque;
auto *addr = static_cast<struct sockaddr_in *>(obj->data.opaque);
if (!addr) return;
if (addr == nullptr) {
return;
}
free_and_zero(obj->data.opaque);
}

View File

@ -26,13 +26,13 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <vector>
#include "conky.h"
#include "core.h"
#include "logging.h"
#include "specials.h"
#include "text_object.h"
#include "x11.h"
#include <vector>
/**
* Length of a character in bytes.
@ -41,14 +41,20 @@
inline int scroll_character_length(char c) {
#ifdef BUILD_X11
if (utf8_mode.get(*state)) {
unsigned char uc = (unsigned char)c;
auto uc = static_cast<unsigned char>(c);
int len = 0;
if (c == -1) return 1;
if (c == -1) {
return 1;
}
if ((uc & 0x80) == 0) return 1;
if ((uc & 0x80) == 0) {
return 1;
}
while (len < 7 && (uc & (0x80 >> len)) != 0) ++len;
while (len < 7 && (uc & (0x80 >> len)) != 0) {
++len;
}
return len;
}
@ -124,7 +130,7 @@ static void scroll_scroll_right(struct scroll_data *sd,
unsigned int amount) {
for (int i = 0; i < amount; ++i) {
if (sd->start <= 0) {
sd->start = (int)strlen(&(buf[0]));
sd->start = static_cast<int>(strlen(&(buf[0])));
}
while (--(sd->start) >= 0) {
@ -141,23 +147,26 @@ void parse_scroll_arg(struct text_object *obj, const char *arg,
int n1 = 0, n2 = 0;
char dirarg[6];
sd = (struct scroll_data *)malloc(sizeof(struct scroll_data));
sd = static_cast<struct scroll_data *>(malloc(sizeof(struct scroll_data)));
memset(sd, 0, sizeof(struct scroll_data));
sd->resetcolor = get_current_text_color();
sd->step = 1;
sd->direction = SCROLL_LEFT;
if (arg && sscanf(arg, "%5s %n", dirarg, &n1) == 1) {
if (strcasecmp(dirarg, "right") == 0 || strcasecmp(dirarg, "r") == 0)
if ((arg != nullptr) && sscanf(arg, "%5s %n", dirarg, &n1) == 1) {
if (strcasecmp(dirarg, "right") == 0 || strcasecmp(dirarg, "r") == 0) {
sd->direction = SCROLL_RIGHT;
else if (strcasecmp(dirarg, "wait") == 0 || strcasecmp(dirarg, "w") == 0)
} else if (strcasecmp(dirarg, "wait") == 0 ||
strcasecmp(dirarg, "w") == 0) {
sd->direction = SCROLL_WAIT;
else if (strcasecmp(dirarg, "left") != 0 && strcasecmp(dirarg, "l") != 0)
} else if (strcasecmp(dirarg, "left") != 0 &&
strcasecmp(dirarg, "l") != 0) {
n1 = 0;
}
}
if (!arg || sscanf(arg + n1, "%u %n", &sd->show, &n2) <= 0) {
if ((arg == nullptr) || sscanf(arg + n1, "%u %n", &sd->show, &n2) <= 0) {
free(sd);
#ifdef BUILD_X11
free(obj->next);
@ -182,19 +191,21 @@ void parse_scroll_arg(struct text_object *obj, const char *arg,
sd->wait_arg = sd->wait = 0;
}
sd->text = (char *)malloc(strlen(arg + n1) + sd->show + 1);
sd->text = static_cast<char *>(malloc(strlen(arg + n1) + sd->show + 1));
if (strlen(arg) > sd->show && sd->direction != SCROLL_WAIT) {
for (n2 = 0; (unsigned int)n2 < sd->show; n2++) {
for (n2 = 0; static_cast<unsigned int>(n2) < sd->show; n2++) {
sd->text[n2] = ' ';
}
sd->text[n2] = 0;
} else
} else {
sd->text[0] = 0;
}
strcat(sd->text, arg + n1);
sd->start = sd->direction == SCROLL_WAIT ? strlen(sd->text) : 0;
obj->sub = (struct text_object *)malloc(sizeof(struct text_object));
obj->sub =
static_cast<struct text_object *>(malloc(sizeof(struct text_object)));
extract_variable_text_internal(obj->sub, sd->text);
obj->data.opaque = sd;
@ -205,14 +216,16 @@ void parse_scroll_arg(struct text_object *obj, const char *arg,
}
void print_scroll(struct text_object *obj, char *p, int p_max_size) {
struct scroll_data *sd = (struct scroll_data *)obj->data.opaque;
auto *sd = static_cast<struct scroll_data *>(obj->data.opaque);
unsigned int j, colorchanges = 0, frontcolorchanges = 0,
visibcolorchanges = 0, strend;
unsigned int visiblechars = 0;
char *pwithcolors;
std::vector<char> buf(max_user_text.get(*state), (char)0);
std::vector<char> buf(max_user_text.get(*state), static_cast<char>(0));
if (!sd) return;
if (sd == nullptr) {
return;
}
generate_text_internal(&(buf[0]), max_user_text.get(*state), *obj->sub);
for (j = 0; buf[j] != 0; j++) {
@ -256,7 +269,7 @@ void print_scroll(struct text_object *obj, char *p, int p_max_size) {
} else {
int l = scroll_character_length(c);
while (--l) {
while (--l != 0) {
p[j] = buf[sd->start + j];
++j;
}
@ -270,11 +283,13 @@ void print_scroll(struct text_object *obj, char *p, int p_max_size) {
p[j] = 0;
// count colorchanges in front of the visible part and place that many
// colorchanges in front of the visible part
for (j = 0; j < (unsigned)sd->start; j++) {
if (buf[j] == SPECIAL_CHAR) frontcolorchanges++;
for (j = 0; j < static_cast<unsigned>(sd->start); j++) {
if (buf[j] == SPECIAL_CHAR) {
frontcolorchanges++;
}
}
pwithcolors =
(char *)malloc(strlen(p) + 4 + colorchanges - visibcolorchanges);
pwithcolors = static_cast<char *>(
malloc(strlen(p) + 4 + colorchanges - visibcolorchanges));
for (j = 0; j < frontcolorchanges; j++) {
pwithcolors[j] = SPECIAL_CHAR;
}
@ -296,14 +311,14 @@ void print_scroll(struct text_object *obj, char *p, int p_max_size) {
unsigned int charsleft = scroll_count_characters_to_right(sd, buf);
if (sd->show >= charsleft) {
if (sd->wait_arg && (--sd->wait <= 0 && sd->wait_arg != 1)) {
if ((sd->wait_arg != 0u) && (--sd->wait <= 0 && sd->wait_arg != 1)) {
sd->wait = sd->wait_arg;
} else {
sd->start = 0;
}
} else {
if (!sd->wait_arg || sd->wait_arg == 1 ||
(sd->wait_arg && sd->wait-- <= 0)) {
if ((sd->wait_arg == 0u) || sd->wait_arg == 1 ||
((sd->wait_arg != 0u) && sd->wait-- <= 0)) {
sd->wait = 0;
if (sd->step < charsleft) {
@ -318,15 +333,18 @@ void print_scroll(struct text_object *obj, char *p, int p_max_size) {
}
#ifdef BUILD_X11
// reset color when scroll is finished
if (out_to_x.get(*state))
if (out_to_x.get(*state)) {
new_special(p + strlen(p), FG)->arg = sd->resetcolor;
}
#endif
}
void free_scroll(struct text_object *obj) {
struct scroll_data *sd = (struct scroll_data *)obj->data.opaque;
auto *sd = static_cast<struct scroll_data *>(obj->data.opaque);
if (!sd) return;
if (sd == nullptr) {
return;
}
free_and_zero(sd->text);
free_text_objects(obj->sub);

View File

@ -45,18 +45,18 @@ class semaphore {
semaphore &operator=(const semaphore &) = delete;
public:
semaphore(unsigned int value = 0) throw(std::logic_error) {
semaphore(unsigned int value = 0) {
sem = dispatch_semaphore_create(value);
if (!sem) throw std::logic_error(strerror(errno));
}
~semaphore() throw() { dispatch_release(sem); }
void post() throw(std::overflow_error) { dispatch_semaphore_signal(sem); }
~semaphore() { dispatch_release(sem); }
void post() { dispatch_semaphore_signal(sem); }
void wait() throw() { dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); }
void wait() { dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); }
bool trywait() throw() {
bool trywait() {
/* XXX Quick patch */
#define DISPATCH_EAGAIN 49
@ -83,23 +83,23 @@ class semaphore {
semaphore &operator=(const semaphore &) = delete;
public:
semaphore(unsigned int value = 0) throw(std::logic_error) {
semaphore(unsigned int value = 0) {
if (sem_init(&sem, 0, value)) throw std::logic_error(strerror(errno));
}
~semaphore() throw() { sem_destroy(&sem); }
~semaphore() { sem_destroy(&sem); }
void post() throw(std::overflow_error) {
void post() {
if (sem_post(&sem)) throw std::overflow_error(strerror(errno));
}
void wait() throw() {
void wait() {
while (sem_wait(&sem)) {
if (errno != EINTR) abort();
}
}
bool trywait() throw() {
bool trywait() {
while (sem_trywait(&sem)) {
if (errno == EAGAIN)
return false;

View File

@ -27,6 +27,7 @@
#include <algorithm>
#include <memory>
#include <unordered_map>
#include <utility>
#include <vector>
namespace conky {
@ -34,7 +35,7 @@ namespace conky {
namespace {
typedef std::unordered_map<std::string, priv::config_setting_base *>
settings_map;
typedef std::vector<priv::config_setting_base *> settings_vector;
using settings_vector = std::vector<priv::config_setting_base *>;
/*
* We cannot construct this object statically, because order of object
@ -46,20 +47,20 @@ settings_map *settings;
/*
* Returns the setting record corresponding to the value at the specified index.
* If the value is not valid, returns NULL and prints an error.
* If the value is not valid, returns nullptr and prints an error.
*/
priv::config_setting_base *get_setting(lua::state &l, int index) {
lua::Type type = l.type(index);
if (type != lua::TSTRING) {
NORM_ERR("invalid setting of type '%s'", l.type_name(type));
return NULL;
return nullptr;
}
const std::string &name = l.tostring(index);
auto iter = settings->find(name);
if (iter == settings->end()) {
NORM_ERR("Unknown setting '%s'", name.c_str());
return NULL;
return nullptr;
}
return iter->second;
@ -70,8 +71,9 @@ settings_vector make_settings_vector() {
settings_vector ret;
ret.reserve(settings->size());
for (auto i = settings->begin(); i != settings->end(); ++i)
ret.push_back(i->second);
for (auto &setting : *settings) {
ret.push_back(setting.second);
}
sort(ret.begin(), ret.end(), &priv::config_setting_base::seq_compare);
return ret;
@ -86,7 +88,7 @@ size_t get_next_seq_no() {
settings_constructor() { settings = new settings_map; }
~settings_constructor() {
delete settings;
settings = NULL;
settings = nullptr;
}
};
static settings_constructor constructor;
@ -97,12 +99,13 @@ size_t get_next_seq_no() {
namespace priv {
config_setting_base::config_setting_base(const std::string &name_)
: name(name_), seq_no(get_next_seq_no()) {
config_setting_base::config_setting_base(std::string name_)
: name(std::move(name_)), seq_no(get_next_seq_no()) {
bool inserted = settings->insert({name, this}).second;
if (not inserted)
if (not inserted) {
throw std::logic_error("Setting with name '" + name +
"' already registered");
}
}
void config_setting_base::lua_set(lua::state &l) {
@ -128,7 +131,9 @@ void config_setting_base::process_setting(lua::state &l, bool init) {
lua::stack_sentry s(l, -3);
config_setting_base *ptr = get_setting(l, -3);
if (not ptr) return;
if (ptr == nullptr) {
return;
}
ptr->lua_setter(l, init);
l.pushvalue(-2);
@ -194,13 +199,15 @@ void set_config_settings(lua::state &l) {
l.getglobal("conky");
{
if (l.type(-1) != lua::TTABLE)
if (l.type(-1) != lua::TTABLE) {
throw std::runtime_error("conky must be a table");
}
l.rawgetfield(-1, "config");
{
if (l.type(-1) != lua::TTABLE)
if (l.type(-1) != lua::TTABLE) {
throw std::runtime_error("conky.config must be a table");
}
priv::config_setting_base::make_conky_config(l);
l.rawsetfield(-3, "config");
@ -211,9 +218,9 @@ void set_config_settings(lua::state &l) {
{
const settings_vector &v = make_settings_vector();
for (size_t i = 0; i < v.size(); ++i) {
l.pushstring(v[i]->name);
l.rawgetfield(-3, v[i]->name.c_str());
for (auto i : v) {
l.pushstring(i->name);
l.rawgetfield(-3, i->name.c_str());
l.pushnil();
priv::config_setting_base::process_setting(l, true);
}

View File

@ -174,7 +174,7 @@ class config_setting_base {
return a->seq_no < b->seq_no;
}
explicit config_setting_base(const std::string &name_);
explicit config_setting_base(std::string name_);
virtual ~config_setting_base() {}
/*

View File

@ -58,7 +58,7 @@ static int smapi_bat_installed_internal(int idx) {
static char *smapi_read_str(const char *path) {
FILE *fp;
char str[256] = "failed";
if ((fp = fopen(path, "r")) != NULL) {
if ((fp = fopen(path, "r")) != nullptr) {
if (fscanf(fp, "%255s\n", str) < 0) perror("fscanf()");
fclose(fp);
}
@ -67,7 +67,7 @@ static char *smapi_read_str(const char *path) {
static char *smapi_get_str(const char *fname) {
char path[128];
if (snprintf(path, 127, SYS_SMAPI_PATH "/%s", fname) < 0) return NULL;
if (snprintf(path, 127, SYS_SMAPI_PATH "/%s", fname) < 0) return nullptr;
return smapi_read_str(path);
}
@ -75,7 +75,7 @@ static char *smapi_get_str(const char *fname) {
static char *smapi_get_bat_str(int idx, const char *fname) {
char path[128];
if (snprintf(path, 127, SYS_SMAPI_PATH "/BAT%i/%s", idx, fname) < 0)
return NULL;
return nullptr;
return smapi_read_str(path);
}
@ -92,10 +92,10 @@ static char *smapi_get_bat_val(const char *args) {
if (sscanf(args, "%i %n", &idx, &cnt) <= 0 ||
snprintf(fname, 127, "%s", (args + cnt)) < 0) {
NORM_ERR("smapi: wrong arguments, should be 'bat,<int>,<str>'");
return NULL;
return nullptr;
}
if (!smapi_bat_installed_internal(idx)) return NULL;
if (!smapi_bat_installed_internal(idx)) return nullptr;
return smapi_get_bat_str(idx, fname);
}
@ -103,7 +103,7 @@ static char *smapi_get_bat_val(const char *args) {
static char *smapi_get_val(const char *args) {
char str[128];
if (!args || sscanf(args, "%127s", str) <= 0) return NULL;
if (!args || sscanf(args, "%127s", str) <= 0) return nullptr;
if (!strcmp(str, "bat")) return smapi_get_bat_val(args + 4);

View File

@ -65,10 +65,10 @@ static int pagetok(int pages) {
}
static void update_kstat() {
time_t now = time(NULL);
time_t now = time(nullptr);
if (kstat == NULL) {
if ((kstat = kstat_open()) == NULL) {
if (kstat == nullptr) {
if ((kstat = kstat_open()) == nullptr) {
NORM_ERR("can't open kstat: %s", strerror(errno));
return;
}
@ -91,13 +91,13 @@ static kstat_named_t *get_kstat(const char *module, int inst, const char *name,
update_kstat();
ksp = kstat_lookup(kstat, (char *)module, inst, (char *)name);
if (ksp == NULL) {
if (ksp == nullptr) {
NORM_ERR("cannot lookup kstat %s:%d:%s:%s %s", module, inst, name, stat,
strerror(errno));
return NULL;
return nullptr;
}
if (kstat_read(kstat, ksp, NULL) >= 0) {
if (kstat_read(kstat, ksp, nullptr) >= 0) {
if (ksp->ks_type == KSTAT_TYPE_NAMED || ksp->ks_type == KSTAT_TYPE_TIMER) {
kstat_named_t *knp =
(kstat_named_t *)kstat_data_lookup(ksp, (char *)stat);
@ -105,11 +105,11 @@ static kstat_named_t *get_kstat(const char *module, int inst, const char *name,
} else {
NORM_ERR("kstat %s:%d:%s:%s has unexpected type %d", module, inst, name,
stat, ksp->ks_type);
return NULL;
return nullptr;
}
}
NORM_ERR("cannot read kstat %s:%d:%s:%s", module, inst, name, stat);
return NULL;
return nullptr;
}
void prepare_update() { kstat_updated = 0; }
@ -124,7 +124,7 @@ int update_meminfo() {
/* RAM stats */
knp = get_kstat("unix", -1, "system_pages", "freemem");
if (knp != NULL) info.memfree = pagetok(knp->value.ui32);
if (knp != nullptr) info.memfree = pagetok(knp->value.ui32);
info.memmax = pagetok(sysconf(_SC_PHYS_PAGES));
if (info.memmax > info.memfree)
info.mem = info.memmax - info.memfree;
@ -136,7 +136,7 @@ int update_meminfo() {
/* for swapctl(2) */
swt =
(struct swaptable *)malloc(nswap * sizeof(struct swapent) + sizeof(int));
if (swt == NULL) return 0;
if (swt == nullptr) return 0;
swt->swt_n = nswap;
swe = &(swt->swt_ent[0]);
/* We are not interested in ste_path */
@ -180,7 +180,7 @@ double get_acpi_temperature(int fd) {
int update_total_processes(void) {
kstat_named_t *knp = get_kstat("unix", -1, "system_misc", "nproc");
if (knp != NULL) info.procs = knp->value.ui32;
if (knp != nullptr) info.procs = knp->value.ui32;
return 0;
}
@ -223,7 +223,7 @@ int update_net_stats(void) {
long long r, t;
kstat_named_t *knp;
ns = get_net_stat((const char *)ifr->ifr_name, NULL, NULL);
ns = get_net_stat((const char *)ifr->ifr_name, nullptr, NULL);
ns->up = 1;
memcpy(&(ns->addr), &ifr->ifr_addr, sizeof(ifr->ifr_addr));
@ -235,7 +235,7 @@ int update_net_stats(void) {
/* Get received bytes */
knp = get_kstat("link", -1, ifr->ifr_name, "rbytes");
if (knp == NULL) {
if (knp == nullptr) {
NORM_ERR("cannot read rbytes for %s\n", ifr->ifr_name);
continue;
}
@ -249,7 +249,7 @@ int update_net_stats(void) {
/* Get transceived bytes */
knp = get_kstat("link", -1, ifr->ifr_name, "obytes");
if (knp == NULL) {
if (knp == nullptr) {
NORM_ERR("cannot read obytes for %s\n", ifr->ifr_name);
continue;
}
@ -269,7 +269,7 @@ int update_net_stats(void) {
int update_cpu_usage(void) {
static int last_cpu_cnt = 0;
static int *last_cpu_use = NULL;
static int *last_cpu_use = nullptr;
double d = current_update_time - last_update_time;
int cpu;
@ -280,10 +280,10 @@ int update_cpu_usage(void) {
info.cpu_count = sysconf(_SC_NPROCESSORS_ONLN);
/* (Re)allocate the array with previous values */
if (last_cpu_cnt != info.cpu_count || last_cpu_use == NULL) {
if (last_cpu_cnt != info.cpu_count || last_cpu_use == nullptr) {
last_cpu_use = (int *)realloc(last_cpu_use, info.cpu_count * sizeof(int));
last_cpu_cnt = info.cpu_count;
if (last_cpu_use == NULL) return 0;
if (last_cpu_use == nullptr) return 0;
}
info.cpu_usage = (float *)malloc(info.cpu_count * sizeof(float));
@ -297,8 +297,8 @@ int update_cpu_usage(void) {
snprintf(stat_name, PATH_MAX, "cpu_stat%d", cpu);
ksp = kstat_lookup(kstat, (char *)"cpu_stat", cpu, stat_name);
if (ksp == NULL) continue;
if (kstat_read(kstat, ksp, NULL) == -1) continue;
if (ksp == nullptr) continue;
if (kstat_read(kstat, ksp, nullptr) == -1) continue;
cs = (cpu_stat_t *)ksp->ks_data;
cpu_idle = cs->cpu_sysinfo.cpu[CPU_IDLE];
@ -355,7 +355,7 @@ void get_top_info(void) {
while ((entry = readdir(dir))) {
pid_t pid;
if (entry == NULL) break;
if (entry == nullptr) break;
if (sscanf(entry->d_name, "%u", &pid) != 1) continue;
update_proc_entry(get_process(pid));
}
@ -380,9 +380,9 @@ int update_diskio(void) {
kstat_io_t *ksio;
kstat_t *ksp;
if (cur->dev == NULL) continue;
if ((ksp = kstat_lookup(kstat, NULL, -1, cur->dev)) == NULL) continue;
if (kstat_read(kstat, ksp, NULL) == -1) continue;
if (cur->dev == nullptr) continue;
if ((ksp = kstat_lookup(kstat, nullptr, -1, cur->dev)) == NULL) continue;
if (kstat_read(kstat, ksp, nullptr) == -1) continue;
ksio = (kstat_io_t *)ksp->ks_data;
tot_read += read = (unsigned int)(ksio->nread / 512);
tot_written += written = (unsigned int)(ksio->nwritten / 512);
@ -432,7 +432,7 @@ char get_freq(char *p_client_buffer, size_t client_buffer_size,
snprintf(stat_name, PATH_MAX, "cpu_info%d", cpu - 1);
knp = get_kstat("cpu_info", cpu - 1, stat_name, "current_clock_Hz");
if (knp == NULL) return 0;
if (knp == nullptr) return 0;
snprintf(p_client_buffer, client_buffer_size, p_format,
(float)knp->value.ui32 / divisor / 1000000.0);
return 1;
@ -442,8 +442,8 @@ int update_uptime(void) {
kstat_named_t *knp;
knp = get_kstat("unix", -1, "system_misc", "boot_time");
if (knp == NULL) return 0;
info.uptime = time(NULL) - knp->value.ui32;
if (knp == nullptr) return 0;
info.uptime = time(nullptr) - knp->value.ui32;
return 1;
}
@ -472,5 +472,5 @@ int update_load_average(void) {
void get_cpu_count(void) {
kstat_named_t *knp = get_kstat("unix", -1, "system_misc", "ncpus");
if (knp != NULL) info.cpu_count = knp->value.ui32;
if (knp != nullptr) info.cpu_count = knp->value.ui32;
}

View File

@ -58,11 +58,11 @@ void get_sony_fanspeed(struct text_object *obj, char *p_client_buffer,
snprintf(fan, 127, "%s/fanspeed", SONY_LAPTOP_DIR);
fp = fopen(fan, "r");
if (fp != NULL) {
if (fp != nullptr) {
while (!feof(fp)) {
char line[256];
if (fgets(line, 255, fp) == NULL) {
if (fgets(line, 255, fp) == nullptr) {
break;
}
if (sscanf(line, "%u", &speed)) {
@ -70,7 +70,7 @@ void get_sony_fanspeed(struct text_object *obj, char *p_client_buffer,
}
}
} else {
CRIT_ERR(NULL, NULL,
CRIT_ERR(nullptr, NULL,
"can't open '%s': %s\nEnable sony support or remove "
"sony* from your " PACKAGE_NAME " config file.",
fan, strerror(errno));

View File

@ -30,18 +30,18 @@
#ifdef BUILD_X11
#include "fonts.h"
#endif /* BUILD_X11 */
#include <math.h>
#include <cmath>
#include "logging.h"
#include "nc.h"
#include "specials.h"
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif /* HAVE_SYS_PARAM_H */
#include "colours.h"
#include <algorithm>
#include <sstream>
#include "colours.h"
struct special_t *specials = NULL;
struct special_t *specials = nullptr;
int special_count;
@ -112,20 +112,21 @@ const char *scan_gauge(struct text_object *obj, const char *args,
double scale) {
struct gauge *g;
g = (struct gauge *)malloc(sizeof(struct gauge));
g = static_cast<struct gauge *>(malloc(sizeof(struct gauge)));
memset(g, 0, sizeof(struct gauge));
/*width and height*/
g->width = default_gauge_width.get(*state);
g->height = default_gauge_height.get(*state);
if (scale)
if (scale != 0.0) {
g->scale = scale;
else
} else {
g->flags |= SF_SCALED;
}
/* gauge's argument is either height or height,width */
if (args) {
if (args != nullptr) {
int n = 0;
if (sscanf(args, "%d,%d %n", &g->height, &g->width, &n) <= 1) {
@ -144,20 +145,21 @@ const char *scan_gauge(struct text_object *obj, const char *args,
const char *scan_bar(struct text_object *obj, const char *args, double scale) {
struct bar *b;
b = (struct bar *)malloc(sizeof(struct bar));
b = static_cast<struct bar *>(malloc(sizeof(struct bar)));
memset(b, 0, sizeof(struct bar));
/* zero width means all space that is available */
b->width = default_bar_width.get(*state);
b->height = default_bar_height.get(*state);
if (scale)
if (scale != 0.0) {
b->scale = scale;
else
} else {
b->flags |= SF_SCALED;
}
/* bar's argument is either height or height,width */
if (args) {
if (args != nullptr) {
int n = 0;
if (sscanf(args, "%d,%d %n", &b->height, &b->width, &n) <= 1) {
@ -172,7 +174,9 @@ const char *scan_bar(struct text_object *obj, const char *args, double scale) {
#ifdef BUILD_X11
void scan_font(struct text_object *obj, const char *args) {
if (args && *args) obj->data.s = strndup(args, DEFAULT_TEXT_BUFFER_SIZE);
if ((args != nullptr) && (*args != 0)) {
obj->data.s = strndup(args, DEFAULT_TEXT_BUFFER_SIZE);
}
}
/**
@ -184,7 +188,7 @@ void scan_font(struct text_object *obj, const char *args) {
* @param[out] obj struct in which to save width, height and other options
* @param[in] args argument string to parse
* @param[in] defscale default scale if no scale argument given
* @return string to the command argument, NULL if argument didn't start with
* @return string to the command argument, nullptr if argument didn't start with
* a string, but a number or if invalid argument string
**/
char *scan_graph(struct text_object *obj, const char *args, double defscale) {
@ -192,7 +196,7 @@ char *scan_graph(struct text_object *obj, const char *args, double defscale) {
char argstr[1024] = {'\0'}; /* args minus quoted_cmd */
char buf[1024] = {'\0'}; /* first unquoted string argument in argstr */
struct graph *g = (struct graph *)malloc(sizeof(struct graph));
auto *g = static_cast<struct graph *>(malloc(sizeof(struct graph)));
memset(g, 0, sizeof(struct graph));
obj->special_data = g;
@ -203,16 +207,17 @@ char *scan_graph(struct text_object *obj, const char *args, double defscale) {
g->last_colour = 0;
g->scale = defscale;
g->tempgrad = FALSE;
if (args) {
if (args != nullptr) {
/* extract double-quoted command in case of execgraph */
if (*args == '"') {
char *_ptr;
size_t _size;
if ((_ptr = const_cast<char *>(strrchr(args, '"'))) && _ptr != args) {
if (((_ptr = const_cast<char *>(strrchr(args, '"'))) != nullptr) &&
_ptr != args) {
_size = _ptr - args - 1;
} else {
NORM_ERR("mismatched double-quote in execgraph object");
return NULL;
return nullptr;
}
_size = _size < 1024 ? _size : 1023;
@ -230,13 +235,13 @@ char *scan_graph(struct text_object *obj, const char *args, double defscale) {
/* set tempgrad to true, if '-t' specified.
* It doesn#t matter where the argument is exactly. */
if (strstr(argstr, " " TEMPGRAD) ||
if ((strstr(argstr, " " TEMPGRAD) != nullptr) ||
strncmp(argstr, TEMPGRAD, strlen(TEMPGRAD)) == 0) {
g->tempgrad = TRUE;
}
/* set showlog-flag, if '-l' specified
* It doesn#t matter where the argument is exactly. */
if (strstr(argstr, " " LOGGRAPH) ||
if ((strstr(argstr, " " LOGGRAPH) != nullptr) ||
strncmp(argstr, LOGGRAPH, strlen(LOGGRAPH)) == 0) {
g->flags |= SF_SHOWLOG;
}
@ -250,15 +255,17 @@ char *scan_graph(struct text_object *obj, const char *args, double defscale) {
* This means parameters like -t and -l may not be in the beginning */
if (sscanf(argstr, "%d,%d %x %x %lf", &g->height, &g->width,
&g->first_colour, &g->last_colour, &g->scale) == 5) {
return *quoted_cmd ? strndup(quoted_cmd, text_buffer_size.get(*state))
: NULL;
return *quoted_cmd != 0
? strndup(quoted_cmd, text_buffer_size.get(*state))
: nullptr;
}
/* [height],[width] [color1] [color2] */
g->scale = defscale;
if (sscanf(argstr, "%d,%d %x %x", &g->height, &g->width, &g->first_colour,
&g->last_colour) == 4) {
return *quoted_cmd ? strndup(quoted_cmd, text_buffer_size.get(*state))
: NULL;
return *quoted_cmd != 0
? strndup(quoted_cmd, text_buffer_size.get(*state))
: nullptr;
}
/* [command] [height],[width] [color1] [color2] [scale] */
if (sscanf(argstr, "%1023s %d,%d %x %x %lf", buf, &g->height, &g->width,
@ -276,13 +283,15 @@ char *scan_graph(struct text_object *obj, const char *args, double defscale) {
g->width = default_graph_width.get(*state);
if (sscanf(argstr, "%x %x %lf", &g->first_colour, &g->last_colour,
&g->scale) == 3) {
return *quoted_cmd ? strndup(quoted_cmd, text_buffer_size.get(*state))
: NULL;
return *quoted_cmd != 0
? strndup(quoted_cmd, text_buffer_size.get(*state))
: nullptr;
}
g->scale = defscale;
if (sscanf(argstr, "%x %x", &g->first_colour, &g->last_colour) == 2) {
return *quoted_cmd ? strndup(quoted_cmd, text_buffer_size.get(*state))
: NULL;
return *quoted_cmd != 0
? strndup(quoted_cmd, text_buffer_size.get(*state))
: nullptr;
}
if (sscanf(argstr, "%1023s %x %x %lf", buf, &g->first_colour,
&g->last_colour, &g->scale) == 4) {
@ -298,30 +307,31 @@ char *scan_graph(struct text_object *obj, const char *args, double defscale) {
g->first_colour = 0;
g->last_colour = 0;
if (sscanf(argstr, "%d,%d %lf", &g->height, &g->width, &g->scale) == 3) {
return *quoted_cmd ? strndup(quoted_cmd, text_buffer_size.get(*state))
: NULL;
return *quoted_cmd != 0
? strndup(quoted_cmd, text_buffer_size.get(*state))
: nullptr;
}
g->scale = defscale;
if (sscanf(argstr, "%d,%d", &g->height, &g->width) == 2) {
return *quoted_cmd ? strndup(quoted_cmd, text_buffer_size.get(*state))
: NULL;
return *quoted_cmd != 0
? strndup(quoted_cmd, text_buffer_size.get(*state))
: nullptr;
}
if (sscanf(argstr, "%1023s %d,%d %lf", buf, &g->height, &g->width,
&g->scale) < 4) {
g->scale = defscale;
// TODO: check the return value and throw an error?
// TODO(brenden): check the return value and throw an error?
sscanf(argstr, "%1023s %d,%d", buf, &g->height, &g->width);
}
if (!*quoted_cmd && !*buf) {
return NULL;
} else {
return strndup(*quoted_cmd ? quoted_cmd : buf,
text_buffer_size.get(*state));
if ((*quoted_cmd == 0) && (*buf == 0)) {
return nullptr;
}
return strndup(*quoted_cmd != 0 ? quoted_cmd : buf,
text_buffer_size.get(*state));
}
return NULL;
return nullptr;
}
#endif /* BUILD_X11 */
@ -330,7 +340,7 @@ char *scan_graph(struct text_object *obj, const char *args, double defscale) {
*/
struct special_t *new_special_t_node() {
special_t *newnode = new special_t;
auto *newnode = new special_t;
memset(newnode, 0, sizeof *newnode);
return newnode;
@ -349,11 +359,15 @@ struct special_t *new_special(char *buf, enum special_types t) {
buf[0] = SPECIAL_CHAR;
buf[1] = '\0';
if (!specials) specials = new_special_t_node();
if (specials == nullptr) {
specials = new_special_t_node();
}
current = specials;
/* allocate special_count linked list elements */
for (int i = 0; i < special_count; i++) {
if (current->next == NULL) current->next = new_special_t_node();
if (current->next == nullptr) {
current->next = new_special_t_node();
}
current = current->next;
}
current->type = t;
@ -364,19 +378,23 @@ struct special_t *new_special(char *buf, enum special_types t) {
void new_gauge_in_shell(struct text_object *obj, char *p, int p_max_size,
double usage) {
static const char *gaugevals[] = {"_. ", "\\. ", " | ", " ./", " ._"};
struct gauge *g = (struct gauge *)obj->special_data;
auto *g = static_cast<struct gauge *>(obj->special_data);
snprintf(p, p_max_size, "%s", gaugevals[round_to_int(usage * 4 / g->scale)]);
}
#ifdef BUILD_X11
void new_gauge_in_x11(struct text_object *obj, char *buf, double usage) {
struct special_t *s = 0;
struct gauge *g = (struct gauge *)obj->special_data;
struct special_t *s = nullptr;
auto *g = static_cast<struct gauge *>(obj->special_data);
if (not out_to_x.get(*state)) return;
if (not out_to_x.get(*state)) {
return;
}
if (!g) return;
if (g == nullptr) {
return;
}
s = new_special(buf, GAUGE);
@ -388,21 +406,27 @@ void new_gauge_in_x11(struct text_object *obj, char *buf, double usage) {
#endif /* BUILD_X11 */
void new_gauge(struct text_object *obj, char *p, int p_max_size, double usage) {
struct gauge *g = (struct gauge *)obj->special_data;
auto *g = static_cast<struct gauge *>(obj->special_data);
if (!p_max_size || !g) return;
if ((p_max_size == 0) || (g == nullptr)) {
return;
}
if (g->flags & SF_SCALED)
if ((g->flags & SF_SCALED) != 0) {
g->scale = MAX(g->scale, usage);
else
} else {
usage = MIN(g->scale, usage);
}
#ifdef BUILD_X11
if (out_to_x.get(*state))
if (out_to_x.get(*state)) {
new_gauge_in_x11(obj, p, usage);
else
#endif /* BUILD_X11 */
} else {
new_gauge_in_shell(obj, p, p_max_size, usage);
}
#else /* BUILD_X11 */
new_gauge_in_shell(obj, p, p_max_size, usage);
#endif /* BUILD_X11 */
}
#ifdef BUILD_X11
@ -410,15 +434,19 @@ void new_font(struct text_object *obj, char *p, int p_max_size) {
struct special_t *s;
int tmp = selected_font;
if (not out_to_x.get(*state)) return;
if (not out_to_x.get(*state)) {
return;
}
if (!p_max_size) return;
if (p_max_size == 0) {
return;
}
s = new_special(p, FONT);
if (obj->data.s) {
if (s->font_added >= (int)fonts.size() || !s->font_added ||
obj->data.s != fonts[s->font_added].name) {
if (obj->data.s != nullptr) {
if (s->font_added >= static_cast<int>(fonts.size()) ||
(s->font_added == 0) || obj->data.s != fonts[s->font_added].name) {
selected_font = s->font_added = add_font(obj->data.s);
selected_font = tmp;
}
@ -435,15 +463,17 @@ static void graph_append(struct special_t *graph, double f, char showaslog) {
int i;
/* do nothing if we don't even have a graph yet */
if (!graph->graph) return;
if (graph->graph == nullptr) {
return;
}
if (showaslog) {
if (showaslog != 0) {
#ifdef BUILD_MATH
f = log10(f + 1);
#endif
}
if (!graph->scaled && f > graph->scale) {
if ((graph->scaled == 0) && f > graph->scale) {
f = graph->scale;
}
@ -453,7 +483,7 @@ static void graph_append(struct special_t *graph, double f, char showaslog) {
}
graph->graph[0] = f; /* add new data */
if (graph->scaled) {
if (graph->scaled != 0) {
graph->scale =
*std::max_element(graph->graph + 0, graph->graph + graph->graph_width);
if (graph->scale < 1e-47) {
@ -467,7 +497,7 @@ static void graph_append(struct special_t *graph, double f, char showaslog) {
void new_graph_in_shell(struct special_t *s, char *buf, int buf_max_size) {
// Split config string on comma to avoid the hassle of dealing with the
// idiosyncrasies of multi-byte unicode on different platforms.
// TODO: Parse config string once and cache result.
// TODO(brenden): Parse config string once and cache result.
const std::string ticks = console_graph_ticks.get(*state);
std::stringstream ss(ticks);
std::string tickitem;
@ -485,7 +515,9 @@ void new_graph_in_shell(struct special_t *s, char *buf, int buf_max_size) {
size_t itemlen = tickitems[v].size();
for (unsigned int j = 0; j < itemlen; j++) {
*p++ = tick[j];
if (p == buf_max) goto graph_buf_end;
if (p == buf_max) {
goto graph_buf_end;
}
}
}
graph_buf_end:
@ -502,26 +534,30 @@ graph_buf_end:
**/
void new_graph(struct text_object *obj, char *buf, int buf_max_size,
double val) {
struct special_t *s = 0;
struct graph *g = (struct graph *)obj->special_data;
struct special_t *s = nullptr;
auto *g = static_cast<struct graph *>(obj->special_data);
if (!g || !buf_max_size) return;
if ((g == nullptr) || (buf_max_size == 0)) {
return;
}
s = new_special(buf, GRAPH);
/* set graph (special) width to width in obj */
s->width = g->width;
if (s->width) s->graph_width = s->width;
if (s->width != 0) {
s->graph_width = s->width;
}
if (s->graph_width != s->graph_allocated) {
double *graph = static_cast<double *>(
auto *graph = static_cast<double *>(
realloc(s->graph, s->graph_width * sizeof(double)));
DBGP("reallocing graph from %d to %d", s->graph_allocated, s->graph_width);
if (!s->graph) {
if (s->graph == nullptr) {
/* initialize */
std::fill_n(graph, s->graph_width, 0.0);
s->scale = 100;
} else if (graph) {
} else if (graph != nullptr) {
if (s->graph_width > s->graph_allocated) {
/* initialize the new region */
std::fill(graph + s->graph_allocated, graph + s->graph_width, 0.0);
@ -548,19 +584,25 @@ void new_graph(struct text_object *obj, char *buf, int buf_max_size,
}
s->tempgrad = g->tempgrad;
#ifdef BUILD_MATH
if (g->flags & SF_SHOWLOG) {
if ((g->flags & SF_SHOWLOG) != 0) {
s->scale = log10(s->scale + 1);
}
#endif
graph_append(s, val, g->flags);
if (not out_to_x.get(*state)) new_graph_in_shell(s, buf, buf_max_size);
if (not out_to_x.get(*state)) {
new_graph_in_shell(s, buf, buf_max_size);
}
}
void new_hr(struct text_object *obj, char *p, int p_max_size) {
if (not out_to_x.get(*state)) return;
if (not out_to_x.get(*state)) {
return;
}
if (!p_max_size) return;
if (p_max_size == 0) {
return;
}
new_special(p, HORIZONTAL_LINE)->height = obj->data.l;
}
@ -568,13 +610,13 @@ void new_hr(struct text_object *obj, char *p, int p_max_size) {
void scan_stippled_hr(struct text_object *obj, const char *arg) {
struct stippled_hr *sh;
sh = (struct stippled_hr *)malloc(sizeof(struct stippled_hr));
sh = static_cast<struct stippled_hr *>(malloc(sizeof(struct stippled_hr)));
memset(sh, 0, sizeof(struct stippled_hr));
sh->arg = stippled_borders.get(*state);
sh->height = 1;
if (arg) {
if (arg != nullptr) {
if (sscanf(arg, "%d %d", &sh->arg, &sh->height) != 2) {
sscanf(arg, "%d", &sh->height);
}
@ -586,12 +628,16 @@ void scan_stippled_hr(struct text_object *obj, const char *arg) {
}
void new_stippled_hr(struct text_object *obj, char *p, int p_max_size) {
struct special_t *s = 0;
struct stippled_hr *sh = (struct stippled_hr *)obj->special_data;
struct special_t *s = nullptr;
auto *sh = static_cast<struct stippled_hr *>(obj->special_data);
if (not out_to_x.get(*state)) return;
if (not out_to_x.get(*state)) {
return;
}
if (!sh || !p_max_size) return;
if ((sh == nullptr) || (p_max_size == 0)) {
return;
}
s = new_special(p, STIPPLED_HR);
@ -602,10 +648,14 @@ void new_stippled_hr(struct text_object *obj, char *p, int p_max_size) {
void new_fg(struct text_object *obj, char *p, int p_max_size) {
#ifdef BUILD_X11
if (out_to_x.get(*state)) new_special(p, FG)->arg = obj->data.l;
if (out_to_x.get(*state)) {
new_special(p, FG)->arg = obj->data.l;
}
#endif /* BUILD_X11 */
#ifdef BUILD_NCURSES
if (out_to_ncurses.get(*state)) new_special(p, FG)->arg = obj->data.l;
if (out_to_ncurses.get(*state)) {
new_special(p, FG)->arg = obj->data.l;
}
#endif /* BUILD_NCURSES */
UNUSED(obj);
UNUSED(p);
@ -614,9 +664,13 @@ void new_fg(struct text_object *obj, char *p, int p_max_size) {
#ifdef BUILD_X11
void new_bg(struct text_object *obj, char *p, int p_max_size) {
if (not out_to_x.get(*state)) return;
if (not out_to_x.get(*state)) {
return;
}
if (!p_max_size) return;
if (p_max_size == 0) {
return;
}
new_special(p, BG)->arg = obj->data.l;
}
@ -624,33 +678,47 @@ void new_bg(struct text_object *obj, char *p, int p_max_size) {
static void new_bar_in_shell(struct text_object *obj, char *buffer,
int buf_max_size, double usage) {
struct bar *b = (struct bar *)obj->special_data;
auto *b = static_cast<struct bar *>(obj->special_data);
int width, i, scaledusage;
if (!b) return;
if (b == nullptr) {
return;
}
width = b->width;
if (!width) width = DEFAULT_BAR_WIDTH_NO_X;
if (width == 0) {
width = DEFAULT_BAR_WIDTH_NO_X;
}
if (width > buf_max_size) width = buf_max_size;
if (width > buf_max_size) {
width = buf_max_size;
}
scaledusage = round_to_int(usage * width / b->scale);
for (i = 0; i < scaledusage; i++) buffer[i] = '#';
for (i = 0; i < scaledusage; i++) {
buffer[i] = '#';
}
for (; i < width; i++) buffer[i] = '_';
for (; i < width; i++) {
buffer[i] = '_';
}
buffer[i] = 0;
}
#ifdef BUILD_X11
static void new_bar_in_x11(struct text_object *obj, char *buf, double usage) {
struct special_t *s = 0;
struct bar *b = (struct bar *)obj->special_data;
struct special_t *s = nullptr;
auto *b = static_cast<struct bar *>(obj->special_data);
if (not out_to_x.get(*state)) return;
if (not out_to_x.get(*state)) {
return;
}
if (!b) return;
if (b == nullptr) {
return;
}
s = new_special(buf, BAR);
@ -663,64 +731,82 @@ static void new_bar_in_x11(struct text_object *obj, char *buf, double usage) {
/* usage is in range [0,255] */
void new_bar(struct text_object *obj, char *p, int p_max_size, double usage) {
struct bar *b = (struct bar *)obj->special_data;
auto *b = static_cast<struct bar *>(obj->special_data);
if (!p_max_size || !b) return;
if ((p_max_size == 0) || (b == nullptr)) {
return;
}
if (b->flags & SF_SCALED)
if ((b->flags & SF_SCALED) != 0) {
b->scale = MAX(b->scale, usage);
else
} else {
usage = MIN(b->scale, usage);
}
#ifdef BUILD_X11
if (out_to_x.get(*state))
if (out_to_x.get(*state)) {
new_bar_in_x11(obj, p, usage);
else
#endif /* BUILD_X11 */
} else {
new_bar_in_shell(obj, p, p_max_size, usage);
}
#else /* BUILD_X11 */
new_bar_in_shell(obj, p, p_max_size, usage);
#endif /* BUILD_X11 */
}
void new_outline(struct text_object *obj, char *p, int p_max_size) {
if (!p_max_size) return;
if (p_max_size == 0) {
return;
}
new_special(p, OUTLINE)->arg = obj->data.l;
}
void new_offset(struct text_object *obj, char *p, int p_max_size) {
if (!p_max_size) return;
if (p_max_size == 0) {
return;
}
new_special(p, OFFSET)->arg = obj->data.l;
}
void new_voffset(struct text_object *obj, char *p, int p_max_size) {
if (!p_max_size) return;
if (p_max_size == 0) {
return;
}
new_special(p, VOFFSET)->arg = obj->data.l;
}
void new_alignr(struct text_object *obj, char *p, int p_max_size) {
if (!p_max_size) return;
if (p_max_size == 0) {
return;
}
new_special(p, ALIGNR)->arg = obj->data.l;
}
// A postive offset pushes the text further left
void new_alignc(struct text_object *obj, char *p, int p_max_size) {
if (!p_max_size) return;
if (p_max_size == 0) {
return;
}
new_special(p, ALIGNC)->arg = obj->data.l;
}
void new_goto(struct text_object *obj, char *p, int p_max_size) {
if (!p_max_size) return;
if (p_max_size == 0) {
return;
}
new_special(p, GOTO)->arg = obj->data.l;
}
void scan_tab(struct text_object *obj, const char *arg) {
struct tab *t;
t = (struct tab *)malloc(sizeof(struct tab));
t = static_cast<struct tab *>(malloc(sizeof(struct tab)));
memset(t, 0, sizeof(struct tab));
t->width = 10;
t->arg = 0;
if (arg) {
if (arg != nullptr) {
if (sscanf(arg, "%d %d", &t->width, &t->arg) != 2) {
sscanf(arg, "%d", &t->arg);
}
@ -732,10 +818,12 @@ void scan_tab(struct text_object *obj, const char *arg) {
}
void new_tab(struct text_object *obj, char *p, int p_max_size) {
struct special_t *s = 0;
struct tab *t = (struct tab *)obj->special_data;
struct special_t *s = nullptr;
auto *t = static_cast<struct tab *>(obj->special_data);
if (!t || !p_max_size) return;
if ((t == nullptr) || (p_max_size == 0)) {
return;
}
s = new_special(p, TAB);
s->width = t->width;

View File

@ -27,11 +27,11 @@
*
*/
#include <ctype.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cctype>
#include <cstring>
#include <memory>
#include "common.h"
#include "config.h"
@ -43,19 +43,14 @@
#define DEFAULT_MAX_HEADTAIL_USES 2
struct headtail {
int wantedlines;
int wantedlines{0};
std::string logfile;
char *buffer;
int current_use;
int max_uses;
int reported;
char *buffer{nullptr};
int current_use{0};
int max_uses{0};
int reported{0};
headtail()
: wantedlines(0),
buffer(NULL),
current_use(0),
max_uses(0),
reported(0) {}
headtail() = default;
~headtail() { free(buffer); }
};
@ -81,15 +76,15 @@ static void tailstring(char *string, int endofstring, int wantedlines) {
}
void free_tailhead(struct text_object *obj) {
struct headtail *ht = (struct headtail *)obj->data.opaque;
obj->data.opaque = NULL;
auto *ht = static_cast<struct headtail *>(obj->data.opaque);
obj->data.opaque = nullptr;
delete ht;
}
void init_tailhead(const char *type, const char *arg, struct text_object *obj,
void *free_at_crash) {
unsigned int args;
struct headtail *ht = new headtail;
auto *ht = new headtail;
std::unique_ptr<char[]> tmp(new char[DEFAULT_TEXT_BUFFER_SIZE]);
memset(tmp.get(), 0, DEFAULT_TEXT_BUFFER_SIZE);
@ -111,7 +106,7 @@ void init_tailhead(const char *type, const char *arg, struct text_object *obj,
}
if (ht->wantedlines > 0 && ht->wantedlines <= MAX_HEADTAIL_LINES) {
ht->logfile = to_real_path(tmp.get());
ht->buffer = NULL;
ht->buffer = nullptr;
ht->current_use = 0;
} else {
free_tailhead(obj);
@ -126,19 +121,21 @@ static void print_tailhead(const char *type, struct text_object *obj, char *p,
int p_max_size) {
int fd, i, endofstring = 0, linescounted = 0;
FILE *fp;
struct stat st;
struct headtail *ht = (struct headtail *)obj->data.opaque;
struct stat st {};
auto *ht = static_cast<struct headtail *>(obj->data.opaque);
if (!ht) return;
if (ht == nullptr) {
return;
}
// empty the buffer and reset the counter if we used it the max number of
// times
if (ht->buffer && ht->current_use >= ht->max_uses - 1) {
if ((ht->buffer != nullptr) && ht->current_use >= ht->max_uses - 1) {
free_and_zero(ht->buffer);
ht->current_use = 0;
}
// use the buffer if possible
if (ht->buffer) {
if (ht->buffer != nullptr) {
strcpy(p, ht->buffer);
ht->current_use++;
} else { // otherwise find the needed data
@ -148,7 +145,9 @@ static void print_tailhead(const char *type, struct text_object *obj, char *p,
if (fd != -1) {
if (strcmp(type, "head") == 0) {
for (i = 0; linescounted < ht->wantedlines; i++) {
if (read(fd, p + i, 1) <= 0) break;
if (read(fd, p + i, 1) <= 0) {
break;
}
if (p[i] == '\n') {
linescounted++;
}
@ -158,7 +157,7 @@ static void print_tailhead(const char *type, struct text_object *obj, char *p,
i = read(fd, p, p_max_size - 1);
tailstring(p, i, ht->wantedlines);
} else {
CRIT_ERR(NULL, NULL,
CRIT_ERR(nullptr, nullptr,
"If you are seeing this then there is a bug in the code, "
"report it !");
}
@ -166,10 +165,13 @@ static void print_tailhead(const char *type, struct text_object *obj, char *p,
close(fd);
} else {
fp = open_file(ht->logfile.c_str(), &ht->reported);
if (fp != NULL) {
if (fp != nullptr) {
if (strcmp(type, "head") == 0) {
for (i = 0; i < ht->wantedlines; i++) {
if (!fgets(p + endofstring, p_max_size - endofstring, fp)) break;
if (fgets(p + endofstring, p_max_size - endofstring, fp) ==
nullptr) {
break;
}
endofstring = strlen(p);
}
} else if (strcmp(type, "tail") == 0) {
@ -177,7 +179,7 @@ static void print_tailhead(const char *type, struct text_object *obj, char *p,
i = fread(p, 1, p_max_size - 1, fp);
tailstring(p, i, ht->wantedlines);
} else {
CRIT_ERR(NULL, NULL,
CRIT_ERR(nullptr, nullptr,
"If you are seeing this then there is a bug in the code, "
"report it !");
}
@ -186,11 +188,10 @@ static void print_tailhead(const char *type, struct text_object *obj, char *p,
}
ht->buffer = strdup(p);
} else {
CRIT_ERR(NULL, NULL, "$%s can't find information about %s", type,
CRIT_ERR(nullptr, nullptr, "$%s can't find information about %s", type,
ht->logfile.c_str());
}
}
return;
}
void print_head(struct text_object *obj, char *p, int p_max_size) {
@ -210,13 +211,13 @@ void print_lines(struct text_object *obj, char *p, int p_max_size) {
char buf[BUFSZ];
int j, lines;
if (!fp) {
if (fp == nullptr) {
snprintf(p, p_max_size, "File Unreadable");
return;
}
lines = 0;
while (fgets(buf, BUFSZ, fp) != NULL) {
while (fgets(buf, BUFSZ, fp) != nullptr) {
for (j = 0; buf[j] != 0; j++) {
if (buf[j] == '\n') {
lines++;
@ -234,16 +235,16 @@ void print_words(struct text_object *obj, char *p, int p_max_size) {
int j, words;
char inword = 0;
if (!fp) {
if (fp == nullptr) {
snprintf(p, p_max_size, "File Unreadable");
return;
}
words = 0;
while (fgets(buf, BUFSZ, fp) != NULL) {
while (fgets(buf, BUFSZ, fp) != nullptr) {
for (j = 0; buf[j] != 0; j++) {
if (!isspace(buf[j])) {
if (!inword) {
if (isspace(buf[j]) == 0) {
if (inword == 0) {
words++;
inword = 1;
}

View File

@ -23,7 +23,7 @@
#include "logging.h"
#include "text_object.h"
static tcp_port_monitor_collection_t *pmc = NULL;
static tcp_port_monitor_collection_t *pmc = nullptr;
static conky::range_config_setting<int> max_port_monitor_connections(
"max_port_monitor_connections", 0, std::numeric_limits<int>::max(),
@ -40,14 +40,14 @@ int tcp_portmon_init(struct text_object *obj, const char *arg) {
argc = sscanf(arg, "%d %d %31s %d", &port_begin, &port_end, itembuf,
&connection_index);
if ((argc != 3) && (argc != 4)) {
CRIT_ERR(NULL, NULL, "tcp_portmon: requires 3 or 4 arguments");
CRIT_ERR(nullptr, NULL, "tcp_portmon: requires 3 or 4 arguments");
}
if ((port_begin < 1) || (port_begin > 65535) || (port_end < 1) ||
(port_end > 65535)) {
CRIT_ERR(NULL, NULL, "tcp_portmon: port values must be from 1 to 65535");
CRIT_ERR(nullptr, NULL, "tcp_portmon: port values must be from 1 to 65535");
}
if (port_begin > port_end) {
CRIT_ERR(NULL, NULL, "tcp_portmon: starting port must be <= ending port");
CRIT_ERR(nullptr, NULL, "tcp_portmon: starting port must be <= ending port");
}
if (strncmp(itembuf, "count", 31) == EQUAL) {
item = COUNT;
@ -68,15 +68,15 @@ int tcp_portmon_init(struct text_object *obj, const char *arg) {
} else if (strncmp(itembuf, "lservice", 31) == EQUAL) {
item = LOCALSERVICE;
} else {
CRIT_ERR(NULL, NULL, "tcp_portmon: invalid item specified");
CRIT_ERR(nullptr, NULL, "tcp_portmon: invalid item specified");
}
if ((argc == 3) && (item != COUNT)) {
CRIT_ERR(NULL, NULL,
CRIT_ERR(nullptr, NULL,
"tcp_portmon: 3 argument form valid only for \"count\" "
"item");
}
if ((argc == 4) && (connection_index < 0)) {
CRIT_ERR(NULL, NULL, "tcp_portmon: connection index must be non-negative");
CRIT_ERR(nullptr, NULL, "tcp_portmon: connection index must be non-negative");
}
/* ok, args looks good. save the text object data */
pmd = (tcp_port_monitor_data *)malloc(sizeof(struct tcp_port_monitor_data));
@ -92,7 +92,7 @@ int tcp_portmon_init(struct text_object *obj, const char *arg) {
if (!pmc) {
pmc = create_tcp_port_monitor_collection();
if (!pmc) {
CRIT_ERR(NULL, NULL,
CRIT_ERR(nullptr, NULL,
"tcp_portmon: unable to create port monitor "
"collection");
}
@ -100,7 +100,7 @@ int tcp_portmon_init(struct text_object *obj, const char *arg) {
/* if a port monitor for this port does not exist,
* create one and add it to the collection */
if (find_tcp_port_monitor(pmc, port_begin, port_end) == NULL) {
if (find_tcp_port_monitor(pmc, port_begin, port_end) == nullptr) {
tcp_port_monitor_args_t pma;
memset(&pma, 0, sizeof pma);
pma.max_port_monitor_connections = max_port_monitor_connections.get(*state);
@ -108,7 +108,7 @@ int tcp_portmon_init(struct text_object *obj, const char *arg) {
/* add the newly created monitor to the collection */
if (insert_new_tcp_port_monitor_into_collection(pmc, port_begin, port_end,
&pma) != 0) {
CRIT_ERR(NULL, NULL,
CRIT_ERR(nullptr, NULL,
"tcp_portmon: unable to add port monitor to "
"collection");
}
@ -145,7 +145,7 @@ int tcp_portmon_update(void) {
int tcp_portmon_clear(void) {
destroy_tcp_port_monitor_collection(pmc);
pmc = NULL;
pmc = nullptr;
return 0;
}

View File

@ -21,11 +21,11 @@
*
*/
#include "temphelper.h"
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "config.h"
#include "conky.h"
@ -41,7 +41,9 @@ static double fahrenheit_to_celsius(double n) { return ((n - 32) * 5 / 9); }
static double celsius_to_fahrenheit(double n) { return ((n * 9 / 5) + 32); }
static double convert_temp_output(double n, enum TEMP_UNIT input_unit) {
if (input_unit == output_unit.get(*state)) return n;
if (input_unit == output_unit.get(*state)) {
return n;
}
switch (output_unit.get(*state)) {
case TEMP_CELSIUS:
@ -61,5 +63,5 @@ int temp_print(char *p, size_t p_max_size, double n,
out = round_to_int_temp(convert_temp_output(n, input_unit));
plen = spaced_print(p, p_max_size, "%d", 3, out);
return !(plen >= p_max_size);
return static_cast<int>(!(plen >= p_max_size));
}

View File

@ -26,8 +26,8 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <ctype.h>
#include <stdlib.h>
#include <cctype>
#include <cstdlib>
#include <string>
#include "conky.h"
#include "logging.h"
@ -39,12 +39,12 @@ conky::simple_config_setting<std::string> _template[10] = {
{"template4", std::string(), true}, {"template5", std::string(), true},
{"template6", std::string(), true}, {"template7", std::string(), true},
{"template8", std::string(), true}, {"template9", std::string(), true}};
}
} // namespace
/* backslash_escape - do the actual substitution task for template objects
*
* The field templates is used for substituting the \N occurences. Set it to
* NULL to leave them as they are.
* nullptr to leave them as they are.
*/
static char *backslash_escape(const char *src, char **templates,
unsigned int template_count) {
@ -53,13 +53,15 @@ static char *backslash_escape(const char *src, char **templates,
unsigned int dup_idx = 0, dup_len;
dup_len = strlen(src) + 1;
src_dup = (char *)malloc(dup_len * sizeof(char));
src_dup = static_cast<char *>(malloc(dup_len * sizeof(char)));
p = src;
while (*p) {
while (*p != 0) {
switch (*p) {
case '\\':
if (!*(p + 1)) break;
if (*(p + 1) == 0) {
break;
}
if (*(p + 1) == '\\') {
src_dup[dup_idx++] = '\\';
p++;
@ -69,18 +71,20 @@ static char *backslash_escape(const char *src, char **templates,
} else if (*(p + 1) == 'n') {
src_dup[dup_idx++] = '\n';
p++;
} else if (templates) {
} else if (templates != nullptr) {
unsigned int tmpl_num;
int digits;
if ((sscanf(p + 1, "%u%n", &tmpl_num, &digits) <= 0) ||
(tmpl_num > template_count))
(tmpl_num > template_count)) {
break;
}
if (tmpl_num == 0)
CRIT_ERR(
NULL, NULL,
nullptr, nullptr,
"invalid template argument \\0; arguments must start at \\1");
dup_len += strlen(templates[tmpl_num - 1]);
src_dup = (char *)realloc(src_dup, dup_len * sizeof(char));
src_dup =
static_cast<char *>(realloc(src_dup, dup_len * sizeof(char)));
sprintf(src_dup + dup_idx, "%s", templates[tmpl_num - 1]);
dup_idx += strlen(templates[tmpl_num - 1]);
p += digits;
@ -93,7 +97,7 @@ static char *backslash_escape(const char *src, char **templates,
p++;
}
src_dup[dup_idx++] = '\0';
src_dup = (char *)realloc(src_dup, dup_idx * sizeof(char));
src_dup = static_cast<char *>(realloc(src_dup, dup_idx * sizeof(char)));
return src_dup;
}
@ -109,34 +113,41 @@ static char *backslash_escape(const char *src, char **templates,
* ${template2 cdrom /mnt/cdrom}
*/
static char *handle_template(const char *tmpl, const char *args) {
char *args_dup = NULL;
char *args_dup = nullptr;
char *p, *p_old;
char **argsp = NULL;
char **argsp = nullptr;
unsigned int argcnt = 0, template_idx, i;
char *eval_text;
if ((sscanf(tmpl, "template%u", &template_idx) != 1) ||
(template_idx >= MAX_TEMPLATES))
return NULL;
(template_idx >= MAX_TEMPLATES)) {
return nullptr;
}
if (args) {
if (args != nullptr) {
args_dup = strdup(args);
p = args_dup;
while (*p) {
while (*p && (*p == ' ' && (p == args_dup || *(p - 1) != '\\'))) p++;
if (p > args_dup && *(p - 1) == '\\') p--;
while (*p != 0) {
while ((*p != 0) && (*p == ' ' && (p == args_dup || *(p - 1) != '\\'))) {
p++;
}
if (p > args_dup && *(p - 1) == '\\') {
p--;
}
p_old = p;
while (*p && (*p != ' ' || (p > args_dup && *(p - 1) == '\\'))) p++;
if (*p) {
while ((*p != 0) && (*p != ' ' || (p > args_dup && *(p - 1) == '\\'))) {
p++;
}
if (*p != 0) {
(*p) = '\0';
p++;
}
argsp = (char **)realloc(argsp, ++argcnt * sizeof(char *));
argsp = static_cast<char **>(realloc(argsp, ++argcnt * sizeof(char *)));
argsp[argcnt - 1] = p_old;
}
for (i = 0; i < argcnt; i++) {
char *tmp;
tmp = backslash_escape(argsp[i], NULL, 0);
tmp = backslash_escape(argsp[i], nullptr, 0);
DBGP2("%s: substituted arg '%s' to '%s'", tmpl, argsp[i], tmp);
argsp[i] = tmp;
}
@ -146,7 +157,9 @@ static char *handle_template(const char *tmpl, const char *args) {
argsp, argcnt);
DBGP("substituted %s, output is '%s'", tmpl, eval_text);
free(args_dup);
for (i = 0; i < argcnt; i++) free(argsp[i]);
for (i = 0; i < argcnt; i++) {
free(argsp[i]);
}
free(argsp);
return eval_text;
}
@ -158,17 +171,22 @@ char *find_and_replace_templates(const char *inbuf) {
int stack, outlen;
outlen = strlen(inbuf) + 1;
o = outbuf = (char *)calloc(outlen, sizeof(char));
o = outbuf = static_cast<char *>(calloc(outlen, sizeof(char)));
memset(outbuf, 0, outlen * sizeof(char));
p = indup = strdup(inbuf);
while (*p) {
while (*p && *p != '$') *(o++) = *(p++);
while (*p != 0) {
while ((*p != 0) && *p != '$') {
*(o++) = *(p++);
}
if (!(*p)) break;
if ((*p) == 0) {
break;
}
if (strncmp(p, "$template", strlen("$template")) &&
strncmp(p, "${template", strlen("${template"))) {
if ((static_cast<int>(strncmp(p, "$template", strlen("$template")) != 0) !=
0) &&
(strncmp(p, "${template", strlen("${template")) != 0)) {
*(o++) = *(p++);
continue;
}
@ -176,18 +194,22 @@ char *find_and_replace_templates(const char *inbuf) {
if (*(p + 1) == '{') {
p += 2;
templ = p;
while (*p && !isspace(*p) && *p != '{' && *p != '}') p++;
if (*p == '}')
args = NULL;
else
while ((*p != 0) && (isspace(*p) == 0) && *p != '{' && *p != '}') {
p++;
}
if (*p == '}') {
args = nullptr;
} else {
args = p;
}
stack = 1;
while (*p && stack > 0) {
if (*p == '{')
while ((*p != 0) && stack > 0) {
if (*p == '{') {
stack++;
else if (*p == '}')
} else if (*p == '}') {
stack--;
}
p++;
}
if (stack == 0) {
@ -195,19 +217,22 @@ char *find_and_replace_templates(const char *inbuf) {
*(p - 1) = '\0';
} else {
// we ran into the end of string without finding a closing }, bark
CRIT_ERR(NULL, NULL, "cannot find a closing '}' in template expansion");
CRIT_ERR(nullptr, nullptr,
"cannot find a closing '}' in template expansion");
}
} else {
templ = p + 1;
p += strlen("$template");
while (*p && isdigit(*p)) p++;
args = NULL;
while ((*p != 0) && (isdigit(*p) != 0)) {
p++;
}
args = nullptr;
}
tmpl_out = handle_template(templ, args);
if (tmpl_out) {
if (tmpl_out != nullptr) {
outlen += strlen(tmpl_out);
*o = '\0';
outbuf = (char *)realloc(outbuf, outlen * sizeof(char));
outbuf = static_cast<char *>(realloc(outbuf, outlen * sizeof(char)));
strcat(outbuf, tmpl_out);
free(tmpl_out);
o = outbuf + strlen(outbuf);
@ -216,14 +241,19 @@ char *find_and_replace_templates(const char *inbuf) {
}
}
*o = '\0';
outbuf = (char *)realloc(outbuf, (strlen(outbuf) + 1) * sizeof(char));
outbuf =
static_cast<char *>(realloc(outbuf, (strlen(outbuf) + 1) * sizeof(char)));
free(indup);
return outbuf;
}
/* check text for any template object references */
int text_contains_templates(const char *text) {
if (strcasestr(text, "${template") != NULL) return 1;
if (strcasestr(text, "$template") != NULL) return 1;
if (strcasestr(text, "${template") != nullptr) {
return 1;
}
if (strcasestr(text, "$template") != nullptr) {
return 1;
}
return 0;
}

View File

@ -26,8 +26,8 @@
*
*/
#include "text_object.h"
#include <stdio.h>
#include <stdlib.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "config.h"
#include "conky.h"
@ -44,25 +44,27 @@ int gen_false_iftest(struct text_object *obj) {
void gen_print_nothing(struct text_object *obj, char *p, int p_max_size) {
(void)obj;
(void)p;
p = p; // just a trick to make the compiler happy about this being non-const
(void)p_max_size;
}
void gen_print_obj_data_s(struct text_object *obj, char *p, int p_max_size) {
if (!obj->data.s) return;
if (obj->data.s == nullptr) {
return;
}
snprintf(p, p_max_size, "%s", obj->data.s);
}
/* text_object_list
*
* this list is special. it looks like this:
* NULL <-- obj1 <--> obj2 <--> ... <--> objN --> NULL
* nullptr <-- obj1 <--> obj2 <--> ... <--> objN --> NULL
* ^-------root_object----------^
* directions are reversed here
*
* why this is cool:
* - root_object points both to the start and end of the list
* - while traversing, the end of the list is always a NULL pointer
* - while traversing, the end of the list is always a nullptr pointer
* (this works in BOTH directions)
*/
@ -75,15 +77,18 @@ int append_object(struct text_object *root, struct text_object *obj) {
obj->prev = end;
/* update pointers of the list to append to */
if (end) {
if (end->next) CRIT_ERR(NULL, NULL, "huston, we have a lift-off");
if (end != nullptr) {
if (end->next != nullptr)
CRIT_ERR(nullptr, nullptr, "huston, we have a lift-off");
end->next = obj;
} else {
root->next = obj;
}
/* find end of appended list to point root->prev there */
while (obj->next) obj = obj->next;
while (obj->next != nullptr) {
obj = obj->next;
}
root->prev = obj;
return 0;
@ -125,8 +130,8 @@ static int push_ifblock(struct ifblock_stack_obj **ifblock_stack_top,
switch (type) {
case IFBLOCK_ENDIF:
if (!(*ifblock_stack_top))
CRIT_ERR(NULL, NULL, "got an endif without matching if");
if ((*ifblock_stack_top) == nullptr)
CRIT_ERR(nullptr, nullptr, "got an endif without matching if");
(*ifblock_stack_top)->obj->ifblock_next = obj;
/* if there's some else in between, remove and free it */
if ((*ifblock_stack_top)->type == IFBLOCK_ELSE) {
@ -140,19 +145,20 @@ static int push_ifblock(struct ifblock_stack_obj **ifblock_stack_top,
free(stackobj);
break;
case IFBLOCK_ELSE:
if (!(*ifblock_stack_top))
CRIT_ERR(NULL, NULL, "got an else without matching if");
if ((*ifblock_stack_top) == nullptr)
CRIT_ERR(nullptr, nullptr, "got an else without matching if");
(*ifblock_stack_top)->obj->ifblock_next = obj;
/* fall through */
case IFBLOCK_IF:
stackobj = (ifblock_stack_obj *)malloc(sizeof(struct ifblock_stack_obj));
stackobj = static_cast<ifblock_stack_obj *>(
malloc(sizeof(struct ifblock_stack_obj)));
stackobj->type = type;
stackobj->obj = obj;
stackobj->next = *ifblock_stack_top;
*ifblock_stack_top = stackobj;
break;
default:
CRIT_ERR(NULL, NULL, "push_ifblock() missuse detected!");
CRIT_ERR(nullptr, nullptr, "push_ifblock() missuse detected!");
}
return 0;
}
@ -160,19 +166,24 @@ static int push_ifblock(struct ifblock_stack_obj **ifblock_stack_top,
/* public functions for client use */
int obj_be_ifblock_if(void **opaque, struct text_object *obj) {
return push_ifblock((struct ifblock_stack_obj **)opaque, obj, IFBLOCK_IF);
return push_ifblock(reinterpret_cast<struct ifblock_stack_obj **>(opaque),
obj, IFBLOCK_IF);
}
int obj_be_ifblock_else(void **opaque, struct text_object *obj) {
return push_ifblock((struct ifblock_stack_obj **)opaque, obj, IFBLOCK_ELSE);
return push_ifblock(reinterpret_cast<struct ifblock_stack_obj **>(opaque),
obj, IFBLOCK_ELSE);
}
int obj_be_ifblock_endif(void **opaque, struct text_object *obj) {
return push_ifblock((struct ifblock_stack_obj **)opaque, obj, IFBLOCK_ENDIF);
return push_ifblock(reinterpret_cast<struct ifblock_stack_obj **>(opaque),
obj, IFBLOCK_ENDIF);
}
/* check if ifblock stack is empty
* if so, return true (!= 0)
*/
int ifblock_stack_empty(void **opaque) { return *opaque == NULL; }
int ifblock_stack_empty(void **opaque) {
return static_cast<int>(*opaque == nullptr);
}
void obj_be_plain_text(struct text_object *obj, const char *text) {
obj->data.s = strdup(text);

View File

@ -133,7 +133,7 @@ int append_object(struct text_object *root, struct text_object *obj);
*
* Opaque is a pointer to the address of the ifblock stack's top object.
* Calling clients should pass the address of a defined void pointer which
* was initialised to NULL (empty stack).
* was initialised to nullptr (empty stack).
* */
int obj_be_ifblock_if(void **opaque, struct text_object *);
int obj_be_ifblock_else(void **opaque, struct text_object *);

View File

@ -31,10 +31,10 @@
#include "timeinfo.h"
#include <errno.h>
#include <locale.h>
#include <string.h>
#include <time.h>
#include <cerrno>
#include <clocale>
#include <cstring>
#include <ctime>
#include "conky.h"
#include "logging.h"
#include "text_object.h"
@ -50,15 +50,16 @@ conky::simple_config_setting<bool> times_in_seconds("times_in_seconds", false,
false);
void scan_time(struct text_object *obj, const char *arg) {
obj->data.opaque = strndup(arg ? arg : "%F %T", text_buffer_size.get(*state));
obj->data.opaque =
strndup(arg != nullptr ? arg : "%F %T", text_buffer_size.get(*state));
}
void scan_tztime(struct text_object *obj, const char *arg) {
char buf1[256], buf2[256], *fmt, *tz;
struct tztime_s *ts;
fmt = tz = NULL;
if (arg) {
fmt = tz = nullptr;
if (arg != nullptr) {
int nArgs = sscanf(arg, "%255s %255[^\n]", buf1, buf2);
switch (nArgs) {
@ -69,48 +70,51 @@ void scan_tztime(struct text_object *obj, const char *arg) {
}
}
ts = (tztime_s *)malloc(sizeof(struct tztime_s));
ts = static_cast<tztime_s *>(malloc(sizeof(struct tztime_s)));
memset(ts, 0, sizeof(struct tztime_s));
ts->fmt = strndup(fmt ? fmt : "%F %T", text_buffer_size.get(*state));
ts->tz = tz ? strndup(tz, text_buffer_size.get(*state)) : NULL;
ts->fmt =
strndup(fmt != nullptr ? fmt : "%F %T", text_buffer_size.get(*state));
ts->tz = tz != nullptr ? strndup(tz, text_buffer_size.get(*state)) : nullptr;
obj->data.opaque = ts;
}
void print_time(struct text_object *obj, char *p, int p_max_size) {
time_t t = time(NULL);
time_t t = time(nullptr);
struct tm *tm = localtime(&t);
setlocale(LC_TIME, "");
strftime(p, p_max_size, (char *)obj->data.opaque, tm);
strftime(p, p_max_size, static_cast<char *>(obj->data.opaque), tm);
}
void print_utime(struct text_object *obj, char *p, int p_max_size) {
time_t t = time(NULL);
time_t t = time(nullptr);
struct tm *tm = gmtime(&t);
setlocale(LC_TIME, "");
strftime(p, p_max_size, (char *)obj->data.opaque, tm);
strftime(p, p_max_size, static_cast<char *>(obj->data.opaque), tm);
}
void print_tztime(struct text_object *obj, char *p, int p_max_size) {
char *oldTZ = NULL;
char *oldTZ = nullptr;
time_t t;
struct tm *tm;
struct tztime_s *ts = (tztime_s *)obj->data.opaque;
auto *ts = static_cast<tztime_s *>(obj->data.opaque);
if (!ts) return;
if (ts == nullptr) {
return;
}
if (ts->tz) {
if (ts->tz != nullptr) {
oldTZ = getenv("TZ");
setenv("TZ", ts->tz, 1);
tzset();
}
t = time(NULL);
t = time(nullptr);
tm = localtime(&t);
setlocale(LC_TIME, "");
strftime(p, p_max_size, ts->fmt, tm);
if (oldTZ) {
if (oldTZ != nullptr) {
setenv("TZ", oldTZ, 1);
tzset();
} else {
@ -122,9 +126,11 @@ void print_tztime(struct text_object *obj, char *p, int p_max_size) {
void free_time(struct text_object *obj) { free_and_zero(obj->data.opaque); }
void free_tztime(struct text_object *obj) {
struct tztime_s *ts = (tztime_s *)obj->data.opaque;
auto *ts = static_cast<tztime_s *>(obj->data.opaque);
if (!ts) return;
if (ts == nullptr) {
return;
}
free_and_zero(ts->tz);
free_and_zero(ts->fmt);
@ -199,14 +205,22 @@ static void do_format_time(struct text_object *obj, char *p,
}
}
}
if (show_weeks == 0) days += weeks * 7;
if (show_days == 0) hours += days * 24;
if (show_hours == 0) minutes += hours * 60;
if (show_minutes == 0) seconds += minutes * 60;
if (show_weeks == 0) {
days += weeks * 7;
}
if (show_days == 0) {
hours += days * 24;
}
if (show_hours == 0) {
minutes += hours * 60;
}
if (show_minutes == 0) {
seconds += minutes * 60;
}
hidestring = 0;
while (output_length < p_max_size - 1) {
if (*currentchar != 0 && *currentchar != '"') {
temp = NULL;
temp = nullptr;
if (*currentchar == '\\' && hidestring == 0) {
currentchar++;
switch (*currentchar) {
@ -230,7 +244,7 @@ static void do_format_time(struct text_object *obj, char *p,
if (*currentchar >= '0' && *currentchar <= '9') {
safe_asprintf(&temp, "%.*f", (*currentchar) - '0', seconds);
} else if (*currentchar == 'x') {
if (seconds == (int)seconds) {
if (seconds == static_cast<int>(seconds)) {
safe_asprintf(&temp, "%d", (int)seconds);
} else {
safe_asprintf(&temp, "%.9f", seconds);
@ -261,42 +275,54 @@ static void do_format_time(struct text_object *obj, char *p,
if (*(temp - 1) == '\\') {
switch (*temp) {
case 'w':
if (weeks == 0) hidestring = 1;
if (weeks == 0) {
hidestring = 1;
}
break;
case 'd':
if (days == 0) hidestring = 1;
if (days == 0) {
hidestring = 1;
}
break;
case 'h':
if (hours == 0) hidestring = 1;
if (hours == 0) {
hidestring = 1;
}
break;
case 'm':
if (minutes == 0) hidestring = 1;
if (minutes == 0) {
hidestring = 1;
}
break;
case 's':
case 'S':
if (seconds == 0) hidestring = 1;
if (seconds == 0) {
hidestring = 1;
}
break;
}
}
}
temp = NULL;
temp = nullptr;
} else if (*currentchar == ')') {
hidestring = 0;
} else if (hidestring == 0) {
p[output_length] = *currentchar;
output_length++;
}
if (temp) {
if (temp != nullptr) {
if (output_length + strlen(temp) < p_max_size - 1) {
strcpy(p + output_length, temp);
output_length += strlen(temp);
} else
} else {
NORM_ERR("The format string for $format_time is too long");
}
free(temp);
}
currentchar++;
} else
} else {
break;
}
}
p[output_length] = 0;
} else {

View File

@ -35,7 +35,7 @@
/* hash table size - always a power of 2 */
#define HTABSIZE 256
struct process *first_process = 0;
struct process *first_process = nullptr;
unsigned long g_time = 0;
@ -52,7 +52,7 @@ static void hash_process(struct process *p) {
int bucket;
/* better make sure all next pointers are zero upon first access */
if (first_run) {
if (first_run != 0) {
memset(proc_hash_table, 0, sizeof(struct proc_hash_entry) * HTABSIZE);
first_run = 0;
}
@ -61,7 +61,8 @@ static void hash_process(struct process *p) {
bucket = p->pid & (HTABSIZE - 1);
/* insert a new element on bucket's top */
phe = (struct proc_hash_entry *)malloc(sizeof(struct proc_hash_entry));
phe = static_cast<struct proc_hash_entry *>(
malloc(sizeof(struct proc_hash_entry)));
phe->proc = p;
phe->next = proc_hash_table[bucket].next;
proc_hash_table[bucket].next = phe;
@ -73,7 +74,7 @@ static void unhash_process(struct process *p) {
/* get the bucket head */
phe = &proc_hash_table[p->pid & (HTABSIZE - 1)];
/* find the entry pointing to p and drop it */
while (phe->next) {
while (phe->next != nullptr) {
if (phe->next->proc == p) {
tmp = phe->next;
phe->next = phe->next->next;
@ -85,34 +86,36 @@ static void unhash_process(struct process *p) {
}
static void __unhash_all_processes(struct proc_hash_entry *phe) {
if (phe->next) __unhash_all_processes(phe->next);
if (phe->next != nullptr) {
__unhash_all_processes(phe->next);
}
free(phe->next);
}
static void unhash_all_processes(void) {
static void unhash_all_processes() {
int i;
for (i = 0; i < HTABSIZE; i++) {
__unhash_all_processes(&proc_hash_table[i]);
proc_hash_table[i].next = NULL;
proc_hash_table[i].next = nullptr;
}
}
struct process *get_first_process(void) {
struct process *get_first_process() {
return first_process;
}
void free_all_processes(void) {
struct process *next = NULL, *pr = first_process;
void free_all_processes() {
struct process *next = nullptr, *pr = first_process;
while (pr) {
while (pr != nullptr) {
next = pr->next;
free_and_zero(pr->name);
free_and_zero(pr->basename);
free(pr);
pr = next;
}
first_process = NULL;
first_process = nullptr;
/* drop the whole hash table */
unhash_all_processes();
@ -121,43 +124,46 @@ void free_all_processes(void) {
struct process *get_process_by_name(const char *name) {
struct process *p = first_process;
while (p) {
while (p != nullptr) {
/* Try matching against the full command line first. If that fails,
* fall back to the basename.
*/
if ((p->name && !strcmp(p->name, name)) ||
(p->basename && !strcmp(p->basename, name)))
if (((p->name != nullptr) && (strcmp(p->name, name) == 0)) ||
((p->basename != nullptr) && (strcmp(p->basename, name) == 0))) {
return p;
}
p = p->next;
}
return 0;
return nullptr;
}
static struct process *find_process(pid_t pid) {
struct proc_hash_entry *phe;
phe = &proc_hash_table[pid & (HTABSIZE - 1)];
while (phe->next) {
if (phe->next->proc->pid == pid) return phe->next->proc;
while (phe->next != nullptr) {
if (phe->next->proc->pid == pid) {
return phe->next->proc;
}
phe = phe->next;
}
return NULL;
return nullptr;
}
static struct process *new_process(pid_t pid) {
struct process *p = (struct process *)malloc(sizeof(struct process));
auto *p = static_cast<struct process *>(malloc(sizeof(struct process)));
/* Do stitching necessary for doubly linked list */
p->previous = NULL;
p->previous = nullptr;
p->next = first_process;
if (p->next) {
if (p->next != nullptr) {
p->next->previous = p;
}
first_process = p;
p->pid = pid;
p->name = 0;
p->basename = 0;
p->name = nullptr;
p->basename = nullptr;
p->amount = 0;
p->user_time = 0;
p->total = 0;
@ -189,7 +195,7 @@ static struct process *new_process(pid_t pid) {
/* Get / create a new process object and insert it into the process list */
struct process *get_process(pid_t pid) {
struct process *p = find_process(pid);
return p ? p : new_process(pid);
return p != nullptr ? p : new_process(pid);
}
/******************************************
@ -213,11 +219,14 @@ static void delete_process(struct process *p) {
/*
* Maintain doubly linked list.
*/
if (p->next) p->next->previous = p->previous;
if (p->previous)
if (p->next != nullptr) {
p->next->previous = p->previous;
}
if (p->previous != nullptr) {
p->previous->next = p->next;
else
} else {
first_process = p->next;
}
free_and_zero(p->name);
free_and_zero(p->basename);
@ -230,10 +239,10 @@ static void delete_process(struct process *p) {
* Strip dead process entries *
******************************************/
static void process_cleanup(void) {
static void process_cleanup() {
struct process *p = first_process;
while (p) {
while (p != nullptr) {
struct process *current = p;
#if defined(PARANOID)
@ -254,55 +263,59 @@ static void process_cleanup(void) {
/* cpu comparison function for prio queue */
static int compare_cpu(void *va, void *vb) {
struct process *a = (struct process *)va, *b = (struct process *)vb;
auto *a = static_cast<struct process *>(va),
*b = static_cast<struct process *>(vb);
if (b->amount > a->amount) {
return 1;
} else if (a->amount > b->amount) {
return -1;
} else {
return 0;
}
if (a->amount > b->amount) {
return -1;
}
return 0;
}
/* mem comparison function for prio queue */
static int compare_mem(void *va, void *vb) {
struct process *a = (struct process *)va, *b = (struct process *)vb;
auto *a = static_cast<struct process *>(va),
*b = static_cast<struct process *>(vb);
if (b->rss > a->rss) {
return 1;
} else if (a->rss > b->rss) {
return -1;
} else {
return 0;
}
if (a->rss > b->rss) {
return -1;
}
return 0;
}
/* CPU time comparision function for prio queue */
static int compare_time(void *va, void *vb) {
struct process *a = (struct process *)va, *b = (struct process *)vb;
auto *a = static_cast<struct process *>(va),
*b = static_cast<struct process *>(vb);
if (b->total_cpu_time > a->total_cpu_time) {
return 1;
} else if (b->total_cpu_time < a->total_cpu_time) {
return -1;
} else {
return 0;
}
if (b->total_cpu_time < a->total_cpu_time) {
return -1;
}
return 0;
}
#ifdef BUILD_IOSTATS
/* I/O comparision function for prio queue */
static int compare_io(void *va, void *vb) {
struct process *a = (struct process *)va, *b = (struct process *)vb;
auto *a = static_cast<struct process *>(va),
*b = static_cast<struct process *>(vb);
if (b->io_perc > a->io_perc) {
return 1;
} else if (a->io_perc > b->io_perc) {
return -1;
} else {
return 0;
}
if (a->io_perc > b->io_perc) {
return -1;
}
return 0;
}
#endif /* BUILD_IOSTATS */
@ -322,14 +335,14 @@ static void process_find_top(struct process **cpu, struct process **mem,
#ifdef BUILD_IOSTATS
prio_queue_t io_queue;
#endif
struct process *cur_proc = NULL;
struct process *cur_proc = nullptr;
int i;
if (!top_cpu && !top_mem && !top_time
if ((top_cpu == 0) && (top_mem == 0) && (top_time == 0)
#ifdef BUILD_IOSTATS
&& !top_io
&& (top_io == 0)
#endif /* BUILD_IOSTATS */
&& !top_running) {
&& (top_running == 0)) {
return;
}
@ -364,18 +377,18 @@ static void process_find_top(struct process **cpu, struct process **mem,
cur_proc = first_process;
while (cur_proc != NULL) {
if (top_cpu) {
while (cur_proc != nullptr) {
if (top_cpu != 0) {
insert_prio_elem(cpu_queue, cur_proc);
}
if (top_mem) {
if (top_mem != 0) {
insert_prio_elem(mem_queue, cur_proc);
}
if (top_time) {
if (top_time != 0) {
insert_prio_elem(time_queue, cur_proc);
}
#ifdef BUILD_IOSTATS
if (top_io) {
if (top_io != 0) {
insert_prio_elem(io_queue, cur_proc);
}
#endif /* BUILD_IOSTATS */
@ -383,11 +396,19 @@ static void process_find_top(struct process **cpu, struct process **mem,
}
for (i = 0; i < MAX_SP; i++) {
if (top_cpu) cpu[i] = (process *)pop_prio_elem(cpu_queue);
if (top_mem) mem[i] = (process *)pop_prio_elem(mem_queue);
if (top_time) ptime[i] = (process *)pop_prio_elem(time_queue);
if (top_cpu != 0) {
cpu[i] = static_cast<process *>(pop_prio_elem(cpu_queue));
}
if (top_mem != 0) {
mem[i] = static_cast<process *>(pop_prio_elem(mem_queue));
}
if (top_time != 0) {
ptime[i] = static_cast<process *>(pop_prio_elem(time_queue));
}
#ifdef BUILD_IOSTATS
if (top_io) io[i] = (process *)pop_prio_elem(io_queue);
if (top_io != 0) {
io[i] = static_cast<process *>(pop_prio_elem(io_queue));
}
#endif /* BUILD_IOSTATS */
}
free_prio_queue(cpu_queue);
@ -398,7 +419,7 @@ static void process_find_top(struct process **cpu, struct process **mem,
#endif /* BUILD_IOSTATS */
}
int update_top(void) {
int update_top() {
// XXX: this was a separate callback. and it should be again, as soon as it's
// possible
update_meminfo();
@ -464,10 +485,13 @@ static conky::simple_config_setting<bool> top_name_verbose("top_name_verbose",
false, true);
static void print_top_name(struct text_object *obj, char *p, int p_max_size) {
struct top_data *td = (struct top_data *)obj->data.opaque;
auto *td = static_cast<struct top_data *>(obj->data.opaque);
int width;
if (!td || !td->list || !td->list[td->num]) return;
if ((td == nullptr) || (td->list == nullptr) ||
(td->list[td->num] == nullptr)) {
return;
}
width = MIN(p_max_size, (int)top_name_width.get(*state) + 1);
if (top_name_verbose.get(*state)) {
@ -480,22 +504,28 @@ static void print_top_name(struct text_object *obj, char *p, int p_max_size) {
}
static void print_top_mem(struct text_object *obj, char *p, int p_max_size) {
struct top_data *td = (struct top_data *)obj->data.opaque;
auto *td = static_cast<struct top_data *>(obj->data.opaque);
int width;
if (!td || !td->list || !td->list[td->num]) return;
if ((td == nullptr) || (td->list == nullptr) ||
(td->list[td->num] == nullptr)) {
return;
}
width = MIN(p_max_size, 7);
snprintf(p, width, "%6.2f",
(float)((float)td->list[td->num]->rss / info.memmax) / 10);
(static_cast<float>(td->list[td->num]->rss) / info.memmax) / 10);
}
static void print_top_time(struct text_object *obj, char *p, int p_max_size) {
struct top_data *td = (struct top_data *)obj->data.opaque;
auto *td = static_cast<struct top_data *>(obj->data.opaque);
int width;
char *timeval;
if (!td || !td->list || !td->list[td->num]) return;
if ((td == nullptr) || (td->list == nullptr) ||
(td->list[td->num] == nullptr)) {
return;
}
width = MIN(p_max_size, 10);
timeval = format_time(td->list[td->num]->total_cpu_time, 9);
@ -504,9 +534,12 @@ static void print_top_time(struct text_object *obj, char *p, int p_max_size) {
}
static void print_top_user(struct text_object *obj, char *p, int p_max_size) {
struct top_data *td = (struct top_data *)obj->data.opaque;
auto *td = static_cast<struct top_data *>(obj->data.opaque);
if (!td || !td->list || !td->list[td->num]) return;
if ((td == nullptr) || (td->list == nullptr) ||
(td->list[td->num] == nullptr)) {
return;
}
snprintf(p, p_max_size, "%.8s", getpwuid(td->list[td->num]->uid)->pw_name);
}
@ -519,12 +552,12 @@ static void print_top_user(struct text_object *obj, char *p, int p_max_size) {
snprintf(p, MIN(p_max_size, width), fmt, td->list[td->num]->field); \
}
#define PRINT_TOP_HR_GENERATOR(name, field, denom) \
static void print_top_##name(struct text_object *obj, char *p, \
int p_max_size) { \
struct top_data *td = (struct top_data *)obj->data.opaque; \
if (!td || !td->list || !td->list[td->num]) return; \
human_readable(td->list[td->num]->field / denom, p, p_max_size); \
#define PRINT_TOP_HR_GENERATOR(name, field, denom) \
static void print_top_##name(struct text_object *obj, char *p, \
int p_max_size) { \
struct top_data *td = (struct top_data *)obj->data.opaque; \
if (!td || !td->list || !td->list[td->num]) return; \
human_readable(td->list[td->num]->field / (denom), p, p_max_size); \
}
PRINT_TOP_GENERATOR(cpu, 7, "%6.2f", amount)
@ -539,9 +572,11 @@ PRINT_TOP_GENERATOR(io_perc, 7, "%6.2f", io_perc)
#endif /* BUILD_IOSTATS */
static void free_top(struct text_object *obj) {
struct top_data *td = (struct top_data *)obj->data.opaque;
auto *td = static_cast<struct top_data *>(obj->data.opaque);
if (!td) return;
if (td == nullptr) {
return;
}
free_and_zero(td->s);
free_and_zero(obj->data.opaque);
}
@ -551,12 +586,13 @@ int parse_top_args(const char *s, const char *arg, struct text_object *obj) {
char buf[64];
int n;
if (!arg) {
if (arg == nullptr) {
NORM_ERR("top needs arguments");
return 0;
}
obj->data.opaque = td = (struct top_data *)malloc(sizeof(struct top_data));
obj->data.opaque = td =
static_cast<struct top_data *>(malloc(sizeof(struct top_data)));
memset(td, 0, sizeof(struct top_data));
if (s[3] == 0) {
@ -630,9 +666,9 @@ int parse_top_args(const char *s, const char *arg, struct text_object *obj) {
free_and_zero(td->s);
free_and_zero(obj->data.opaque);
return 0;
} else {
td->num = n - 1;
}
td->num = n - 1;
} else {
NORM_ERR("invalid argument count for top");
free_and_zero(td->s);

View File

@ -25,8 +25,8 @@
#include "update-cb.hh"
#include <unistd.h>
#include <typeinfo>
#include <unistd.h>
namespace conky {
namespace {
@ -38,16 +38,18 @@ namespace priv {
callback_base::~callback_base() { stop(); }
void callback_base::stop() {
if (thread) {
if (thread != nullptr) {
done = true;
sem_start.post();
if (pipefd.second >= 0)
if (write(pipefd.second, "X", 1) != 1)
if (pipefd.second >= 0) {
if (write(pipefd.second, "X", 1) != 1) {
NORM_ERR("can't write 'X' to pipefd %d: %s", pipefd.second,
strerror(errno));
}
}
thread->join();
delete thread;
thread = NULL;
thread = nullptr;
}
if (pipefd.first >= 0) {
close(pipefd.first);
@ -62,9 +64,13 @@ void callback_base::stop() {
inline size_t callback_base::get_hash(const handle &h) { return h->hash; }
inline bool callback_base::is_equal(const handle &a, const handle &b) {
if (a->hash != b->hash) return false;
if (a->hash != b->hash) {
return false;
}
if (typeid(*a) != typeid(*b)) return false;
if (typeid(*a) != typeid(*b)) {
return false;
}
return *a == *b;
}
@ -91,13 +97,17 @@ callback_base::handle callback_base::do_register_cb(const handle &h) {
const auto &p = callbacks.insert(h);
/* insertion failed; callback already exists */
if (not p.second) (*p.first)->merge(std::move(*h));
if (not p.second) {
(*p.first)->merge(std::move(*h));
}
return *p.first;
}
void callback_base::run() {
if (not thread) thread = new std::thread(&callback_base::start_routine, this);
if (thread == nullptr) {
thread = new std::thread(&callback_base::start_routine, this);
}
sem_start.post();
}
@ -105,15 +115,20 @@ void callback_base::run() {
void callback_base::start_routine() {
for (;;) {
sem_start.wait();
if (done) return;
if (done) {
return;
}
// clear any remaining posts in case the previous iteration was very slow
// (this should only happen if wait == false)
while (sem_start.trywait())
while (sem_start.trywait()) {
;
}
work();
if (wait) sem_wait.post();
if (wait) {
sem_wait.post();
}
}
}
@ -135,17 +150,22 @@ void run_all_callbacks() {
if (!i->unique() || ++cb.unused < UNUSED_MAX) {
cb.remaining = cb.period - 1;
cb.run();
if (cb.wait) ++wait;
if (cb.wait) {
++wait;
}
}
}
if (cb.unused == UNUSED_MAX) {
auto t = i;
++i;
callback_base::callbacks.erase(t);
} else
} else {
++i;
}
}
while (wait-- > 0) sem_wait.wait();
while (wait-- > 0) {
sem_wait.wait();
}
}
} // namespace conky

View File

@ -97,7 +97,7 @@ class callback_base {
protected:
callback_base(size_t hash_, uint32_t period_, bool wait_, bool use_pipe)
: thread(NULL),
: thread(nullptr),
hash(hash_),
period(period_),
remaining(0),

View File

@ -29,9 +29,9 @@
#include <config.h>
#include <errno.h>
#include <grp.h>
#include <pwd.h>
#include <cerrno>
#include <memory>
#include "conky.h"
#include "logging.h"
@ -48,7 +48,7 @@ void print_uid_name(struct text_object *obj, char *p, int p_max_size) {
uid = strtol(objbuf.get(), &firstinvalid, 10);
if (errno == 0 && objbuf.get() != firstinvalid) {
pw = getpwuid(uid);
if (pw != NULL) {
if (pw != nullptr) {
snprintf(p, p_max_size, "%s", pw->pw_name);
} else {
NORM_ERR("The uid %d doesn't exist", uid);
@ -70,7 +70,7 @@ void print_gid_name(struct text_object *obj, char *p, int p_max_size) {
gid = strtol(objbuf.get(), &firstinvalid, 10);
if (errno == 0 && objbuf.get() != firstinvalid) {
grp = getgrgid(gid);
if (grp != NULL) {
if (grp != nullptr) {
snprintf(p, p_max_size, "%s", grp->gr_name);
} else {
NORM_ERR("The gid %d doesn't exist", gid);

View File

@ -38,7 +38,7 @@ static void user_name(char *ptr) {
const struct utmp *usr = 0;
setutent();
while ((usr = getutent()) != NULL) {
while ((usr = getutent()) != nullptr) {
if (usr->ut_type == USER_PROCESS) {
if (strlen(ptr) + strlen(usr->ut_name) + 1 <= BUFLEN) {
strncat(ptr, usr->ut_name, UT_NAMESIZE);
@ -51,7 +51,7 @@ static void user_num(int *ptr) {
int users_num = 0;
setutent();
while ((usr = getutent()) != NULL) {
while ((usr = getutent()) != nullptr) {
if (usr->ut_type == USER_PROCESS) {
++users_num;
}
@ -62,7 +62,7 @@ static void user_term(char *ptr) {
const struct utmp *usr;
setutent();
while ((usr = getutent()) != NULL) {
while ((usr = getutent()) != nullptr) {
if (usr->ut_type == USER_PROCESS) {
if (strlen(ptr) + strlen(usr->ut_line) + 1 <= BUFLEN) {
strncat(ptr, usr->ut_line, UT_LINESIZE);
@ -76,7 +76,7 @@ static void user_time(char *ptr) {
char buf[BUFLEN] = "";
setutent();
while ((usr = getutent()) != NULL) {
while ((usr = getutent()) != nullptr) {
if (usr->ut_type == USER_PROCESS) {
log_in = usr->ut_time;
time(&real);
@ -97,7 +97,7 @@ static void tty_user_time(char *ptr, char *tty) {
setutent();
strcpy(line.ut_line, tty);
usr = getutline(&line);
if (usr == NULL) {
if (usr == nullptr) {
return;
}
@ -110,13 +110,13 @@ static void tty_user_time(char *ptr, char *tty) {
}
static void users_alloc(struct information *ptr) {
if (ptr->users.names == NULL) {
if (ptr->users.names == nullptr) {
ptr->users.names = (char *)malloc(text_buffer_size.get(*state));
}
if (ptr->users.terms == NULL) {
if (ptr->users.terms == nullptr) {
ptr->users.terms = (char *)malloc(text_buffer_size.get(*state));
}
if (ptr->users.times == NULL) {
if (ptr->users.times == nullptr) {
ptr->users.times = (char *)malloc(text_buffer_size.get(*state));
}
}
@ -125,13 +125,13 @@ static void update_user_time(char *tty) {
struct information *current_info = &info;
char temp[BUFLEN] = "";
if (current_info->users.ctime == NULL) {
if (current_info->users.ctime == nullptr) {
current_info->users.ctime = (char *)malloc(text_buffer_size.get(*state));
}
tty_user_time(temp, tty);
if (temp != NULL) {
if (temp != nullptr) {
free_and_zero(current_info->users.ctime);
current_info->users.ctime = (char *)malloc(text_buffer_size.get(*state));
strncpy(current_info->users.ctime, temp, text_buffer_size.get(*state));
@ -148,7 +148,7 @@ int update_users(void) {
int t;
users_alloc(current_info);
user_name(temp);
if (temp != NULL) {
if (temp != nullptr) {
free_and_zero(current_info->users.names);
current_info->users.names = (char *)malloc(text_buffer_size.get(*state));
strncpy(current_info->users.names, temp, text_buffer_size.get(*state));
@ -168,7 +168,7 @@ int update_users(void) {
}
temp[0] = 0;
user_term(temp);
if (temp != NULL) {
if (temp != nullptr) {
free_and_zero(current_info->users.terms);
current_info->users.terms = (char *)malloc(text_buffer_size.get(*state));
strncpy(current_info->users.terms, temp, text_buffer_size.get(*state));
@ -178,7 +178,7 @@ int update_users(void) {
strncpy(current_info->users.terms, "broken", text_buffer_size.get(*state));
}
user_time(temp);
if (temp != NULL) {
if (temp != nullptr) {
free_and_zero(current_info->users.times);
current_info->users.times = (char *)malloc(text_buffer_size.get(*state));
strncpy(current_info->users.times, temp, text_buffer_size.get(*state));

View File

@ -163,7 +163,7 @@ int rel_humidity(int dew_point, int air) {
#ifdef BUILD_WEATHER_XOAP
void weather_forecast::parse_df(xmlXPathContextPtr xpathCtx) {
int i, j, k;
char *content = NULL;
char *content = nullptr;
xmlXPathObjectPtr xpathObj;
xpathObj = xmlXPathEvalExpression((const xmlChar *)"/error/err", xpathCtx);
@ -180,7 +180,7 @@ void weather_forecast::parse_df(xmlXPathContextPtr xpathCtx) {
for (i = 0; i < NUM_XPATH_EXPRESSIONS_DF; i++) {
xpathObj = xmlXPathEvalExpression((const xmlChar *)xpath_expression_df[i],
xpathCtx);
if (xpathObj != NULL) {
if (xpathObj != nullptr) {
xmlNodeSetPtr nodes = xpathObj->nodesetval;
k = 0;
for (j = 0; j < nodes->nodeNr; ++j) {
@ -233,13 +233,13 @@ weather_forecast::weather_forecast(const std::string &data) {
xmlDocPtr doc;
xmlXPathContextPtr xpathCtx;
if (!(doc = xmlReadMemory(data.c_str(), data.length(), "", NULL, 0))) {
if (!(doc = xmlReadMemory(data.c_str(), data.length(), "", nullptr, 0))) {
NORM_ERR("weather_forecast: can't read xml data");
return;
}
xpathCtx = xmlXPathNewContext(doc);
if (xpathCtx == NULL) {
if (xpathCtx == nullptr) {
NORM_ERR("weather_forecast: unable to create new XPath context");
xmlFreeDoc(doc);
return;
@ -309,13 +309,13 @@ void weather::parse_weather_xml(const std::string &data) {
xmlDocPtr doc;
xmlXPathContextPtr xpathCtx;
if (!(doc = xmlReadMemory(data.c_str(), data.length(), "", NULL, 0))) {
if (!(doc = xmlReadMemory(data.c_str(), data.length(), "", nullptr, 0))) {
NORM_ERR("weather: can't read xml data");
return;
}
xpathCtx = xmlXPathNewContext(doc);
if (xpathCtx == NULL) {
if (xpathCtx == nullptr) {
NORM_ERR("weather: unable to create new XPath context");
xmlFreeDoc(doc);
return;
@ -634,18 +634,18 @@ weather::weather(const std::string &data)
lastupd = lastupd_;
// Process all tokens
char *p_tok = NULL;
char *p_save = NULL;
char *p_tok = nullptr;
char *p_save = nullptr;
if ((strtok_r(s_tmp, delim, &p_save)) != NULL) {
if ((strtok_r(s_tmp, delim, &p_save)) != nullptr) {
// Jump first token, must be icao
p_tok = strtok_r(NULL, delim, &p_save);
p_tok = strtok_r(nullptr, delim, &p_save);
do {
parse_token(p_tok);
p_tok = strtok_r(NULL, delim, &p_save);
p_tok = strtok_r(nullptr, delim, &p_save);
} while (p_tok != NULL);
} while (p_tok != nullptr);
}
return;
} else {
@ -878,7 +878,7 @@ void load_xoap_keys(void) {
std::string xoap = to_real_path(XOAP_FILE);
fp = fopen(xoap.c_str(), "r");
if (fp != NULL) {
if (fp != nullptr) {
if (fscanf(fp, "%10s %16s", par, key) == 2) {
xoap_cc = std::string("?cc=*&link=xoap&prod=xoap&par=") + par +
"&key=" + key + "&unit=m";

View File

@ -32,11 +32,11 @@
#include "conky.h"
#include "logging.h"
#include "x11.h"
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#include <X11/Xmd.h>
#include <X11/Xutil.h>
#include "x11.h"
#ifdef BUILD_IMLIB2
#include "imlib2.h"
#endif /* BUILD_IMLIB2 */
@ -55,7 +55,7 @@ bool have_argb_visual;
#endif /* BUILD_ARGB */
/* some basic X11 stuff */
Display *display = NULL;
Display *display = nullptr;
int display_width;
int display_height;
int screen;
@ -68,7 +68,7 @@ struct conky_window window;
char window_created = 0;
/* local prototypes */
static void update_workarea(void);
static void update_workarea();
static Window find_desktop_window(Window *p_root, Window *p_desktop);
static Window find_subwindow(Window win, int w, int h);
static void init_X11();
@ -82,7 +82,9 @@ void out_to_x_setting::lua_setter(lua::state &l, bool init) {
Base::lua_setter(l, init);
if (init && do_convert(l, -1).first) init_X11();
if (init && do_convert(l, -1).first) {
init_X11();
}
++s;
}
@ -90,7 +92,9 @@ void out_to_x_setting::lua_setter(lua::state &l, bool init) {
void out_to_x_setting::cleanup(lua::state &l) {
lua::stack_sentry s(l, -1);
if (do_convert(l, -1).first) deinit_X11();
if (do_convert(l, -1).first) {
deinit_X11();
}
l.pop();
}
@ -110,9 +114,9 @@ void own_window_setting::lua_setter(lua::state &l, bool init) {
#endif
}
if (out_to_x.get(l))
if (out_to_x.get(l)) {
init_window(l, do_convert(l, -1).first);
else {
} else {
// own_window makes no sense when not drawing to X
l.pop();
l.pushboolean(false);
@ -125,11 +129,13 @@ void own_window_setting::lua_setter(lua::state &l, bool init) {
#ifdef BUILD_XDBE
bool use_xdbe_setting::set_up(lua::state &l) {
// double_buffer makes no sense when not drawing to X
if (not out_to_x.get(l)) return false;
if (not out_to_x.get(l)) {
return false;
}
int major, minor;
if (not XdbeQueryExtension(display, &major, &minor)) {
if (XdbeQueryExtension(display, &major, &minor) == 0) {
NORM_ERR("No compatible double buffer extension found");
return false;
}
@ -209,8 +215,9 @@ void colour_setting::lua_setter(lua::state &l, bool init) {
if (not out_to_x.get(l)) {
// ignore if we're not using X
l.replace(-2);
} else
} else {
Base::lua_setter(l, init);
}
++s;
}
@ -258,7 +265,7 @@ conky::lua_traits<window_hints>::Map conky::lua_traits<window_hints>::map = {
std::pair<uint16_t, bool> window_hints_traits::convert(
lua::state &l, int index, const std::string &name) {
typedef conky::lua_traits<window_hints> Traits;
using Traits = conky::lua_traits<window_hints>;
lua::stack_sentry s(l);
l.checkstack(1);
@ -273,7 +280,9 @@ std::pair<uint16_t, bool> window_hints_traits::convert(
if (newpos > pos) {
l.pushstring(hints.substr(pos, newpos - pos));
auto t = conky::lua_traits<window_hints>::convert(l, -1, name);
if (not t.second) return {0, false};
if (not t.second) {
return {0, false};
};
SET_HINT(ret, t.first);
l.pop();
}
@ -388,11 +397,13 @@ static int __attribute__((noreturn)) x11_ioerror_handler(Display *d) {
/* X11 initializer */
static void init_X11() {
if (!display) {
const std::string &dispstr = display_name.get(*state).c_str();
// passing NULL to XOpenDisplay should open the default display
const char *disp = dispstr.size() ? dispstr.c_str() : NULL;
if ((display = XOpenDisplay(disp)) == NULL) {
if (display == nullptr) {
const std::string &dispstr = display_name.get(*state);
// passing nullptr to XOpenDisplay should open the default display
const char *disp = static_cast<unsigned int>(!dispstr.empty()) != 0u
? dispstr.c_str()
: nullptr;
if ((display = XOpenDisplay(disp)) == nullptr) {
throw std::runtime_error(std::string("can't open display: ") +
XDisplayName(disp));
}
@ -423,10 +434,10 @@ static void init_X11() {
static void deinit_X11() {
XCloseDisplay(display);
display = NULL;
display = nullptr;
}
static void update_workarea(void) {
static void update_workarea() {
/* default work area is display */
workarea[0] = 0;
workarea[1] = 0;
@ -436,19 +447,19 @@ static void update_workarea(void) {
#ifdef BUILD_XINERAMA
/* if xinerama is being used, adjust workarea to the head's area */
int useless1, useless2;
if (!XineramaQueryExtension(display, &useless1, &useless2)) {
if (XineramaQueryExtension(display, &useless1, &useless2) == 0) {
return; /* doesn't even have xinerama */
}
if (!XineramaIsActive(display)) {
if (XineramaIsActive(display) == 0) {
return; /* has xinerama but isn't using it */
}
int heads = 0;
XineramaScreenInfo *si = XineramaQueryScreens(display, &heads);
if (!si) {
if (si == nullptr) {
NORM_ERR(
"warning: XineramaQueryScreen returned NULL, ignoring head settings");
"warning: XineramaQueryScreen returned nullptr, ignoring head settings");
return; /* queryscreens failed? */
}
@ -482,21 +493,21 @@ static Window find_desktop_window(Window *p_root, Window *p_desktop) {
Window root = RootWindow(display, screen);
Window win = root;
Window troot, parent, *children;
unsigned char *buf = NULL;
unsigned char *buf = nullptr;
if (!p_root || !p_desktop) {
if ((p_root == nullptr) || (p_desktop == nullptr)) {
return 0;
}
/* some window managers set __SWM_VROOT to some child of root window */
XQueryTree(display, root, &troot, &parent, &children, &n);
for (i = 0; i < (int)n; i++) {
for (i = 0; i < static_cast<int>(n); i++) {
if (XGetWindowProperty(display, children[i], ATOM(__SWM_VROOT), 0, 1, False,
XA_WINDOW, &type, &format, &nitems, &bytes,
&buf) == Success &&
type == XA_WINDOW) {
win = *(Window *)buf;
win = *reinterpret_cast<Window *>(buf);
XFree(buf);
XFree(children);
fprintf(stderr,
@ -509,9 +520,9 @@ static Window find_desktop_window(Window *p_root, Window *p_desktop) {
return win;
}
if (buf) {
if (buf != nullptr) {
XFree(buf);
buf = 0;
buf = nullptr;
}
}
XFree(children);
@ -523,9 +534,9 @@ static Window find_desktop_window(Window *p_root, Window *p_desktop) {
win = find_subwindow(win, workarea[2], workarea[3]);
if (buf) {
if (buf != nullptr) {
XFree(buf);
buf = 0;
buf = nullptr;
}
if (win != root) {
@ -581,8 +592,9 @@ void set_transparent_background(Window win) {
XQueryTree(display, parent, &r, &parent, &children, &n);
XFree(children);
}
} else
} else {
do_set_background(win, 0);
}
#ifdef BUILD_ARGB
}
#endif /* BUILD_ARGB */
@ -617,13 +629,13 @@ static int get_argb_visual(Visual **visual, int *depth) {
}
#endif /* BUILD_ARGB */
void destroy_window(void) {
void destroy_window() {
#ifdef BUILD_XFT
if (window.xftdraw) {
if (window.xftdraw != nullptr) {
XftDrawDestroy(window.xftdraw);
}
#endif /* BUILD_XFT */
if (window.gc) {
if (window.gc != nullptr) {
XFreeGC(display, window.gc);
}
memset(&window, 0, sizeof(struct conky_window));
@ -638,14 +650,14 @@ static void init_window(lua::state &l __attribute__((unused)), bool own) {
#ifdef OWN_WINDOW
if (own) {
int depth = 0, flags = CWOverrideRedirect | CWBackingStore;
Visual *visual = NULL;
Visual *visual = nullptr;
if (!find_desktop_window(&window.root, &window.desktop)) {
if (find_desktop_window(&window.root, &window.desktop) == 0u) {
return;
}
#ifdef BUILD_ARGB
if (use_argb_visual.get(l) && get_argb_visual(&visual, &depth)) {
if (use_argb_visual.get(l) && (get_argb_visual(&visual, &depth) != 0)) {
have_argb_visual = true;
window.visual = visual;
window.colourmap = XCreateColormap(display, DefaultRootWindow(display),
@ -772,12 +784,12 @@ static void init_window(lua::state &l __attribute__((unused)), bool own) {
wmHint.initial_state = NormalState;
}
XmbSetWMProperties(display, window.window, NULL, NULL, argv_copy,
argc_copy, NULL, &wmHint, &classHint);
XmbSetWMProperties(display, window.window, nullptr, nullptr, argv_copy,
argc_copy, nullptr, &wmHint, &classHint);
XStoreName(display, window.window, own_window_title.get(l).c_str());
/* Sets an empty WM_PROTOCOLS property */
XSetWMProtocols(display, window.window, NULL, 0);
XSetWMProtocols(display, window.window, nullptr, 0);
/* Set window type */
if ((xa = ATOM(_NET_WM_WINDOW_TYPE)) != None) {
@ -807,7 +819,8 @@ static void init_window(lua::state &l __attribute__((unused)), bool own) {
break;
}
XChangeProperty(display, window.window, xa, XA_ATOM, 32,
PropModeReplace, (unsigned char *)&prop, 1);
PropModeReplace,
reinterpret_cast<unsigned char *>(&prop), 1);
}
/* Set desired hints */
@ -821,7 +834,7 @@ static void init_window(lua::state &l __attribute__((unused)), bool own) {
if (xa != None) {
long prop[5] = {2, 0, 0, 0, 0};
XChangeProperty(display, window.window, xa, xa, 32, PropModeReplace,
(unsigned char *)prop, 5);
reinterpret_cast<unsigned char *>(prop), 5);
}
}
@ -835,7 +848,8 @@ static void init_window(lua::state &l __attribute__((unused)), bool own) {
long prop = 0;
XChangeProperty(display, window.window, xa, XA_CARDINAL, 32,
PropModeAppend, (unsigned char *)&prop, 1);
PropModeAppend,
reinterpret_cast<unsigned char *>(&prop), 1);
}
xa = ATOM(_NET_WM_STATE);
@ -843,7 +857,8 @@ static void init_window(lua::state &l __attribute__((unused)), bool own) {
Atom xa_prop = ATOM(_NET_WM_STATE_BELOW);
XChangeProperty(display, window.window, xa, XA_ATOM, 32,
PropModeAppend, (unsigned char *)&xa_prop, 1);
PropModeAppend,
reinterpret_cast<unsigned char *>(&xa_prop), 1);
}
}
@ -857,7 +872,8 @@ static void init_window(lua::state &l __attribute__((unused)), bool own) {
long prop = 6;
XChangeProperty(display, window.window, xa, XA_CARDINAL, 32,
PropModeAppend, (unsigned char *)&prop, 1);
PropModeAppend,
reinterpret_cast<unsigned char *>(&prop), 1);
}
xa = ATOM(_NET_WM_STATE);
@ -865,7 +881,8 @@ static void init_window(lua::state &l __attribute__((unused)), bool own) {
Atom xa_prop = ATOM(_NET_WM_STATE_ABOVE);
XChangeProperty(display, window.window, xa, XA_ATOM, 32,
PropModeAppend, (unsigned char *)&xa_prop, 1);
PropModeAppend,
reinterpret_cast<unsigned char *>(&xa_prop), 1);
}
}
@ -879,7 +896,8 @@ static void init_window(lua::state &l __attribute__((unused)), bool own) {
CARD32 xa_prop = 0xFFFFFFFF;
XChangeProperty(display, window.window, xa, XA_CARDINAL, 32,
PropModeAppend, (unsigned char *)&xa_prop, 1);
PropModeAppend,
reinterpret_cast<unsigned char *>(&xa_prop), 1);
}
xa = ATOM(_NET_WM_STATE);
@ -887,7 +905,8 @@ static void init_window(lua::state &l __attribute__((unused)), bool own) {
Atom xa_prop = ATOM(_NET_WM_STATE_STICKY);
XChangeProperty(display, window.window, xa, XA_ATOM, 32,
PropModeAppend, (unsigned char *)&xa_prop, 1);
PropModeAppend,
reinterpret_cast<unsigned char *>(&xa_prop), 1);
}
}
@ -901,7 +920,8 @@ static void init_window(lua::state &l __attribute__((unused)), bool own) {
Atom xa_prop = ATOM(_NET_WM_STATE_SKIP_TASKBAR);
XChangeProperty(display, window.window, xa, XA_ATOM, 32,
PropModeAppend, (unsigned char *)&xa_prop, 1);
PropModeAppend,
reinterpret_cast<unsigned char *>(&xa_prop), 1);
}
}
@ -915,7 +935,8 @@ static void init_window(lua::state &l __attribute__((unused)), bool own) {
Atom xa_prop = ATOM(_NET_WM_STATE_SKIP_PAGER);
XChangeProperty(display, window.window, xa, XA_ATOM, 32,
PropModeAppend, (unsigned char *)&xa_prop, 1);
PropModeAppend,
reinterpret_cast<unsigned char *>(&xa_prop), 1);
}
}
}
@ -931,13 +952,13 @@ static void init_window(lua::state &l __attribute__((unused)), bool own) {
{
XWindowAttributes attrs;
if (!window.window) {
if (window.window == 0u) {
window.window = find_desktop_window(&window.root, &window.desktop);
}
window.visual = DefaultVisual(display, screen);
window.colourmap = DefaultColormap(display, screen);
if (XGetWindowAttributes(display, window.window, &attrs)) {
if (XGetWindowAttributes(display, window.window, &attrs) != 0) {
window.width = attrs.width;
window.height = attrs.height;
}
@ -973,7 +994,7 @@ static Window find_subwindow(Window win, int w, int h) {
for (j = 0; j < n; j++) {
XWindowAttributes attrs;
if (XGetWindowAttributes(display, children[j], &attrs)) {
if (XGetWindowAttributes(display, children[j], &attrs) != 0) {
/* Window must be mapped and same size as display or
* work space */
if (attrs.map_state != 0 &&
@ -994,7 +1015,7 @@ static Window find_subwindow(Window win, int w, int h) {
return win;
}
void create_gc(void) {
void create_gc() {
XGCValues values;
values.graphics_exposures = 0;
@ -1010,10 +1031,12 @@ static inline void get_x11_desktop_current(Display *current_display,
int actual_format;
unsigned long nitems;
unsigned long bytes_after;
unsigned char *prop = NULL;
unsigned char *prop = nullptr;
struct information *current_info = &info;
if (atom == None) return;
if (atom == None) {
return;
}
if ((XGetWindowProperty(current_display, root, atom, 0, 1L, False,
XA_CARDINAL, &actual_type, &actual_format, &nitems,
@ -1021,7 +1044,7 @@ static inline void get_x11_desktop_current(Display *current_display,
(actual_type == XA_CARDINAL) && (nitems == 1L) && (actual_format == 32)) {
current_info->x11.desktop.current = prop[0] + 1;
}
if (prop) {
if (prop != nullptr) {
XFree(prop);
}
}
@ -1033,10 +1056,12 @@ static inline void get_x11_desktop_number(Display *current_display, Window root,
int actual_format;
unsigned long nitems;
unsigned long bytes_after;
unsigned char *prop = NULL;
unsigned char *prop = nullptr;
struct information *current_info = &info;
if (atom == None) return;
if (atom == None) {
return;
}
if ((XGetWindowProperty(current_display, root, atom, 0, 1L, False,
XA_CARDINAL, &actual_type, &actual_format, &nitems,
@ -1044,7 +1069,7 @@ static inline void get_x11_desktop_number(Display *current_display, Window root,
(actual_type == XA_CARDINAL) && (nitems == 1L) && (actual_format == 32)) {
current_info->x11.desktop.number = prop[0];
}
if (prop) {
if (prop != nullptr) {
XFree(prop);
}
}
@ -1056,10 +1081,12 @@ static inline void get_x11_desktop_names(Display *current_display, Window root,
int actual_format;
unsigned long nitems;
unsigned long bytes_after;
unsigned char *prop = NULL;
unsigned char *prop = nullptr;
struct information *current_info = &info;
if (atom == None) return;
if (atom == None) {
return;
}
if ((XGetWindowProperty(current_display, root, atom, 0, (~0L), False,
ATOM(UTF8_STRING), &actual_type, &actual_format,
@ -1069,7 +1096,7 @@ static inline void get_x11_desktop_names(Display *current_display, Window root,
current_info->x11.desktop.all_names.assign(
reinterpret_cast<const char *>(prop), nitems);
}
if (prop) {
if (prop != nullptr) {
XFree(prop);
}
}
@ -1111,7 +1138,7 @@ void get_x11_desktop_info(Display *current_display, Atom atom) {
/* Set the PropertyChangeMask on the root window, if not set */
XGetWindowAttributes(display, root, &window_attributes);
if (!(window_attributes.your_event_mask & PropertyChangeMask)) {
if ((window_attributes.your_event_mask & PropertyChangeMask) == 0) {
XSetWindowAttributes attributes;
attributes.event_mask =
window_attributes.your_event_mask | PropertyChangeMask;
@ -1239,18 +1266,20 @@ void set_struts(int sidenum) {
}
XChangeProperty(display, window.window, strut, XA_CARDINAL, 32,
PropModeReplace, (unsigned char *)&sizes, 4);
PropModeReplace, reinterpret_cast<unsigned char *>(&sizes),
4);
if ((strut = ATOM(_NET_WM_STRUT_PARTIAL)) != None) {
XChangeProperty(display, window.window, strut, XA_CARDINAL, 32,
PropModeReplace, (unsigned char *)&sizes, 12);
PropModeReplace,
reinterpret_cast<unsigned char *>(&sizes), 12);
}
}
}
#endif /* OWN_WINDOW */
#ifdef BUILD_XDBE
void xdbe_swap_buffers(void) {
void xdbe_swap_buffers() {
if (use_xdbe.get(*state)) {
XdbeSwapInfo swap;

View File

@ -106,7 +106,7 @@ extern char window_created;
void destroy_window(void);
void create_gc(void);
void set_transparent_background(Window win);
void get_x11_desktop_info(Display *display, Atom atom);
void get_x11_desktop_info(Display *current_display, Atom atom);
void set_struts(int);
void print_monitor(struct text_object *, char *, int);

View File

@ -35,31 +35,31 @@ xmmsc_connection_t *xmms2_conn;
#define CONN_NO 2
static void xmms_alloc(struct information *ptr) {
if (ptr->xmms2.artist == NULL) {
if (ptr->xmms2.artist == nullptr) {
ptr->xmms2.artist = (char *)malloc(text_buffer_size.get(*state));
}
if (ptr->xmms2.album == NULL) {
if (ptr->xmms2.album == nullptr) {
ptr->xmms2.album = (char *)malloc(text_buffer_size.get(*state));
}
if (ptr->xmms2.title == NULL) {
if (ptr->xmms2.title == nullptr) {
ptr->xmms2.title = (char *)malloc(text_buffer_size.get(*state));
}
if (ptr->xmms2.genre == NULL) {
if (ptr->xmms2.genre == nullptr) {
ptr->xmms2.genre = (char *)malloc(text_buffer_size.get(*state));
}
if (ptr->xmms2.comment == NULL) {
if (ptr->xmms2.comment == nullptr) {
ptr->xmms2.comment = (char *)malloc(text_buffer_size.get(*state));
}
if (ptr->xmms2.url == NULL) {
if (ptr->xmms2.url == nullptr) {
ptr->xmms2.url = (char *)malloc(text_buffer_size.get(*state));
}
if (ptr->xmms2.date == NULL) {
if (ptr->xmms2.date == nullptr) {
ptr->xmms2.date = (char *)malloc(text_buffer_size.get(*state));
}
@ -137,7 +137,7 @@ int handle_curent_id(xmmsv_t *value, void *p) {
ptr->xmms2.id = current_id;
infos = xmmsv_propdict_to_dict(val, NULL);
infos = xmmsv_propdict_to_dict(val, nullptr);
if (xmmsv_dict_get(infos, "artist", &dict_entry) &&
xmmsv_get_string(dict_entry, &charval))
@ -222,7 +222,7 @@ int handle_playback_state_change(xmmsv_t *value, void *p) {
return TRUE;
}
if (ptr->xmms2.status == NULL) {
if (ptr->xmms2.status == nullptr) {
ptr->xmms2.status = (char *)malloc(text_buffer_size.get(*state));
ptr->xmms2.status[0] = '\0';
}
@ -255,7 +255,7 @@ int handle_playlist_loaded(xmmsv_t *value, void *p) {
return TRUE;
}
if (ptr->xmms2.playlist == NULL) {
if (ptr->xmms2.playlist == nullptr) {
ptr->xmms2.playlist = (char *)malloc(text_buffer_size.get(*state));
ptr->xmms2.playlist[0] = '\0';
}
@ -289,12 +289,12 @@ int update_xmms2(void) {
/* initialize connection */
if (current_info->xmms2.conn_state == CONN_INIT) {
if (xmms2_conn == NULL) {
if (xmms2_conn == nullptr) {
xmms2_conn = xmmsc_init(PACKAGE_NAME);
}
/* did init fail? */
if (xmms2_conn == NULL) {
if (xmms2_conn == nullptr) {
fprintf(stderr, "XMMS2 init failed. %s\n",
xmmsc_get_last_error(xmms2_conn));
return 0;