diff --git a/.clang-format b/.clang-format deleted file mode 100644 index 784c8a93..00000000 --- a/.clang-format +++ /dev/null @@ -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 -... diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..378eac25 --- /dev/null +++ b/.dockerignore @@ -0,0 +1 @@ +build diff --git a/.gitignore b/.gitignore index de23aaab..a507d0fb 100644 --- a/.gitignore +++ b/.gitignore @@ -11,7 +11,6 @@ doc/*.html Makefile CMakeCache.txt CMakeFiles -*.cmake data/convertconf.h data/defconfig.h lua/libcairo-orig.c diff --git a/.travis.yml b/.travis.yml index 14a911b5..c10efd13 100644 --- a/.travis.yml +++ b/.travis.yml @@ -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' diff --git a/CMakeLists.txt b/CMakeLists.txt index 3910d33f..920b26bf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,7 +19,7 @@ # along with this program. If not, see . # -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) diff --git a/Dockerfile b/Dockerfile index 2f5ec359..bb3ec60b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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 diff --git a/README.md b/README.md index 9da3f487..0caf1d84 100755 --- a/README.md +++ b/README.md @@ -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. diff --git a/cmake/ConkyBuildOptions.cmake b/cmake/ConkyBuildOptions.cmake index 5f17d966..9ba21f15 100644 --- a/cmake/ConkyBuildOptions.cmake +++ b/cmake/ConkyBuildOptions.cmake @@ -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) diff --git a/cmake/FindClangFormat.cmake b/cmake/FindClangFormat.cmake deleted file mode 100644 index 036afd7a..00000000 --- a/cmake/FindClangFormat.cmake +++ /dev/null @@ -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() diff --git a/cmake/FindClangTidy.cmake b/cmake/FindClangTidy.cmake new file mode 100644 index 00000000..473c9fb6 --- /dev/null +++ b/cmake/FindClangTidy.cmake @@ -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() diff --git a/cmake/clang-format.cmake b/cmake/clang-format.cmake deleted file mode 100644 index 423d1ef6..00000000 --- a/cmake/clang-format.cmake +++ /dev/null @@ -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} -) - diff --git a/cmake/clang-tidy.cmake b/cmake/clang-tidy.cmake new file mode 100644 index 00000000..6af7f387 --- /dev/null +++ b/cmake/clang-tidy.cmake @@ -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() diff --git a/sonar-project.properties b/sonar-project.properties new file mode 100644 index 00000000..0c0821a1 --- /dev/null +++ b/sonar-project.properties @@ -0,0 +1,4 @@ +sonar.projectKey=conky +sonar.projectName=Conky +sonar.sources=src +sonar.cfamily.build-wrapper-output=build/bw-output diff --git a/src/algebra.cc b/src/algebra.cc index 0617972f..31721854 100644 --- a/src/algebra.cc +++ b/src/algebra.cc @@ -27,10 +27,10 @@ * */ #include "algebra.h" -#include -#include -#include -#include +#include +#include +#include +#include #include #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(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(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(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; diff --git a/src/apcupsd.cc b/src/apcupsd.cc index 7e2c7de8..8734e44b 100644 --- a/src/apcupsd.cc +++ b/src/apcupsd.cc @@ -26,7 +26,7 @@ #include "logging.h" #include "text_object.h" -#include +#include #include #include #include @@ -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(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(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(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)); diff --git a/src/audacious.cc b/src/audacious.cc index 4c38ebea..416a9cf9 100644 --- a/src/audacious.cc +++ b/src/audacious.cc @@ -101,7 +101,7 @@ class audacious_cb : public conky::callback { 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 { 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)) { diff --git a/src/bmpx.cc b/src/bmpx.cc index b23f3d81..5c088a58 100644 --- a/src/bmpx.cc +++ b/src/bmpx.cc @@ -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; diff --git a/src/c++wrap.cc b/src/c++wrap.cc index 14f9788e..eb46b147 100644 --- a/src/c++wrap.cc +++ b/src/c++wrap.cc @@ -24,14 +24,14 @@ #include "c++wrap.hh" -#include +#include #include /* force use of POSIX strerror_r instead of non-portable GNU specific */ #ifdef _GNU_SOURCE #undef _GNU_SOURCE #endif -#include +#include #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 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(fd[0], fd[1]); + } + { return std::pair(fd[0], fd[1]); } } diff --git a/src/ccurl_thread.cc b/src/ccurl_thread.cc index 8c771568..4dd1f078 100644 --- a/src/ccurl_thread.cc +++ b/src/ccurl_thread.cc @@ -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; diff --git a/src/colours.cc b/src/colours.cc index a8fa4e22..f40befd4 100644 --- a/src/colours.cc +++ b/src/colours.cc @@ -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(r * CONST_8_TO_5_BITS) << 11; + colour |= static_cast(g * CONST_8_TO_6_BITS) << 5; + colour |= static_cast(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(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(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(color.pixel); } long get_x11_color(const std::string &colour) { diff --git a/src/combine.cc b/src/combine.cc index 9edff96d..2fdfd5e3 100644 --- a/src/combine.cc +++ b/src/combine.cc @@ -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(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(malloc(endvar[0] - startvar[0] + 1)); + cd->seperation = static_cast(malloc(startvar[1] - endvar[0] + 1)); + cd->right = static_cast(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(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(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(obj->data.opaque); std::vector> 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(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(strlen(current[i]->row)) > longest) { + longest = static_cast(strlen(current[i]->row)); + } + current[i]->next = + static_cast(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(strlen(current[i]->row)) > longest) { + longest = static_cast(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(obj->data.opaque); - if (!cd) return; + if (cd == nullptr) { + return; + } free(cd->left); free(cd->seperation); free(cd->right); diff --git a/src/common.cc b/src/common.cc index 4f1db15f..6dc51cf3 100644 --- a/src/common.cc +++ b/src/common.cc @@ -27,16 +27,16 @@ * */ -#include -#include #include #include #include #include #include #include -#include #include +#include +#include +#include #include #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 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(f + 0.5); } + return static_cast(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(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(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(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(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(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(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(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(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(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(static_cast(visible) == 0); } void print_include(struct text_object *obj, char *p, int p_max_size) { std::vector 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; } diff --git a/src/common.h b/src/common.h index 3f4f6511..8b6407ec 100644 --- a/src/common.h +++ b/src/common.h @@ -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); diff --git a/src/conky.cc b/src/conky.cc index 2e3d6df8..00e52554 100644 --- a/src/conky.cc +++ b/src/conky.cc @@ -28,15 +28,16 @@ */ #include "conky.h" -#include -#include -#include -#include -#include #include +#include +#include +#include #include +#include +#include #include #include +#include #include #include #include "common.h" @@ -51,8 +52,8 @@ #include #endif /* HAVE_SYS_INOTIFY_H */ #ifdef BUILD_X11 -#include #include "x11.h" +#include #ifdef BUILD_XDAMAGE #include #endif @@ -140,7 +141,7 @@ namespace { const char builtin_config_magic[] = "==builtin=="; -} +} // namespace #endif #ifdef BUILD_OLD_CONFIG @@ -236,7 +237,7 @@ void music_player_interval_setting::lua_setter(lua::state &l, bool init) { music_player_interval_setting music_player_interval; -void *global_cpu = NULL; +void *global_cpu = nullptr; static conky::range_config_setting max_text_width( "max_text_width", 0, std::numeric_limits::max(), 0, true); @@ -248,10 +249,10 @@ int argc_copy; char **argv_copy; /* prototypes for internally used functions */ -static void signal_handler(int); -static void reload_config(void); +static void signal_handler(int /*sig*/); +static void reload_config(); -static void print_version(void) { +static void print_version() { std::cout << _(PACKAGE_NAME " " VERSION " compiled " BUILD_DATE " for " BUILD_ARCH "\n" @@ -424,7 +425,7 @@ static const char *suffixes[] = {_nop("B"), _nop("KiB"), _nop("MiB"), #ifdef BUILD_X11 -static void X11_create_window(void); +static void X11_create_window(); struct _x11_stuff_s { Region region; @@ -477,11 +478,11 @@ conky::range_config_setting diskio_avg_samples("diskio_avg_samples", 1, 14, /* filenames for output */ static conky::simple_config_setting overwrite_file( "overwrite_file", std::string(), true); -static FILE *overwrite_fpointer = NULL; +static FILE *overwrite_fpointer = nullptr; static conky::simple_config_setting append_file("append_file", std::string(), true); -static FILE *append_fpointer = NULL; +static FILE *append_fpointer = nullptr; #ifdef BUILD_HTTP std::string webpage; @@ -512,8 +513,8 @@ class out_to_http_setting : public conky::simple_config_setting { Base::lua_setter(l, init); if (init && do_convert(l, -1).first) { - httpd = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, HTTPPORT, NULL, NULL, - &sendanswer, NULL, MHD_OPTION_END); + httpd = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, HTTPPORT, nullptr, NULL, + &sendanswer, nullptr, MHD_OPTION_END); } ++s; @@ -524,7 +525,7 @@ class out_to_http_setting : public conky::simple_config_setting { if (do_convert(l, -1).first) { MHD_stop_daemon(httpd); - httpd = NULL; + httpd = nullptr; } l.pop(); @@ -575,7 +576,7 @@ static conky::range_config_setting maximum_width( static bool isutf8(const char *envvar) { char *s = getenv(envvar); - if (s) { + if (s != nullptr) { std::string temp = s; std::transform(temp.begin(), temp.end(), temp.begin(), ::tolower); if ((temp.find("utf-8") != std::string::npos) || @@ -608,9 +609,9 @@ conky::range_config_setting text_buffer_size( /* pad percentages to decimals? */ static conky::simple_config_setting pad_percents("pad_percents", 0, false); -static char *global_text = 0; +static char *global_text = nullptr; -char *get_global_text(void) { return global_text; } +char *get_global_text() { return global_text; } long global_text_lines; @@ -621,9 +622,9 @@ std::unique_ptr state; void set_updatereset(int i) { updatereset = i; } -int get_updatereset(void) { return updatereset; } +int get_updatereset() { return updatereset; } -int get_total_updates(void) { return total_updates; } +int get_total_updates() { return total_updates; } int calc_text_width(const char *s) { size_t slen = strlen(s); @@ -640,17 +641,17 @@ int calc_text_width(const char *s) { if (utf8_mode.get(*state)) { XftTextExtentsUtf8(display, fonts[selected_font].xftfont, - (const FcChar8 *)s, slen, &gi); + reinterpret_cast(s), slen, &gi); } else { - XftTextExtents8(display, fonts[selected_font].xftfont, (const FcChar8 *)s, - slen, &gi); + XftTextExtents8(display, fonts[selected_font].xftfont, + reinterpret_cast(s), slen, &gi); } return gi.xOff; - } else -#endif /* BUILD_XFT */ - { - return XTextWidth(fonts[selected_font].font, s, slen); } +#endif /* BUILD_XFT */ + + return XTextWidth(fonts[selected_font].font, s, slen); + #endif /* BUILD_X11 */ } @@ -665,8 +666,10 @@ static inline void for_each_line(char *b, int f(char *, int)) { char *ps, *pe; int special_index = 0; /* specials index */ - if (!b) return; - for (ps = b, pe = b; *pe; pe++) { + if (b == nullptr) { + return; + } + for (ps = b, pe = b; *pe != 0; pe++) { if (*pe == '\n') { *pe = '\0'; special_index = f(ps, special_index); @@ -683,7 +686,7 @@ static inline void for_each_line(char *b, int f(char *, int)) { static void convert_escapes(char *buf) { char *p = buf, *s = buf; - while (*s) { + while (*s != 0) { if (*s == '\\') { s++; if (*s == 'n') { @@ -710,7 +713,7 @@ int spaced_print(char *buf, int size, const char *format, int width, ...) { if (size < 1) { return 0; } - tempbuf = (char *)malloc(size * sizeof(char)); + tempbuf = static_cast(malloc(size * sizeof(char))); // Passes the varargs along to vsnprintf va_start(argp, width); @@ -766,11 +769,12 @@ void human_readable(long long num, char *buf, int size) { } if (llabs(num) < 1000LL) { - spaced_print(buf, size, format, width, 0, (float)num, _(*suffix)); + spaced_print(buf, size, format, width, 0, static_cast(num), + _(*suffix)); return; } - while (llabs(num / 1024) >= 1000LL && **(suffix + 2)) { + while (llabs(num / 1024) >= 1000LL && (**(suffix + 2) != 0)) { num /= 1024; suffix++; } @@ -796,8 +800,12 @@ void human_readable(long long num, char *buf, int size) { * printed with a precision of 0. Yay. */ precision = 0; /* print 100-999 without decimal part */ - if (fnum < 99.95) precision = 1; /* print 10-99 with one decimal place */ - if (fnum < 9.995) precision = 2; /* print 0-9 with two decimal places */ + if (fnum < 99.95) { + precision = 1; /* print 10-99 with one decimal place */ + } + if (fnum < 9.995) { + precision = 2; /* print 0-9 with two decimal places */ + } spaced_print(buf, size, format, width, precision, fnum, _(*suffix)); } @@ -809,7 +817,7 @@ static long current_text_color; void set_current_text_color(long colour) { current_text_color = colour; } -long get_current_text_color(void) { return current_text_color; } +long get_current_text_color() { return current_text_color; } static void extract_variable_text(const char *p) { free_text_objects(&global_root_object); @@ -848,7 +856,9 @@ void generate_text_internal(char *p, int p_max_size, struct text_object root) { struct text_object *obj; size_t a; - if (!p) return; + if (p == nullptr) { + return; + } #ifdef BUILD_ICONV char *buff_in; @@ -859,24 +869,26 @@ void generate_text_internal(char *p, int p_max_size, struct text_object root) { p[0] = 0; obj = root.next; - while (obj && p_max_size > 0) { + while ((obj != nullptr) && p_max_size > 0) { /* check callbacks for existence and act accordingly */ - if (obj->callbacks.print) { + if (obj->callbacks.print != nullptr) { (*obj->callbacks.print)(obj, p, p_max_size); - } else if (obj->callbacks.iftest) { - if (!(*obj->callbacks.iftest)(obj)) { + } else if (obj->callbacks.iftest != nullptr) { + if ((*obj->callbacks.iftest)(obj) == 0) { DBGP2("jumping"); - if (obj->ifblock_next) obj = obj->ifblock_next; + if (obj->ifblock_next != nullptr) { + obj = obj->ifblock_next; + } } - } else if (obj->callbacks.barval) { + } else if (obj->callbacks.barval != nullptr) { new_bar(obj, p, p_max_size, (*obj->callbacks.barval)(obj)); - } else if (obj->callbacks.gaugeval) { + } else if (obj->callbacks.gaugeval != nullptr) { new_gauge(obj, p, p_max_size, (*obj->callbacks.gaugeval)(obj)); #ifdef BUILD_X11 - } else if (obj->callbacks.graphval) { + } else if (obj->callbacks.graphval != nullptr) { new_graph(obj, p, p_max_size, (*obj->callbacks.graphval)(obj)); #endif /* BUILD_X11 */ - } else if (obj->callbacks.percentage) { + } else if (obj->callbacks.percentage != nullptr) { percent_print(p, p_max_size, (*obj->callbacks.percentage)(obj)); } @@ -900,7 +912,7 @@ void generate_text_internal(char *p, int p_max_size, struct text_object root) { } void evaluate(const char *text, char *p, int p_max_size) { - struct text_object subroot; + struct text_object subroot {}; parse_conky_vars(&subroot, text, p, p_max_size); DBGP2("evaluated '%s' to '%s'", text, p); @@ -910,7 +922,7 @@ void evaluate(const char *text, char *p, int p_max_size) { double current_update_time, next_update_time, last_update_time; -static void generate_text(void) { +static void generate_text() { char *p; unsigned int i, j, k; special_count = 0; @@ -931,9 +943,9 @@ static void generate_text(void) { unsigned int tbs = text_buffer_size.get(*state); if (mw > 0) { for (i = 0, j = 0; p[i] != 0; i++) { - if (p[i] == '\n') + if (p[i] == '\n') { j = 0; - else if (j == mw) { + } else if (j == mw) { k = i + strlen(p + i) + 1; if (k < tbs) { while (k != i) { @@ -942,12 +954,14 @@ static void generate_text(void) { } p[k] = '\n'; j = 0; - } else + } else { NORM_ERR( "The end of the text_buffer is reached, increase " "\"text_buffer_size\""); - } else + } + } else { j++; + } } } @@ -955,7 +969,7 @@ static void generate_text(void) { char *tmp_p; tmp_p = text_buffer; - while (*tmp_p) { + while (*tmp_p != 0) { *tmp_p = toupper(*tmp_p); tmp_p++; } @@ -964,13 +978,14 @@ static void generate_text(void) { double ui = active_update_interval(); double time = get_time(); next_update_time += ui; - if (next_update_time < time || next_update_time > time + ui) + if (next_update_time < time || next_update_time > time + ui) { next_update_time = time - fmod(time, ui) + ui; + } last_update_time = current_update_time; total_updates++; } -int get_string_width(const char *s) { return *s ? calc_text_width(s) : 0; } +int get_string_width(const char *s) { return *s != 0 ? calc_text_width(s) : 0; } #ifdef BUILD_X11 static inline int get_border_total() { @@ -985,21 +1000,29 @@ static int get_string_width_special(char *s, int special_index) { int width = 0; long i; - if (!s) return 0; + if (s == nullptr) { + return 0; + } - if (not out_to_x.get(*state)) return strlen(s); + if (not out_to_x.get(*state)) { + return strlen(s); + } p = strndup(s, text_buffer_size.get(*state)); final = p; - for (i = 0; i < special_index; i++) current = current->next; - for (i = 0; i < idx; i++) current = current->next; + for (i = 0; i < special_index; i++) { + current = current->next; + } + for (i = 0; i < idx; i++) { + current = current->next; + } - while (*p) { + while (*p != 0) { if (*p == SPECIAL_CHAR) { /* shift everything over by 1 so that the special char * doesn't mess up the size calculation */ - for (i = 0; i < (long)strlen(p); i++) { + for (i = 0; i < static_cast(strlen(p)); i++) { *(p + i) = *(p + i + 1); } if (current->type == GRAPH || current->type == GAUGE || @@ -1018,9 +1041,11 @@ static int get_string_width_special(char *s, int special_index) { if (current_after_font->type == FONT) { influenced_by_font[i] = 0; break; - } else + } + { memmove(&influenced_by_font[i], &influenced_by_font[i + 1], strlen(&influenced_by_font[i + 1]) + 1); + } } } // add the length of influenced_by_font in the new font to width @@ -1033,11 +1058,12 @@ static int get_string_width_special(char *s, int special_index) { // in the old font int specials_skipped = 0; while (i > 0) { - if (p[specials_skipped] != 1) + if (p[specials_skipped] != 1) { memmove(&p[specials_skipped], &p[specials_skipped + 1], strlen(&p[specials_skipped + 1]) + 1); - else + } else { specials_skipped++; + } i--; } } @@ -1057,13 +1083,15 @@ static int get_string_width_special(char *s, int special_index) { static int text_size_updater(char *s, int special_index); int last_font_height; -static void update_text_area(void) { +static void update_text_area() { int x = 0, y = 0; - if (not out_to_x.get(*state)) return; - /* update text size if it isn't fixed */ + if (not out_to_x.get(*state)) { + return; + } + /* update text size if it isn't fixed */ #ifdef OWN_WINDOW - if (!fixed_size) + if (fixed_size == 0) #endif { text_width = minimum_width.get(*state); @@ -1133,7 +1161,7 @@ static void update_text_area(void) { #endif /* OWN_WINDOW */ #ifdef OWN_WINDOW - if (own_window.get(*state) && !fixed_pos) { + if (own_window.get(*state) && (fixed_pos == 0)) { x += workarea[0]; y += workarea[1]; @@ -1174,12 +1202,16 @@ static int text_size_updater(char *s, int special_index) { char *p; special_t *current = specials; - for (int i = 0; i < special_index; i++) current = current->next; + for (int i = 0; i < special_index; i++) { + current = current->next; + } - if (not out_to_x.get(*state)) return 0; + if (not out_to_x.get(*state)) { + return 0; + } /* get string widths and skip specials */ p = s; - while (*p) { + while (*p != 0) { if (*p == SPECIAL_CHAR) { *p = '\0'; w += get_string_width(s); @@ -1200,13 +1232,13 @@ static int text_size_updater(char *s, int special_index) { last_font_height += current->arg; } else if (current->type == GOTO) { if (current->arg > cur_x) { - w = (int)current->arg; + w = static_cast(current->arg); } } else if (current->type == TAB) { int start = current->arg; int step = current->width; - if (!step || step < 0) { + if ((step == 0) || step < 0) { step = 10; } w += step - (cur_x - text_start_x - start) % step; @@ -1261,17 +1293,18 @@ static inline void set_foreground_color(long c) { } #endif /* BUILD_NCURSES */ UNUSED(c); - return; } -std::string string_replace_all(std::string original, std::string oldpart, - std::string newpart, +std::string string_replace_all(std::string original, const std::string &oldpart, + const std::string &newpart, std::string::size_type start) { std::string::size_type i = start; int oldpartlen = oldpart.length(); while (1) { i = original.find(oldpart, i); - if (i == std::string::npos) break; + if (i == std::string::npos) { + break; + } original.replace(i, oldpartlen, newpart); } return original; @@ -1289,17 +1322,19 @@ static void draw_string(const char *s) { width_of_s = get_string_width(s); if (out_to_stdout.get(*state) && draw_mode == FG) { printf("%s\n", s); - if (extra_newline.get(*state)) fputc('\n', stdout); + if (extra_newline.get(*state)) { + fputc('\n', stdout); + } fflush(stdout); /* output immediately, don't buffer */ } if (out_to_stderr.get(*state) && draw_mode == FG) { fprintf(stderr, "%s\n", s); fflush(stderr); /* output immediately, don't buffer */ } - if (draw_mode == FG && overwrite_fpointer) { + if (draw_mode == FG && (overwrite_fpointer != nullptr)) { fprintf(overwrite_fpointer, "%s\n", s); } - if (draw_mode == FG && append_fpointer) { + if (draw_mode == FG && (append_fpointer != nullptr)) { fprintf(append_fpointer, "%s\n", s); } #ifdef BUILD_NCURSES @@ -1380,11 +1415,11 @@ static void draw_string(const char *s) { if (utf8_mode.get(*state)) { XftDrawStringUtf8(window.xftdraw, &c2, fonts[selected_font].xftfont, text_offset_x + cur_x, text_offset_y + cur_y, - (const XftChar8 *)s, strlen(s)); + reinterpret_cast(s), strlen(s)); } else { XftDrawString8(window.xftdraw, &c2, fonts[selected_font].xftfont, text_offset_x + cur_x, text_offset_y + cur_y, - (const XftChar8 *)s, strlen(s)); + reinterpret_cast(s), strlen(s)); } } else #endif @@ -1424,7 +1459,7 @@ int draw_each_line_inner(char *s, int special_index, int last_special_applied) { cur_x = text_start_x; #endif /* BUILD_X11 */ - while (*p) { + while (*p != 0) { if (*p == SPECIAL_CHAR || last_special_applied > -1) { #ifdef BUILD_X11 int w = 0; @@ -1442,7 +1477,9 @@ int draw_each_line_inner(char *s, int special_index, int last_special_applied) { } /* draw special */ special_t *current = specials; - for (int i = 0; i < special_index; i++) current = current->next; + for (int i = 0; i < special_index; i++) { + current = current->next; + } switch (current->type) { #ifdef BUILD_X11 case HORIZONTAL_LINE: { @@ -1548,12 +1585,15 @@ int draw_each_line_inner(char *s, int special_index, int last_special_applied) { usage = current->arg; scale = current->scale; angle = M_PI * usage / scale; - px = (float)(cur_x + (w / 2.)) - (float)(w / 2.) * cos(angle); - py = (float)(by + (h)) - (float)(h)*sin(angle); + px = static_cast(cur_x + (w / 2.)) - + static_cast(w / 2.) * cos(angle); + py = + static_cast(by + (h)) - static_cast(h) * sin(angle); XDrawLine(display, window.drawable, window.gc, text_offset_x + cur_x + (w / 2.), text_offset_y + by + (h), - text_offset_x + (int)(px), text_offset_y + (int)(py)); + text_offset_x + static_cast(px), + text_offset_y + static_cast(py)); #endif /* BUILD_MATH */ if (h > cur_y_add && h > font_h) { @@ -1599,8 +1639,8 @@ int draw_each_line_inner(char *s, int special_index, int last_special_applied) { JoinMiter); /* in case we don't have a graph yet */ - if (current->graph) { - unsigned long *tmpcolour = 0; + if (current->graph != nullptr) { + unsigned long *tmpcolour = nullptr; if (current->last_colour != 0 || current->first_colour != 0) { tmpcolour = do_gradient(w - 1, current->last_colour, @@ -1609,7 +1649,7 @@ int draw_each_line_inner(char *s, int special_index, int last_special_applied) { colour_idx = 0; for (i = w - 2; i > -1; i--) { if (current->last_colour != 0 || current->first_colour != 0) { - if (current->tempgrad) { + if (current->tempgrad != 0) { #ifdef DEBUG_lol assert((int)((float)(w - 2) - current->graph[j] * (w - 2) / (float)current->scale) < @@ -1623,10 +1663,10 @@ int draw_each_line_inner(char *s, int special_index, int last_special_applied) { 0); } #endif /* DEBUG_lol */ - set_foreground_color(tmpcolour[( - int)((float)(w - 2) - - current->graph[j] * (w - 2) / - std::max((float)current->scale, 1.0f))]); + set_foreground_color(tmpcolour[static_cast( + static_cast(w - 2) - + current->graph[j] * (w - 2) / + std::max(static_cast(current->scale), 1.0f))]); } else { set_foreground_color(tmpcolour[colour_idx++]); } @@ -1636,7 +1676,7 @@ int draw_each_line_inner(char *s, int special_index, int last_special_applied) { display, window.drawable, window.gc, text_offset_x + cur_x + i + 1, text_offset_y + by + h, text_offset_x + cur_x + i + 1, - text_offset_y + round_to_int((double)by + h - + text_offset_y + round_to_int(static_cast(by) + h - current->graph[j] * (h - 1) / current->scale)); ++j; @@ -1680,8 +1720,9 @@ int draw_each_line_inner(char *s, int special_index, int last_special_applied) { tmp_sec_str = strdup(""); } if (asprintf(&tmp_str, "%s%s%s%s", tmp_day_str, tmp_hour_str, - tmp_min_str, tmp_sec_str) == -1) + tmp_min_str, tmp_sec_str) == -1) { tmp_str = strdup(""); + } free(tmp_day_str); free(tmp_hour_str); free(tmp_min_str); @@ -1706,7 +1747,7 @@ int draw_each_line_inner(char *s, int special_index, int last_special_applied) { cur_x += font_ascent() / 2; cur_y += font_h / 2; const int tmp_str_len = 64; - tmp_str = (char *)calloc(tmp_str_len, sizeof(char)); + tmp_str = static_cast(calloc(tmp_str_len, sizeof(char))); sprintf(tmp_str, "%.1f", current->scale); draw_string(tmp_str); free(tmp_str); @@ -1764,7 +1805,7 @@ int draw_each_line_inner(char *s, int special_index, int last_special_applied) { int start = current->arg; int step = current->width; - if (!step || step < 0) { + if ((step == 0) || step < 0) { step = 10; } w = step - (cur_x - text_start_x - start) % step; @@ -1811,9 +1852,11 @@ int draw_each_line_inner(char *s, int special_index, int last_special_applied) { case GOTO: if (current->arg >= 0) { #ifdef BUILD_X11 - cur_x = (int)current->arg; + cur_x = static_cast(current->arg); // make sure shades are 1 pixel to the right of the text - if (draw_mode == BG) cur_x++; + if (draw_mode == BG) { + cur_x++; + } #endif /* BUILD_X11 */ #ifdef BUILD_NCURSES if (out_to_ncurses.get(*state)) { @@ -1850,7 +1893,9 @@ int draw_each_line_inner(char *s, int special_index, int last_special_applied) { } #endif /* BUILD_NCURSES */ #ifdef BUILD_X11 - if (out_to_x.get(*state)) cur_y += font_descent(); + if (out_to_x.get(*state)) { + cur_y += font_descent(); + } #endif /* BUILD_X11 */ return special_index; } @@ -1871,7 +1916,7 @@ static int draw_line(char *s, int special_index) { return 0; } -static void draw_text(void) { +static void draw_text() { #ifdef BUILD_HTTP #define WEBPAGE_START1 \ " 0) { - if (stippled_borders.get(*state)) { + if (stippled_borders.get(*state) != 0) { char ss[2] = {stippled_borders.get(*state), stippled_borders.get(*state)}; XSetLineAttributes(display, window.gc, bw, LineOnOffDash, CapButt, @@ -1934,7 +1979,7 @@ static void draw_text(void) { #endif } -static void draw_stuff(void) { +static void draw_stuff() { #ifndef BUILD_X11 static int text_offset_x, text_offset_y; /* offset for start position */ #endif @@ -1942,15 +1987,17 @@ static void draw_stuff(void) { #ifdef BUILD_IMLIB2 cimlib_render(text_start_x, text_start_y, window.width, window.height); #endif /* BUILD_IMLIB2 */ - if (overwrite_file.get(*state).size()) { - overwrite_fpointer = fopen(overwrite_file.get(*state).c_str(), "w"); - if (!overwrite_fpointer) + if (static_cast(!overwrite_file.get(*state).empty()) != 0u) { + overwrite_fpointer = fopen(overwrite_file.get(*state).c_str(), "we"); + if (overwrite_fpointer == nullptr) { NORM_ERR("Cannot overwrite '%s'", overwrite_file.get(*state).c_str()); + } } - if (append_file.get(*state).size()) { - append_fpointer = fopen(append_file.get(*state).c_str(), "a"); - if (!append_fpointer) + if (static_cast(!append_file.get(*state).empty()) != 0u) { + append_fpointer = fopen(append_file.get(*state).c_str(), "ae"); + if (append_fpointer == nullptr) { NORM_ERR("Cannot append to '%s'", append_file.get(*state).c_str()); + } } #ifdef BUILD_X11 llua_draw_pre_hook(); @@ -1998,13 +2045,13 @@ static void draw_stuff(void) { } #endif #endif /* BUILD_X11 && BUILD_XDBE */ - if (overwrite_fpointer) { + if (overwrite_fpointer != nullptr) { fclose(overwrite_fpointer); - overwrite_fpointer = 0; + overwrite_fpointer = nullptr; } - if (append_fpointer) { + if (append_fpointer != nullptr) { fclose(append_fpointer); - append_fpointer = 0; + append_fpointer = nullptr; } } @@ -2014,19 +2061,20 @@ static void clear_text(int exposures) { if (use_xdbe.get(*state)) { /* The swap action is XdbeBackground, which clears */ return; - } else + } #else if (use_xpmdb.get(*state)) { return; } else #endif - if (display && window.window) { // make sure these are !null + if ((display != nullptr) && + (window.window != 0u)) { // make sure these are !null /* there is some extra space for borders and outlines */ int border_total = get_border_total(); XClearArea(display, window.window, text_start_x - border_total, text_start_y - border_total, text_width + 2 * border_total, - text_height + 2 * border_total, exposures ? True : 0); + text_height + 2 * border_total, exposures != 0 ? True : 0); } } #endif /* BUILD_X11 */ @@ -2034,13 +2082,15 @@ static void clear_text(int exposures) { static int need_to_update; /* update_text() generates new text and clears old text area */ -static void update_text(void) { +static void update_text() { #ifdef BUILD_IMLIB2 cimlib_cleanup(); #endif /* BUILD_IMLIB2 */ generate_text(); #ifdef BUILD_X11 - if (out_to_x.get(*state)) clear_text(1); + if (out_to_x.get(*state)) { + clear_text(1); + } #endif /* BUILD_X11 */ need_to_update = 1; llua_update_info(&info, active_update_interval()); @@ -2054,24 +2104,26 @@ bool is_on_battery() { // checks if at least one battery specified in // "detect_battery" is discharging char buf[64]; std::string detect_battery_str; - std::string str_buf = {""}; + std::string str_buf = str_buf; detect_battery_str.assign(detect_battery.get(*state)); detect_battery_str += ','; - for (std::string::size_type i = 0; i < detect_battery_str.size(); - i++) { // parse using ',' as delimiter - if ((detect_battery_str[i] != ',') && (detect_battery_str[i] != ' ')) - str_buf += detect_battery_str[i]; - if ((detect_battery_str[i] == ',') && !str_buf.empty()) { + for (char i : detect_battery_str) { // parse using ',' as delimiter + if ((i != ',') && (i != ' ')) { + str_buf += i; + } + if ((i == ',') && !str_buf.empty()) { get_battery_short_status(buf, 64, str_buf.c_str()); - if (buf[0] == 'D') return true; + if (buf[0] == 'D') { + return true; + } str_buf = ""; } } return false; } -static void main_loop(void) { +static void main_loop() { int terminate = 0; #ifdef SIGNAL_BLOCKING sigset_t newmask, oldmask; @@ -2096,14 +2148,15 @@ static void main_loop(void) { if (out_to_x.get(*state)) { /* allow only decorated windows to be given mouse input */ int major_version, minor_version; - if (!XShapeQueryVersion(display, &major_version, &minor_version)) { + if (XShapeQueryVersion(display, &major_version, &minor_version) == 0) { NORM_ERR("Input shapes are not supported"); } else { if (own_window.get(*state) && (own_window_type.get(*state) != TYPE_NORMAL || - (TEST_HINT(own_window_hints.get(*state), HINT_UNDECORATED)))) { - XShapeCombineRectangles(display, window.window, ShapeInput, 0, 0, NULL, - 0, ShapeSet, Unsorted); + ((TEST_HINT(own_window_hints.get(*state), HINT_UNDECORATED)) != + 0))) { + XShapeCombineRectangles(display, window.window, ShapeInput, 0, 0, + nullptr, 0, ShapeSet, Unsorted); } } } @@ -2115,14 +2168,15 @@ static void main_loop(void) { info.looped = 0; while (terminate == 0 && (total_run_times.get(*state) == 0 || info.looped < total_run_times.get(*state))) { - if ((update_interval_on_battery.get(*state) != NOBATTERY)) + if ((update_interval_on_battery.get(*state) != NOBATTERY)) { on_battery = is_on_battery(); + } info.looped++; #ifdef SIGNAL_BLOCKING /* block signals. we will inspect for pending signals later */ if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0) { - CRIT_ERR(NULL, NULL, "unable to sigprocmask()"); + CRIT_ERR(nullptr, NULL, "unable to sigprocmask()"); } #endif @@ -2132,20 +2186,20 @@ static void main_loop(void) { /* wait for X event or timeout */ - if (!XPending(display)) { + if (XPending(display) == 0) { fd_set fdsr; - struct timeval tv; + struct timeval tv {}; int s; t = next_update_time - get_time(); t = std::min(std::max(t, 0.0), active_update_interval()); - tv.tv_sec = (long)t; - tv.tv_usec = (long)(t * 1000000) % 1000000; + tv.tv_sec = static_cast(t); + tv.tv_usec = static_cast(t * 1000000) % 1000000; FD_ZERO(&fdsr); FD_SET(ConnectionNumber(display), &fdsr); - s = select(ConnectionNumber(display) + 1, &fdsr, 0, 0, &tv); + s = select(ConnectionNumber(display) + 1, &fdsr, nullptr, nullptr, &tv); if (s == -1) { if (errno != EINTR) { NORM_ERR("can't select(): %s", strerror(errno)); @@ -2158,7 +2212,7 @@ static void main_loop(void) { } } - if (need_to_update) { + if (need_to_update != 0) { #ifdef OWN_WINDOW int wx = window.x, wy = window.y; #endif @@ -2173,7 +2227,7 @@ static void main_loop(void) { int border_total = get_border_total(); /* resize window if it isn't right size */ - if (!fixed_size && + if ((fixed_size == 0) && (text_width + 2 * border_total != window.width || text_height + 2 * border_total != window.height)) { window.width = text_width + 2 * border_total; @@ -2211,16 +2265,16 @@ static void main_loop(void) { } /* move window if it isn't in right position */ - if (!fixed_pos && (window.x != wx || window.y != wy)) { + if ((fixed_pos == 0) && (window.x != wx || window.y != wy)) { XMoveWindow(display, window.window, window.x, window.y); changed++; } /* update struts */ - if (changed && own_window_type.get(*state) == TYPE_PANEL) { + if ((changed != 0) && own_window_type.get(*state) == TYPE_PANEL) { int sidenum = -1; - fprintf(stderr, _(PACKAGE_NAME ": defining struts\n")); + fprintf(stderr, "%s", _(PACKAGE_NAME ": defining struts\n")); fflush(stderr); switch (text_alignment.get(*state)) { @@ -2273,7 +2327,7 @@ static void main_loop(void) { } /* handle X events */ - while (XPending(display)) { + while (XPending(display) != 0) { XEvent ev; XNextEvent(display, &ev); @@ -2330,7 +2384,8 @@ static void main_loop(void) { { XWindowAttributes attrs; - if (XGetWindowAttributes(display, window.window, &attrs)) { + if (XGetWindowAttributes(display, window.window, &attrs) != + 0) { window.width = attrs.width; window.height = attrs.height; } @@ -2369,7 +2424,7 @@ static void main_loop(void) { own_window_type.get(*state) == TYPE_DESKTOP) { /* allow conky to hold input focus. */ break; - } else { + } /* forward the click to the desktop window */ XUngrabPointer(display, ev.xbutton.time); ev.xbutton.window = window.desktop; @@ -2379,7 +2434,6 @@ static void main_loop(void) { &ev); XSetInputFocus(display, ev.xbutton.window, RevertToParent, ev.xbutton.time); - } } break; @@ -2391,14 +2445,13 @@ static void main_loop(void) { HINT_UNDECORATED)) { /* allow conky to hold input focus. */ break; - } else { + } /* forward the release to the desktop window */ ev.xbutton.window = window.desktop; ev.xbutton.x = ev.xbutton.x_root; ev.xbutton.y = ev.xbutton.y_root; XSendEvent(display, ev.xbutton.window, False, ButtonReleaseMask, &ev); - } } break; @@ -2407,7 +2460,7 @@ static void main_loop(void) { default: #ifdef BUILD_XDAMAGE if (ev.type == x11_stuff.event_base + XDamageNotify) { - XDamageNotifyEvent *dev = (XDamageNotifyEvent *)&ev; + auto *dev = reinterpret_cast(&ev); XFixesSetRegion(display, x11_stuff.part, &dev->area, 1); XFixesUnionRegion(display, x11_stuff.region2, x11_stuff.region2, @@ -2420,7 +2473,7 @@ static void main_loop(void) { #ifdef BUILD_XDAMAGE XDamageSubtract(display, x11_stuff.damage, x11_stuff.region2, None); - XFixesSetRegion(display, x11_stuff.region2, 0, 0); + XFixesSetRegion(display, x11_stuff.region2, nullptr, 0); #endif /* BUILD_XDAMAGE */ /* XDBE doesn't seem to provide a way to clear the back buffer @@ -2430,7 +2483,7 @@ static void main_loop(void) { * the exposed area. OTOH, if we're not going to call draw_stuff at * all, then no swap happens and we can safely do nothing. */ - if (!XEmptyRegion(x11_stuff.region)) { + if (XEmptyRegion(x11_stuff.region) == 0) { #if defined(BUILD_XDBE) if (use_xdbe.get(*state)) { #else @@ -2458,7 +2511,9 @@ static void main_loop(void) { } else { #endif /* BUILD_X11 */ t = (next_update_time - get_time()) * 1000000; - if (t > 0) usleep((useconds_t)t); + if (t > 0) { + usleep(static_cast(t)); + } update_text(); draw_stuff(); #ifdef BUILD_NCURSES @@ -2473,20 +2528,20 @@ static void main_loop(void) { #ifdef SIGNAL_BLOCKING /* unblock signals of interest and let handler fly */ - if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0) { - CRIT_ERR(NULL, NULL, "unable to sigprocmask()"); + if (sigprocmask(SIG_SETMASK, &oldmask, nullptr) < 0) { + CRIT_ERR(nullptr, NULL, "unable to sigprocmask()"); } #endif - if (g_sighup_pending) { - g_sighup_pending = false; + if (g_sighup_pending != 0) { + g_sighup_pending = 0; NORM_ERR("received SIGHUP or SIGUSR1. reloading the config file."); reload_config(); } - if (g_sigusr2_pending) { - g_sigusr2_pending = false; + if (g_sigusr2_pending != 0) { + g_sigusr2_pending = 0; // refresh view; NORM_ERR("recieved SIGUSR2. refreshing."); update_text(); @@ -2499,14 +2554,14 @@ static void main_loop(void) { #endif } - if (g_sigterm_pending) { - g_sigterm_pending = false; + if (g_sigterm_pending != 0) { + g_sigterm_pending = 0; NORM_ERR("received SIGINT or SIGTERM to terminate. bye!"); terminate = 1; #ifdef BUILD_X11 if (out_to_x.get(*state)) { XDestroyRegion(x11_stuff.region); - x11_stuff.region = NULL; + x11_stuff.region = nullptr; #ifdef BUILD_XDAMAGE XDamageDestroy(display, x11_stuff.damage); XFixesDestroyRegion(display, x11_stuff.region2); @@ -2532,7 +2587,7 @@ static void main_loop(void) { time_to_wait.tv_sec = time_to_wait.tv_usec = 0; - select(inotify_fd + 1, &descriptors, NULL, NULL, &time_to_wait); + select(inotify_fd + 1, &descriptors, nullptr, NULL, &time_to_wait); if (FD_ISSET(inotify_fd, &descriptors)) { /* process inotify events */ len = read(inotify_fd, inotify_buff, INOTIFY_BUF_LEN - 1); @@ -2566,7 +2621,7 @@ static void main_loop(void) { llua_update_info(&info, active_update_interval()); } - clean_up(NULL, NULL); + clean_up(nullptr, nullptr); #ifdef HAVE_SYS_INOTIFY_H if (inotify_fd != -1) { @@ -2580,9 +2635,9 @@ static void main_loop(void) { void initialisation(int argc, char **argv); /* reload the config file */ -static void reload_config(void) { - struct stat sb; - if (stat(current_config.c_str(), &sb) || +static void reload_config() { + struct stat sb {}; + if ((stat(current_config.c_str(), &sb) != 0) || (!S_ISREG(sb.st_mode) && !S_ISLNK(sb.st_mode))) { NORM_ERR(_("Config file '%s' is gone, continuing with config from " "memory.\nIf you recreate this file sent me a SIGUSR1 to tell " @@ -2590,15 +2645,15 @@ static void reload_config(void) { current_config.c_str(), getpid()); return; } - clean_up(NULL, NULL); - state.reset(new lua::state); + clean_up(nullptr, nullptr); + state = std::make_unique(); conky::export_symbols(*state); sleep(1); /* slight pause */ initialisation(argc_copy, argv_copy); } #ifdef BUILD_X11 -void clean_up_x11(void) { +void clean_up_x11() { if (window_created == 1) { int border_total = get_border_total(); @@ -2608,19 +2663,21 @@ void clean_up_x11(void) { } destroy_window(); free_fonts(utf8_mode.get(*state)); - if (x11_stuff.region) { + if (x11_stuff.region != nullptr) { XDestroyRegion(x11_stuff.region); - x11_stuff.region = NULL; + x11_stuff.region = nullptr; } } #endif void free_specials(special_t *¤t) { - if (current) { + if (current != nullptr) { free_specials(current->next); - if (current->type == GRAPH) free(current->graph); + if (current->type == GRAPH) { + free(current->graph); + } delete current; - current = NULL; + current = nullptr; } } @@ -2630,16 +2687,17 @@ void clean_up_without_threads(void *memtofree1, void *memtofree2) { free_and_zero(info.cpu_usage); #ifdef BUILD_X11 - if (out_to_x.get(*state)) + if (out_to_x.get(*state)) { clean_up_x11(); - else + } else { fonts.clear(); // in set_default_configurations a font is set but not - // loaded + } + // loaded #endif /* BUILD_X11 */ - if (info.first_process) { + if (info.first_process != nullptr) { free_all_processes(); - info.first_process = NULL; + info.first_process = nullptr; } free_text_objects(&global_root_object); @@ -2672,7 +2730,7 @@ void clean_up(void *memtofree1, void *memtofree2) { clean_up_without_threads(memtofree1, memtofree2); } -static void set_default_configurations(void) { +static void set_default_configurations() { update_uname(); info.memmax = 0; top_cpu = 0; @@ -2683,14 +2741,14 @@ static void set_default_configurations(void) { #endif top_running = 0; #ifdef BUILD_XMMS2 - info.xmms2.artist = NULL; - info.xmms2.album = NULL; - info.xmms2.title = NULL; - info.xmms2.genre = NULL; - info.xmms2.comment = NULL; - info.xmms2.url = NULL; - info.xmms2.status = NULL; - info.xmms2.playlist = NULL; + info.xmms2.artist = nullptr; + info.xmms2.album = nullptr; + info.xmms2.title = nullptr; + info.xmms2.genre = nullptr; + info.xmms2.comment = nullptr; + info.xmms2.url = nullptr; + info.xmms2.status = nullptr; + info.xmms2.playlist = nullptr; #endif /* BUILD_XMMS2 */ state->pushboolean(true); #ifdef BUILD_X11 @@ -2703,7 +2761,7 @@ static void set_default_configurations(void) { } #ifdef BUILD_X11 -static void X11_create_window(void) { +static void X11_create_window() { if (out_to_x.get(*state)) { setup_fonts(); load_fonts(utf8_mode.get(*state)); @@ -2711,8 +2769,9 @@ static void X11_create_window(void) { #ifdef OWN_WINDOW if (own_window.get(*state)) { - if (not fixed_pos) + if (fixed_pos == 0) { XMoveWindow(display, window.window, window.x, window.y); + } set_transparent_background(window.window); } @@ -2724,8 +2783,8 @@ static void X11_create_window(void) { x11_stuff.region = XCreateRegion(); #ifdef BUILD_XDAMAGE - if (!XDamageQueryExtension(display, &x11_stuff.event_base, - &x11_stuff.error_base)) { + if (XDamageQueryExtension(display, &x11_stuff.event_base, + &x11_stuff.error_base) == 0) { NORM_ERR("Xdamage extension unavailable"); } x11_stuff.damage = @@ -2751,11 +2810,12 @@ void load_config_file() { try { #ifdef BUILD_BUILTIN_CONFIG - if (current_config == builtin_config_magic) + if (current_config == builtin_config_magic) { l.loadstring(defconfig); - else + } else { #endif l.loadfile(current_config.c_str()); + } } catch (lua::syntax_error &e) { #define SYNTAX_ERR_READ_CONF "Syntax error (%s) while reading config file. " #ifdef BUILD_OLD_CONFIG @@ -2778,8 +2838,9 @@ void load_config_file() { l.getglobal("conky"); l.getfield(-1, "text"); l.replace(-2); - if (l.type(-1) != lua::TSTRING) + if (l.type(-1) != lua::TSTRING) { throw conky::error(_("missing text block in configuration")); + } /* Remove \\-\n. */ l.gsub(l.tocstring(-1), "\\\n", ""); @@ -2880,43 +2941,48 @@ static const char *getopt_string = ; static const struct option longopts[] = { - {"help", 0, NULL, 'h'}, {"version", 0, NULL, 'V'}, - {"quiet", 0, NULL, 'q'}, {"debug", 0, NULL, 'D'}, - {"config", 1, NULL, 'c'}, + {"help", 0, nullptr, 'h'}, {"version", 0, nullptr, 'V'}, + {"quiet", 0, nullptr, 'q'}, {"debug", 0, nullptr, 'D'}, + {"config", 1, nullptr, 'c'}, #ifdef BUILD_BUILTIN_CONFIG - {"print-config", 0, NULL, 'C'}, + {"print-config", 0, nullptr, 'C'}, #endif - {"daemonize", 0, NULL, 'd'}, + {"daemonize", 0, nullptr, 'd'}, #ifdef BUILD_X11 - {"alignment", 1, NULL, 'a'}, {"font", 1, NULL, 'f'}, - {"display", 1, NULL, 'X'}, + {"alignment", 1, nullptr, 'a'}, {"font", 1, nullptr, 'f'}, + {"display", 1, nullptr, 'X'}, #ifdef OWN_WINDOW - {"own-window", 0, NULL, 'o'}, + {"own-window", 0, nullptr, 'o'}, #endif - {"double-buffer", 0, NULL, 'b'}, {"window-id", 1, NULL, 'w'}, + {"double-buffer", 0, nullptr, 'b'}, {"window-id", 1, nullptr, 'w'}, #endif /* BUILD_X11 */ - {"text", 1, NULL, 't'}, {"interval", 1, NULL, 'u'}, - {"pause", 1, NULL, 'p'}, {0, 0, 0, 0}}; + {"text", 1, nullptr, 't'}, {"interval", 1, nullptr, 'u'}, + {"pause", 1, nullptr, 'p'}, {nullptr, 0, nullptr, 0}}; void set_current_config() { /* load current_config, CONFIG_FILE or SYSTEM_CONFIG_FILE */ - struct stat s; + struct stat s {}; if (current_config.empty()) { /* Try to use personal config file first */ std::string buf = to_real_path(XDG_CONFIG_FILE); - if (stat(buf.c_str(), &s) == 0) current_config = buf; + if (stat(buf.c_str(), &s) == 0) { + current_config = buf; + } } if (current_config.empty()) { /* Try to use personal config file first */ std::string buf = to_real_path(CONFIG_FILE); - if (stat(buf.c_str(), &s) == 0) current_config = buf; + if (stat(buf.c_str(), &s) == 0) { + current_config = buf; + } } /* Try to use system config file if personal config does not exist */ - if (current_config.empty() && (stat(SYSTEM_CONFIG_FILE, &s) == 0)) + if (current_config.empty() && (stat(SYSTEM_CONFIG_FILE, &s) == 0)) { current_config = SYSTEM_CONFIG_FILE; + } /* No readable config found */ if (current_config.empty()) { @@ -2930,11 +2996,14 @@ void set_current_config() { } // "-" stands for "read from stdin" - if (current_config == "-") current_config = "/dev/stdin"; + if (current_config == "-") { + current_config = "/dev/stdin"; + } } void initialisation(int argc, char **argv) { - struct sigaction act, oact; + struct sigaction act { + }, oact{}; clear_net_stats(); set_default_configurations(); @@ -2948,13 +3017,13 @@ void initialisation(int argc, char **argv) { #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) if ((kd = kvm_open("/dev/null", "/dev/null", "/dev/null", O_RDONLY, - "kvm_open")) == NULL) { - CRIT_ERR(NULL, NULL, "cannot read kvm"); + "kvm_open")) == nullptr) { + CRIT_ERR(nullptr, NULL, "cannot read kvm"); } #endif while (1) { - int c = getopt_long(argc, argv, getopt_string, longopts, NULL); + int c = getopt_long(argc, argv, getopt_string, longopts, nullptr); int startup_pause; char *conv_end; @@ -3008,7 +3077,7 @@ void initialisation(int argc, char **argv) { case 'u': state->pushinteger(strtol(optarg, &conv_end, 10)); if (*conv_end != 0) { - CRIT_ERR(NULL, NULL, "'%s' is a wrong update-interval", optarg); + CRIT_ERR(nullptr, nullptr, "'%s' is a wrong update-interval", optarg); } update_interval.lua_set(*state); break; @@ -3016,7 +3085,7 @@ void initialisation(int argc, char **argv) { case 'i': state->pushinteger(strtol(optarg, &conv_end, 10)); if (*conv_end != 0) { - CRIT_ERR(NULL, NULL, "'%s' is a wrong number of update-times", + CRIT_ERR(nullptr, nullptr, "'%s' is a wrong number of update-times", optarg); } total_run_times.lua_set(*state); @@ -3025,7 +3094,7 @@ void initialisation(int argc, char **argv) { case 'x': state->pushinteger(strtol(optarg, &conv_end, 10)); if (*conv_end != 0) { - CRIT_ERR(NULL, NULL, "'%s' is a wrong value for the X-position", + CRIT_ERR(nullptr, nullptr, "'%s' is a wrong value for the X-position", optarg); } gap_x.lua_set(*state); @@ -3034,14 +3103,14 @@ void initialisation(int argc, char **argv) { case 'y': state->pushinteger(strtol(optarg, &conv_end, 10)); if (*conv_end != 0) { - CRIT_ERR(NULL, NULL, "'%s' is a wrong value for the Y-position", + CRIT_ERR(nullptr, nullptr, "'%s' is a wrong value for the Y-position", optarg); } gap_y.lua_set(*state); break; #endif /* BUILD_X11 */ case 'p': - if (first_pass) { + if (first_pass != 0) { startup_pause = atoi(optarg); sleep(startup_pause); } @@ -3064,7 +3133,7 @@ void initialisation(int argc, char **argv) { extract_variable_text(global_text); free_and_zero(global_text); /* fork */ - if (fork_to_background.get(*state) && first_pass) { + if (fork_to_background.get(*state) && (first_pass != 0)) { int pid = fork(); switch (pid) { @@ -3089,11 +3158,11 @@ void initialisation(int argc, char **argv) { } } - text_buffer = (char *)malloc(max_user_text.get(*state)); + text_buffer = static_cast(malloc(max_user_text.get(*state))); memset(text_buffer, 0, max_user_text.get(*state)); - tmpstring1 = (char *)malloc(text_buffer_size.get(*state)); + tmpstring1 = static_cast(malloc(text_buffer_size.get(*state))); memset(tmpstring1, 0, text_buffer_size.get(*state)); - tmpstring2 = (char *)malloc(text_buffer_size.get(*state)); + tmpstring2 = static_cast(malloc(text_buffer_size.get(*state))); memset(tmpstring2, 0, text_buffer_size.get(*state)); #ifdef BUILD_X11 @@ -3132,9 +3201,9 @@ int main(int argc, char **argv) { #endif argc_copy = argc; argv_copy = argv; - g_sigterm_pending = false; - g_sighup_pending = false; - g_sigusr2_pending = false; + g_sigterm_pending = 0; + g_sighup_pending = 0; + g_sigusr2_pending = 0; #ifdef BUILD_CURL struct curl_global_initializer { @@ -3156,7 +3225,7 @@ int main(int argc, char **argv) { } #endif /* BUILD_X11 */ while (1) { - int c = getopt_long(argc, argv, getopt_string, longopts, NULL); + int c = getopt_long(argc, argv, getopt_string, longopts, nullptr); if (c == -1) { break; @@ -3174,8 +3243,8 @@ int main(int argc, char **argv) { current_config = optarg; break; case 'q': - if (!freopen("/dev/null", "w", stderr)) - CRIT_ERR(0, 0, "could not open /dev/null as stderr!"); + if (freopen("/dev/null", "w", stderr) == nullptr) + CRIT_ERR(nullptr, nullptr, "could not open /dev/null as stderr!"); break; case 'h': print_help(argv[0]); @@ -3187,7 +3256,7 @@ int main(int argc, char **argv) { #endif #ifdef BUILD_X11 case 'w': - window.window = strtol(optarg, 0, 0); + window.window = strtol(optarg, nullptr, 0); break; #endif /* BUILD_X11 */ @@ -3199,7 +3268,7 @@ int main(int argc, char **argv) { try { set_current_config(); - state.reset(new lua::state); + state = std::make_unique(); conky::export_symbols(*state); @@ -3229,7 +3298,7 @@ int main(int argc, char **argv) { return EXIT_FAILURE; } catch (obj_create_error &e) { std::cerr << e.what() << std::endl; - clean_up(NULL, NULL); + clean_up(nullptr, nullptr); return EXIT_FAILURE; } catch (std::exception &e) { std::cerr << PACKAGE_NAME ": " << e.what() << std::endl; @@ -3254,14 +3323,14 @@ static void signal_handler(int sig) { switch (sig) { case SIGINT: case SIGTERM: - g_sigterm_pending = true; + g_sigterm_pending = 1; break; case SIGHUP: case SIGUSR1: - g_sighup_pending = true; + g_sighup_pending = 1; break; case SIGUSR2: - g_sigusr2_pending = true; + g_sigusr2_pending = 1; default: /* Reaching here means someone set a signal * (SIGXXXX, signal_handler), but didn't write any code diff --git a/src/conky.h b/src/conky.h index 4db04e96..a51a2351 100644 --- a/src/conky.h +++ b/src/conky.h @@ -360,7 +360,7 @@ template void free_and_zero(T *&ptr) { if (ptr) { free(ptr); - ptr = NULL; + ptr = nullptr; } } diff --git a/src/core.cc b/src/core.cc index 762c6227..db19e86a 100644 --- a/src/core.cc +++ b/src/core.cc @@ -118,8 +118,8 @@ #include "darwin.h" #endif -#include -#include +#include +#include /* strip a leading /dev/ if any, following symlinks first * @@ -130,17 +130,21 @@ const char *dev_name(const char *path) { static char buf[PATH_MAX]; - if (!path) return NULL; + if (path == nullptr) { + return nullptr; + } #define DEV_NAME(x) \ - x != NULL &&strlen(x) > 5 && strncmp(x, "/dev/", 5) == 0 ? x + 5 : x - if (realpath(path, buf) == NULL) return DEV_NAME(path); + ((x) != nullptr && strlen(x) > 5 && strncmp(x, "/dev/", 5) == 0 ? (x) + 5 : (x)) + if (realpath(path, buf) == nullptr) { + return DEV_NAME(path); + } return DEV_NAME(buf); #undef DEV_NAME } -static struct text_object *new_text_object_internal(void) { - struct text_object *obj = (text_object *)malloc(sizeof(struct text_object)); +static struct text_object *new_text_object_internal() { + auto *obj = static_cast(malloc(sizeof(struct text_object))); memset(obj, 0, sizeof(struct text_object)); return obj; } @@ -148,8 +152,8 @@ static struct text_object *new_text_object_internal(void) { static struct text_object *create_plain_text(const char *s) { struct text_object *obj; - if (s == NULL || *s == '\0') { - return NULL; + if (s == nullptr || *s == '\0') { + return nullptr; } obj = new_text_object_internal(); @@ -163,7 +167,7 @@ void stock_parse_arg(struct text_object *obj, const char *arg) { char stock[8]; char data[16]; - obj->data.s = NULL; + obj->data.s = nullptr; if (sscanf(arg, "%7s %15s", stock, data) != 2) { NORM_ERR("wrong number of arguments for $stock"); return; @@ -356,10 +360,10 @@ void stock_parse_arg(struct text_object *obj, const char *arg) { #endif /* BUILD_CURL */ legacy_cb_handle *create_cb_handle(int (*fn)()) { - if (fn) + if (fn != nullptr) { return new legacy_cb_handle(conky::register_cb(1, fn)); - else - return NULL; + } + { return nullptr; } } /* construct_text_object() creates a new text_object */ @@ -403,13 +407,13 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, } else #endif /* BUILD_X11 */ #ifndef __OpenBSD__ - OBJ(acpitemp, 0) + OBJ(acpitemp, nullptr) obj->data.i = open_acpi_temperature(arg); obj->callbacks.print = &print_acpitemp; obj->callbacks.free = &free_acpitemp; - END OBJ(acpiacadapter, 0) if (arg) { + END OBJ(acpiacadapter, nullptr) if (arg != nullptr) { #ifdef __linux__ - if (strpbrk(arg, "/.") != NULL) { + if (strpbrk(arg, "/.") != nullptr) { /* * a bit of paranoia. screen out funky paths * i hope no device will have a '.' in its name @@ -424,9 +428,9 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, obj->callbacks.print = &print_acpiacadapter; obj->callbacks.free = &gen_free_opaque; #endif /* !__OpenBSD__ */ - END OBJ(freq, 0) get_cpu_count(); - if (!arg || !isdigit(arg[0]) || strlen(arg) >= 3 || atoi(&arg[0]) == 0 || - atoi(&arg[0]) > info.cpu_count) { + END OBJ(freq, nullptr) get_cpu_count(); + if ((arg == nullptr) || (isdigit(arg[0]) == 0) || strlen(arg) >= 3 || + atoi(&arg[0]) == 0 || atoi(&arg[0]) > info.cpu_count) { obj->data.i = 1; /* NORM_ERR("freq: Invalid CPU number or you don't have that many CPUs! " "Displaying the clock for CPU 1."); */ @@ -434,9 +438,9 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, obj->data.i = atoi(&arg[0]); } obj->callbacks.print = &print_freq; - END OBJ(freq_g, 0) get_cpu_count(); - if (!arg || !isdigit(arg[0]) || strlen(arg) >= 3 || atoi(&arg[0]) == 0 || - atoi(&arg[0]) > info.cpu_count) { + END OBJ(freq_g, nullptr) get_cpu_count(); + if ((arg == nullptr) || (isdigit(arg[0]) == 0) || strlen(arg) >= 3 || + atoi(&arg[0]) == 0 || atoi(&arg[0]) > info.cpu_count) { obj->data.i = 1; /* NORM_ERR("freq_g: Invalid CPU number or you don't have that many " "CPUs! Displaying the clock for CPU 1."); */ @@ -444,15 +448,18 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, obj->data.i = atoi(&arg[0]); } obj->callbacks.print = &print_freq_g; - END OBJ_ARG(read_tcp, 0, "read_tcp: Needs \"(host) port\" as argument(s)") + END OBJ_ARG(read_tcp, nullptr, + "read_tcp: Needs \"(host) port\" as argument(s)") parse_read_tcpip_arg(obj, arg, free_at_crash); obj->callbacks.print = &print_read_tcp; obj->callbacks.free = &free_read_tcpip; - END OBJ_ARG(read_udp, 0, "read_udp: Needs \"(host) port\" as argument(s)") + END OBJ_ARG(read_udp, nullptr, + "read_udp: Needs \"(host) port\" as argument(s)") parse_read_tcpip_arg(obj, arg, free_at_crash); obj->callbacks.print = &print_read_udp; obj->callbacks.free = &free_read_tcpip; - END OBJ_ARG(tcp_ping, 0, "tcp_ping: Needs \"host (port)\" as argument(s)") + END OBJ_ARG(tcp_ping, nullptr, + "tcp_ping: Needs \"host (port)\" as argument(s)") parse_tcp_ping_arg(obj, arg, free_at_crash); obj->callbacks.print = &print_tcp_ping; obj->callbacks.free = &free_tcp_ping; @@ -514,10 +521,10 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, #endif /* __linux__ */ #ifndef __OpenBSD__ - END OBJ(acpifan, 0) obj->callbacks.print = &print_acpifan; - END OBJ(battery, 0) char bat[64]; + END OBJ(acpifan, nullptr) obj->callbacks.print = &print_acpifan; + END OBJ(battery, nullptr) char bat[64]; - if (arg) { + if (arg != nullptr) { sscanf(arg, "%63s", bat); } else { strcpy(bat, "BAT0"); @@ -525,9 +532,9 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, obj->data.s = strndup(bat, text_buffer_size.get(*state)); obj->callbacks.print = &print_battery; obj->callbacks.free = &gen_free_opaque; - END OBJ(battery_short, 0) char bat[64]; + END OBJ(battery_short, nullptr) char bat[64]; - if (arg) { + if (arg != nullptr) { sscanf(arg, "%63s", bat); } else { strcpy(bat, "BAT0"); @@ -535,9 +542,9 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, obj->data.s = strndup(bat, text_buffer_size.get(*state)); obj->callbacks.print = &print_battery_short; obj->callbacks.free = &gen_free_opaque; - END OBJ(battery_time, 0) char bat[64]; + END OBJ(battery_time, nullptr) char bat[64]; - if (arg) { + if (arg != nullptr) { sscanf(arg, "%63s", bat); } else { strcpy(bat, "BAT0"); @@ -545,9 +552,9 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, obj->data.s = strndup(bat, text_buffer_size.get(*state)); obj->callbacks.print = &print_battery_time; obj->callbacks.free = &gen_free_opaque; - END OBJ(battery_percent, 0) char bat[64]; + END OBJ(battery_percent, nullptr) char bat[64]; - if (arg) { + if (arg != nullptr) { sscanf(arg, "%63s", bat); } else { strcpy(bat, "BAT0"); @@ -555,10 +562,10 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, obj->data.s = strndup(bat, text_buffer_size.get(*state)); obj->callbacks.percentage = &battery_percentage; obj->callbacks.free = &gen_free_opaque; - END OBJ(battery_bar, 0) char bat[64]; + END OBJ(battery_bar, nullptr) char bat[64]; arg = scan_bar(obj, arg, 100); - if (arg && strlen(arg) > 0) { + if ((arg != nullptr) && strlen(arg) > 0) { sscanf(arg, "%63s", bat); } else { strcpy(bat, "BAT0"); @@ -633,7 +640,8 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, #endif /* __linux__ */ #if (defined(__FreeBSD__) || defined(__linux__) || defined(__DragonFly__) || \ (defined(__APPLE__) && defined(__MACH__))) - END OBJ_IF_ARG(if_up, 0, "if_up needs an argument") parse_if_up_arg(obj, arg); + END OBJ_IF_ARG(if_up, nullptr, "if_up needs an argument") + parse_if_up_arg(obj, arg); obj->callbacks.iftest = &interface_up; obj->callbacks.free = &free_if_up; #endif @@ -654,13 +662,13 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, #endif /* __OpenBSD__ */ END OBJ(buffers, &update_meminfo) obj->callbacks.print = &print_buffers; END OBJ(cached, &update_meminfo) obj->callbacks.print = &print_cached; -#define SCAN_CPU(__arg, __var) \ - { \ - int __offset = 0; \ - if (__arg && sscanf(__arg, " cpu%d %n", &__var, &__offset) > 0) \ - __arg += __offset; \ - else \ - __var = 0; \ +#define SCAN_CPU(__arg, __var) \ + { \ + int __offset = 0; \ + if ((__arg) && sscanf(__arg, " cpu%d %n", &(__var), &__offset) > 0) \ + (__arg) += __offset; \ + else \ + (__var) = 0; \ } END OBJ(cpu, &update_cpu_usage) get_cpu_count(); SCAN_CPU(arg, obj->data.i); @@ -680,7 +688,7 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, DBGP2("Adding $cpubar for CPU %d", obj->data.i); #ifdef BUILD_X11 END OBJ(cpugraph, &update_cpu_usage) get_cpu_count(); - char *buf = 0; + char *buf = nullptr; SCAN_CPU(arg, obj->data.i); buf = scan_graph(obj, arg, 1); DBGP2("Adding $cpugraph for CPU %d", obj->data.i); @@ -703,17 +711,18 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, END OBJ(diskiograph_write, &update_diskio) parse_diskiograph_arg(obj, arg); obj->callbacks.graphval = &diskiographval_write; #endif /* BUILD_X11 */ - END OBJ(color, 0) + END OBJ(color, nullptr) #ifdef BUILD_X11 if (out_to_x.get(*state)) { - obj->data.l = arg ? get_x11_color(arg) : default_color.get(*state); + obj->data.l = + arg != nullptr ? get_x11_color(arg) : default_color.get(*state); set_current_text_color(obj->data.l); } #endif /* BUILD_X11 */ #ifdef BUILD_NCURSES if (out_to_ncurses.get(*state)) { obj->data.l = COLOR_WHITE; - if (arg) { + if (arg != nullptr) { if (strcasecmp(arg, "red") == 0) { obj->data.l = COLOR_RED; } else if (strcasecmp(arg, "green") == 0) { @@ -736,43 +745,43 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, #endif /* BUILD_NCURSES */ obj->callbacks.print = &new_fg; #ifdef BUILD_X11 - END OBJ(color0, 0) obj->data.l = color[0].get(*state); + END OBJ(color0, nullptr) obj->data.l = color[0].get(*state); set_current_text_color(obj->data.l); obj->callbacks.print = &new_fg; - END OBJ(color1, 0) obj->data.l = color[1].get(*state); + END OBJ(color1, nullptr) obj->data.l = color[1].get(*state); set_current_text_color(obj->data.l); obj->callbacks.print = &new_fg; - END OBJ(color2, 0) obj->data.l = color[2].get(*state); + END OBJ(color2, nullptr) obj->data.l = color[2].get(*state); set_current_text_color(obj->data.l); obj->callbacks.print = &new_fg; - END OBJ(color3, 0) obj->data.l = color[3].get(*state); + END OBJ(color3, nullptr) obj->data.l = color[3].get(*state); set_current_text_color(obj->data.l); obj->callbacks.print = &new_fg; - END OBJ(color4, 0) obj->data.l = color[4].get(*state); + END OBJ(color4, nullptr) obj->data.l = color[4].get(*state); set_current_text_color(obj->data.l); obj->callbacks.print = &new_fg; - END OBJ(color5, 0) obj->data.l = color[5].get(*state); + END OBJ(color5, nullptr) obj->data.l = color[5].get(*state); set_current_text_color(obj->data.l); obj->callbacks.print = &new_fg; - END OBJ(color6, 0) obj->data.l = color[6].get(*state); + END OBJ(color6, nullptr) obj->data.l = color[6].get(*state); set_current_text_color(obj->data.l); obj->callbacks.print = &new_fg; - END OBJ(color7, 0) obj->data.l = color[7].get(*state); + END OBJ(color7, nullptr) obj->data.l = color[7].get(*state); set_current_text_color(obj->data.l); obj->callbacks.print = &new_fg; - END OBJ(color8, 0) obj->data.l = color[8].get(*state); + END OBJ(color8, nullptr) obj->data.l = color[8].get(*state); set_current_text_color(obj->data.l); obj->callbacks.print = &new_fg; - END OBJ(color9, 0) obj->data.l = color[9].get(*state); + END OBJ(color9, nullptr) obj->data.l = color[9].get(*state); set_current_text_color(obj->data.l); obj->callbacks.print = &new_fg; - END OBJ(font, 0) scan_font(obj, arg); + END OBJ(font, nullptr) scan_font(obj, arg); obj->callbacks.print = &new_font; obj->callbacks.free = &gen_free_opaque; #endif /* BUILD_X11 */ - END OBJ(conky_version, 0) obj_be_plain_text(obj, VERSION); - END OBJ(conky_build_date, 0) obj_be_plain_text(obj, BUILD_DATE); - END OBJ(conky_build_arch, 0) obj_be_plain_text(obj, BUILD_ARCH); + END OBJ(conky_version, nullptr) obj_be_plain_text(obj, VERSION); + END OBJ(conky_build_date, nullptr) obj_be_plain_text(obj, BUILD_DATE); + END OBJ(conky_build_arch, nullptr) obj_be_plain_text(obj, BUILD_ARCH); END OBJ(downspeed, &update_net_stats) parse_net_stat_arg(obj, arg, free_at_crash); obj->callbacks.print = &print_downspeed; @@ -784,17 +793,17 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, parse_net_stat_graph_arg(obj, arg, free_at_crash); obj->callbacks.graphval = &downspeedgraphval; #endif /* BUILD_X11 */ - END OBJ(else, 0) obj_be_ifblock_else(ifblock_opaque, obj); + END OBJ(else, nullptr) obj_be_ifblock_else(ifblock_opaque, obj); obj->callbacks.iftest = &gen_false_iftest; - END OBJ(endif, 0) obj_be_ifblock_endif(ifblock_opaque, obj); + END OBJ(endif, nullptr) obj_be_ifblock_endif(ifblock_opaque, obj); obj->callbacks.print = &gen_print_nothing; - END OBJ(eval, 0) obj->data.s = - strndup(arg ? arg : "", text_buffer_size.get(*state)); + END OBJ(eval, nullptr) obj->data.s = + strndup(arg != nullptr ? arg : "", text_buffer_size.get(*state)); obj->callbacks.print = &print_evaluate; obj->callbacks.free = &gen_free_opaque; #if defined(BUILD_IMLIB2) && defined(BUILD_X11) - END OBJ(image, 0) obj->data.s = - strndup(arg ? arg : "", text_buffer_size.get(*state)); + END OBJ(image, nullptr) obj->data.s = + strndup(arg != nullptr ? arg : "", text_buffer_size.get(*state)); obj->callbacks.print = &print_image_callback; obj->callbacks.free = &gen_free_opaque; #endif /* BUILD_IMLIB2 */ @@ -802,71 +811,72 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, END OBJ_ARG(mysql, 0, "mysql needs a query") obj->data.s = strdup(arg); obj->callbacks.print = &print_mysql; #endif /* BUILD_MYSQL */ - END OBJ_ARG(no_update, 0, "no_update needs arguments") + END OBJ_ARG(no_update, nullptr, "no_update needs arguments") scan_no_update(obj, arg); obj->callbacks.print = &print_no_update; obj->callbacks.free = &free_no_update; - END OBJ_ARG(exec, 0, "exec needs arguments: ") + END OBJ_ARG(exec, nullptr, "exec needs arguments: ") scan_exec_arg(obj, arg, EF_EXEC); obj->parse = false; obj->thread = false; register_exec(obj); obj->callbacks.print = &print_exec; obj->callbacks.free = &free_exec; - END OBJ_ARG(execi, 0, "execi needs arguments: ") + END OBJ_ARG(execi, nullptr, "execi needs arguments: ") scan_exec_arg(obj, arg, EF_EXECI); obj->parse = false; obj->thread = false; register_execi(obj); obj->callbacks.print = &print_exec; obj->callbacks.free = &free_execi; - END OBJ_ARG(execp, 0, "execp needs arguments: ") + END OBJ_ARG(execp, nullptr, "execp needs arguments: ") scan_exec_arg(obj, arg, EF_EXEC); obj->parse = true; obj->thread = false; register_exec(obj); obj->callbacks.print = &print_exec; obj->callbacks.free = &free_exec; - END OBJ_ARG(execpi, 0, "execpi needs arguments: ") + END OBJ_ARG(execpi, nullptr, "execpi needs arguments: ") scan_exec_arg(obj, arg, EF_EXECI); obj->parse = true; obj->thread = false; register_execi(obj); obj->callbacks.print = &print_exec; obj->callbacks.free = &free_execi; - END OBJ_ARG(execbar, 0, "execbar needs arguments: [height],[width] ") + END OBJ_ARG(execbar, nullptr, + "execbar needs arguments: [height],[width] ") scan_exec_arg(obj, arg, EF_EXEC | EF_BAR); register_exec(obj); obj->callbacks.barval = &execbarval; obj->callbacks.free = &free_exec; - END OBJ_ARG(execibar, 0, + END OBJ_ARG(execibar, nullptr, "execibar needs arguments: [height],[width] ") scan_exec_arg(obj, arg, EF_EXECI | EF_BAR); register_execi(obj); obj->callbacks.barval = &execbarval; obj->callbacks.free = &free_execi; #ifdef BUILD_X11 - END OBJ_ARG(execgauge, 0, + END OBJ_ARG(execgauge, nullptr, "execgauge needs arguments: [height],[width] ") scan_exec_arg(obj, arg, EF_EXEC | EF_GAUGE); register_exec(obj); obj->callbacks.gaugeval = &execbarval; obj->callbacks.free = &free_exec; END OBJ_ARG( - execigauge, 0, + execigauge, nullptr, "execigauge needs arguments: [height],[width] ") scan_exec_arg(obj, arg, EF_EXECI | EF_GAUGE); register_execi(obj); obj->callbacks.gaugeval = &execbarval; obj->callbacks.free = &free_execi; - END OBJ_ARG(execgraph, 0, + END OBJ_ARG(execgraph, nullptr, "execgraph needs arguments: [height],[width] [color1] " "[color2] [scale] [-t|-l]") scan_exec_arg(obj, arg, EF_EXEC | EF_GRAPH); register_exec(obj); obj->callbacks.graphval = &execbarval; obj->callbacks.free = &free_exec; - END OBJ_ARG(execigraph, 0, + END OBJ_ARG(execigraph, nullptr, "execigraph needs arguments: " "[height],[width] [color1] [color2] [scale] [-t|-l]") scan_exec_arg(obj, arg, EF_EXECI | EF_GRAPH); @@ -874,14 +884,14 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, obj->callbacks.graphval = &execbarval; obj->callbacks.free = &free_execi; #endif /* BUILD_X11 */ - END OBJ_ARG(texeci, 0, "texeci needs arguments: ") + END OBJ_ARG(texeci, nullptr, "texeci needs arguments: ") scan_exec_arg(obj, arg, EF_EXECI); obj->parse = false; obj->thread = true; register_execi(obj); obj->callbacks.print = &print_exec; obj->callbacks.free = &free_execi; - END OBJ_ARG(texecpi, 0, "texecpi needs arguments: ") + END OBJ_ARG(texecpi, nullptr, "texecpi needs arguments: ") scan_exec_arg(obj, arg, EF_EXECI); obj->parse = true; obj->thread = true; @@ -905,20 +915,20 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, END OBJ(fs_used, &update_fs_stats) init_fs(obj, arg); obj->callbacks.print = &print_fs_used; #ifdef BUILD_X11 - END OBJ(hr, 0) obj->data.l = arg ? atoi(arg) : 1; + END OBJ(hr, nullptr) obj->data.l = arg != nullptr ? atoi(arg) : 1; obj->callbacks.print = &new_hr; #endif /* BUILD_X11 */ END OBJ(nameserver, &update_dns_data) parse_nameserver_arg(obj, arg); obj->callbacks.print = &print_nameserver; obj->callbacks.free = &free_dns_data; - END OBJ(offset, 0) obj->data.l = arg ? atoi(arg) : 1; + END OBJ(offset, nullptr) obj->data.l = arg != nullptr ? atoi(arg) : 1; obj->callbacks.print = &new_offset; - END OBJ(voffset, 0) obj->data.l = arg ? atoi(arg) : 1; + END OBJ(voffset, nullptr) obj->data.l = arg != nullptr ? atoi(arg) : 1; obj->callbacks.print = &new_voffset; - END OBJ_ARG(goto, 0, "goto needs arguments") obj->data.l = atoi(arg); + END OBJ_ARG(goto, nullptr, "goto needs arguments") obj->data.l = atoi(arg); obj->callbacks.print = &new_goto; #ifdef BUILD_X11 - END OBJ(tab, 0) scan_tab(obj, arg); + END OBJ(tab, nullptr) scan_tab(obj, arg); obj->callbacks.print = &new_tab; #endif /* BUILD_X11 */ #ifdef __linux__ @@ -940,14 +950,14 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, /* XXX: maybe fiddle them apart later, as print_top() does * nothing else than just that, using an ugly switch(). */ if (strncmp(s, "top", 3) == EQUAL) { - if (parse_top_args(s, arg, obj)) { + if (parse_top_args(s, arg, obj) != 0) { #ifdef __linux__ determine_longstat_file(); #endif obj->cb_handle = create_cb_handle(update_top); } else { free(obj); - return NULL; + return nullptr; } } else OBJ(addr, &update_net_stats) parse_net_stat_arg(obj, arg, free_at_crash); @@ -963,33 +973,33 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, #endif /* BUILD_IPV6 */ END #endif /* __linux__ */ - OBJ_ARG(tail, 0, "tail needs arguments") + OBJ_ARG(tail, nullptr, "tail needs arguments") init_tailhead("tail", arg, obj, free_at_crash); obj->callbacks.print = &print_tail; obj->callbacks.free = &free_tailhead; - END OBJ_ARG(head, 0, "head needs arguments") + END OBJ_ARG(head, nullptr, "head needs arguments") init_tailhead("head", arg, obj, free_at_crash); obj->callbacks.print = &print_head; obj->callbacks.free = &free_tailhead; - END OBJ_ARG(lines, 0, "lines needs an argument") obj->data.s = + END OBJ_ARG(lines, nullptr, "lines needs an argument") obj->data.s = strndup(arg, text_buffer_size.get(*state)); obj->callbacks.print = &print_lines; obj->callbacks.free = &gen_free_opaque; - END OBJ_ARG(words, 0, "words needs a argument") obj->data.s = + END OBJ_ARG(words, nullptr, "words needs a argument") obj->data.s = strndup(arg, text_buffer_size.get(*state)); obj->callbacks.print = &print_words; obj->callbacks.free = &gen_free_opaque; END OBJ(loadavg, &update_load_average) scan_loadavg_arg(obj, arg); obj->callbacks.print = &print_loadavg; - END OBJ_IF_ARG(if_empty, 0, "if_empty needs an argument") obj->sub = - (text_object *)malloc(sizeof(struct text_object)); + END OBJ_IF_ARG(if_empty, nullptr, "if_empty needs an argument") obj->sub = + static_cast(malloc(sizeof(struct text_object))); extract_variable_text_internal(obj->sub, arg); obj->callbacks.iftest = &if_empty_iftest; - END OBJ_IF_ARG(if_match, 0, "if_match needs arguments") obj->sub = - (text_object *)malloc(sizeof(struct text_object)); + END OBJ_IF_ARG(if_match, nullptr, "if_match needs arguments") obj->sub = + static_cast(malloc(sizeof(struct text_object))); extract_variable_text_internal(obj->sub, arg); obj->callbacks.iftest = &check_if_match; - END OBJ_IF_ARG(if_existing, 0, "if_existing needs an argument or two") + END OBJ_IF_ARG(if_existing, nullptr, "if_existing needs an argument or two") obj->data.s = strndup(arg, text_buffer_size.get(*state)); obj->callbacks.iftest = &if_existing_iftest; obj->callbacks.free = &gen_free_opaque; @@ -1004,14 +1014,14 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, obj->callbacks.iftest = &if_running_iftest; obj->callbacks.free = &gen_free_opaque; #elif defined(__APPLE__) && defined(__MACH__) - END OBJ_IF_ARG(if_mounted, 0, "if_mounted needs an argument") obj->data.s = - strndup(arg, text_buffer_size.get(*state)); + END OBJ_IF_ARG(if_mounted, nullptr, "if_mounted needs an argument") + obj->data.s = strndup(arg, text_buffer_size.get(*state)); obj->callbacks.iftest = &check_mount; obj->callbacks.free = &gen_free_opaque; /* System Integrity Protection */ END OBJ(sip_status, &get_sip_status) obj->data.s = - strndup(arg ? arg : "", text_buffer_size.get(*state)); + strndup(arg != nullptr ? arg : "", text_buffer_size.get(*state)); obj->callbacks.print = &print_sip_status; obj->callbacks.free = &gen_free_opaque; #else @@ -1024,48 +1034,48 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, /* XXX: maybe use a different callback here */ obj->callbacks.iftest = &if_running_iftest; #endif - END OBJ(kernel, 0) obj->callbacks.print = &print_kernel; - END OBJ(machine, 0) obj->callbacks.print = &print_machine; + END OBJ(kernel, nullptr) obj->callbacks.print = &print_kernel; + END OBJ(machine, nullptr) obj->callbacks.print = &print_machine; #if defined(__DragonFly__) END OBJ(version, 0) obj->callbacks.print = &print_version; #endif - END OBJ(mails, 0) parse_local_mail_args(obj, arg); + END OBJ(mails, nullptr) parse_local_mail_args(obj, arg); obj->callbacks.print = &print_mails; obj->callbacks.free = &free_local_mails; - END OBJ(new_mails, 0) parse_local_mail_args(obj, arg); + END OBJ(new_mails, nullptr) parse_local_mail_args(obj, arg); obj->callbacks.print = &print_new_mails; obj->callbacks.free = &free_local_mails; - END OBJ(seen_mails, 0) parse_local_mail_args(obj, arg); + END OBJ(seen_mails, nullptr) parse_local_mail_args(obj, arg); obj->callbacks.print = &print_seen_mails; obj->callbacks.free = &free_local_mails; - END OBJ(unseen_mails, 0) parse_local_mail_args(obj, arg); + END OBJ(unseen_mails, nullptr) parse_local_mail_args(obj, arg); obj->callbacks.print = &print_unseen_mails; obj->callbacks.free = &free_local_mails; - END OBJ(flagged_mails, 0) parse_local_mail_args(obj, arg); + END OBJ(flagged_mails, nullptr) parse_local_mail_args(obj, arg); obj->callbacks.print = &print_flagged_mails; obj->callbacks.free = &free_local_mails; - END OBJ(unflagged_mails, 0) parse_local_mail_args(obj, arg); + END OBJ(unflagged_mails, nullptr) parse_local_mail_args(obj, arg); obj->callbacks.print = &print_unflagged_mails; obj->callbacks.free = &free_local_mails; - END OBJ(forwarded_mails, 0) parse_local_mail_args(obj, arg); + END OBJ(forwarded_mails, nullptr) parse_local_mail_args(obj, arg); obj->callbacks.print = &print_forwarded_mails; obj->callbacks.free = &free_local_mails; - END OBJ(unforwarded_mails, 0) parse_local_mail_args(obj, arg); + END OBJ(unforwarded_mails, nullptr) parse_local_mail_args(obj, arg); obj->callbacks.print = &print_unforwarded_mails; obj->callbacks.free = &free_local_mails; - END OBJ(replied_mails, 0) parse_local_mail_args(obj, arg); + END OBJ(replied_mails, nullptr) parse_local_mail_args(obj, arg); obj->callbacks.print = &print_replied_mails; obj->callbacks.free = &free_local_mails; - END OBJ(unreplied_mails, 0) parse_local_mail_args(obj, arg); + END OBJ(unreplied_mails, nullptr) parse_local_mail_args(obj, arg); obj->callbacks.print = &print_unreplied_mails; obj->callbacks.free = &free_local_mails; - END OBJ(draft_mails, 0) parse_local_mail_args(obj, arg); + END OBJ(draft_mails, nullptr) parse_local_mail_args(obj, arg); obj->callbacks.print = &print_draft_mails; obj->callbacks.free = &free_local_mails; - END OBJ(trashed_mails, 0) parse_local_mail_args(obj, arg); + END OBJ(trashed_mails, nullptr) parse_local_mail_args(obj, arg); obj->callbacks.print = &print_trashed_mails; obj->callbacks.free = &free_local_mails; - END OBJ(mboxscan, 0) parse_mboxscan_arg(obj, arg); + END OBJ(mboxscan, nullptr) parse_mboxscan_arg(obj, arg); obj->callbacks.print = &print_mboxscan; obj->callbacks.free = &free_mboxscan; END OBJ(mem, &update_meminfo) obj->callbacks.print = &print_mem; @@ -1088,7 +1098,7 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, END OBJ(memwithbuffersbar, &update_meminfo) scan_bar(obj, arg, 1); obj->callbacks.barval = &mem_with_buffers_barval; #ifdef BUILD_X11 - END OBJ(memgraph, &update_meminfo) char *buf = 0; + END OBJ(memgraph, &update_meminfo) char *buf = nullptr; buf = scan_graph(obj, arg, 1); free_and_zero(buf); @@ -1111,148 +1121,152 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, obj->callbacks.iftest = &check_mixer_muted; #endif #ifdef BUILD_X11 - END OBJ(monitor, 0) obj->callbacks.print = &print_monitor; - END OBJ(monitor_number, 0) obj->callbacks.print = &print_monitor_number; - END OBJ(desktop, 0) obj->callbacks.print = &print_desktop; - END OBJ(desktop_number, 0) obj->callbacks.print = &print_desktop_number; - END OBJ(desktop_name, 0) obj->callbacks.print = &print_desktop_name; + END OBJ(monitor, nullptr) obj->callbacks.print = &print_monitor; + END OBJ(monitor_number, nullptr) obj->callbacks.print = &print_monitor_number; + END OBJ(desktop, nullptr) obj->callbacks.print = &print_desktop; + END OBJ(desktop_number, nullptr) obj->callbacks.print = &print_desktop_number; + END OBJ(desktop_name, nullptr) obj->callbacks.print = &print_desktop_name; #endif /* BUILD_X11 */ - END OBJ_ARG(format_time, 0, "format_time needs a pid as argument") obj->sub = - (text_object *)malloc(sizeof(struct text_object)); + END OBJ_ARG(format_time, nullptr, "format_time needs a pid as argument") + obj->sub = static_cast(malloc(sizeof(struct text_object))); extract_variable_text_internal(obj->sub, arg); obj->callbacks.print = &print_format_time; - END OBJ(nodename, 0) obj->callbacks.print = &print_nodename; - END OBJ(nodename_short, 0) obj->callbacks.print = &print_nodename_short; - END OBJ_ARG(cmdline_to_pid, 0, + END OBJ(nodename, nullptr) obj->callbacks.print = &print_nodename; + END OBJ(nodename_short, nullptr) obj->callbacks.print = &print_nodename_short; + END OBJ_ARG(cmdline_to_pid, nullptr, "cmdline_to_pid needs a command line as argument") scan_cmdline_to_pid_arg(obj, arg, free_at_crash); obj->callbacks.print = &print_cmdline_to_pid; obj->callbacks.free = &gen_free_opaque; - END OBJ_ARG(pid_chroot, 0, "pid_chroot needs a pid as argument") + END OBJ_ARG(pid_chroot, nullptr, "pid_chroot needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_chroot; - END OBJ_ARG(pid_cmdline, 0, "pid_cmdline needs a pid as argument") + END OBJ_ARG(pid_cmdline, nullptr, "pid_cmdline needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_cmdline; - END OBJ_ARG(pid_cwd, 0, "pid_cwd needs a pid as argument") + END OBJ_ARG(pid_cwd, nullptr, "pid_cwd needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_cwd; - END OBJ_ARG(pid_environ, 0, "pid_environ needs arguments") + END OBJ_ARG(pid_environ, nullptr, "pid_environ needs arguments") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_environ; - END OBJ_ARG(pid_environ_list, 0, "pid_environ_list needs a pid as argument") + END OBJ_ARG(pid_environ_list, nullptr, + "pid_environ_list needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_environ_list; - END OBJ_ARG(pid_exe, 0, "pid_exe needs a pid as argument") + END OBJ_ARG(pid_exe, nullptr, "pid_exe needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_exe; - END OBJ_ARG(pid_nice, 0, "pid_nice needs a pid as argument") + END OBJ_ARG(pid_nice, nullptr, "pid_nice needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_nice; - END OBJ_ARG(pid_openfiles, 0, "pid_openfiles needs a pid as argument") + END OBJ_ARG(pid_openfiles, nullptr, "pid_openfiles needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_openfiles; - END OBJ_ARG(pid_parent, 0, "pid_parent needs a pid as argument") + END OBJ_ARG(pid_parent, nullptr, "pid_parent needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_parent; - END OBJ_ARG(pid_priority, 0, "pid_priority needs a pid as argument") + END OBJ_ARG(pid_priority, nullptr, "pid_priority needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_priority; - END OBJ_ARG(pid_state, 0, "pid_state needs a pid as argument") + END OBJ_ARG(pid_state, nullptr, "pid_state needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_state; - END OBJ_ARG(pid_state_short, 0, "pid_state_short needs a pid as argument") + END OBJ_ARG(pid_state_short, nullptr, + "pid_state_short needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_state_short; - END OBJ_ARG(pid_stderr, 0, "pid_stderr needs a pid as argument") + END OBJ_ARG(pid_stderr, nullptr, "pid_stderr needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_stderr; - END OBJ_ARG(pid_stdin, 0, "pid_stdin needs a pid as argument") + END OBJ_ARG(pid_stdin, nullptr, "pid_stdin needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_stdin; - END OBJ_ARG(pid_stdout, 0, "pid_stdout needs a pid as argument") + END OBJ_ARG(pid_stdout, nullptr, "pid_stdout needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_stdout; - END OBJ_ARG(pid_threads, 0, "pid_threads needs a pid as argument") + END OBJ_ARG(pid_threads, nullptr, "pid_threads needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_threads; - END OBJ_ARG(pid_thread_list, 0, "pid_thread_list needs a pid as argument") + END OBJ_ARG(pid_thread_list, nullptr, + "pid_thread_list needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_thread_list; - END OBJ_ARG(pid_time_kernelmode, 0, + END OBJ_ARG(pid_time_kernelmode, nullptr, "pid_time_kernelmode needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_time_kernelmode; - END OBJ_ARG(pid_time_usermode, 0, "pid_time_usermode needs a pid as argument") + END OBJ_ARG(pid_time_usermode, nullptr, + "pid_time_usermode needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_time_usermode; - END OBJ_ARG(pid_time, 0, "pid_time needs a pid as argument") + END OBJ_ARG(pid_time, nullptr, "pid_time needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_time; - END OBJ_ARG(pid_uid, 0, "pid_uid needs a pid as argument") + END OBJ_ARG(pid_uid, nullptr, "pid_uid needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_uid; - END OBJ_ARG(pid_euid, 0, "pid_euid needs a pid as argument") + END OBJ_ARG(pid_euid, nullptr, "pid_euid needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_euid; - END OBJ_ARG(pid_suid, 0, "pid_suid needs a pid as argument") + END OBJ_ARG(pid_suid, nullptr, "pid_suid needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_suid; - END OBJ_ARG(pid_fsuid, 0, "pid_fsuid needs a pid as argument") + END OBJ_ARG(pid_fsuid, nullptr, "pid_fsuid needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_fsuid; - END OBJ_ARG(pid_gid, 0, "pid_gid needs a pid as argument") + END OBJ_ARG(pid_gid, nullptr, "pid_gid needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_gid; - END OBJ_ARG(pid_egid, 0, "pid_egid needs a pid as argument") + END OBJ_ARG(pid_egid, nullptr, "pid_egid needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_egid; - END OBJ_ARG(pid_sgid, 0, "pid_sgid needs a pid as argument") + END OBJ_ARG(pid_sgid, nullptr, "pid_sgid needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_sgid; - END OBJ_ARG(pid_fsgid, 0, "pid_fsgid needs a pid as argument") + END OBJ_ARG(pid_fsgid, nullptr, "pid_fsgid needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_fsgid; - END OBJ_ARG(gid_name, 0, "gid_name needs a gid as argument") + END OBJ_ARG(gid_name, nullptr, "gid_name needs a gid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_gid_name; - END OBJ_ARG(uid_name, 0, "uid_name needs a uid as argument") + END OBJ_ARG(uid_name, nullptr, "uid_name needs a uid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_uid_name; - END OBJ_ARG(pid_read, 0, "pid_read needs a pid as argument") + END OBJ_ARG(pid_read, nullptr, "pid_read needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_read; - END OBJ_ARG(pid_vmpeak, 0, "pid_vmpeak needs a pid as argument") + END OBJ_ARG(pid_vmpeak, nullptr, "pid_vmpeak needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_vmpeak; - END OBJ_ARG(pid_vmsize, 0, "pid_vmsize needs a pid as argument") + END OBJ_ARG(pid_vmsize, nullptr, "pid_vmsize needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_vmsize; - END OBJ_ARG(pid_vmlck, 0, "pid_vmlck needs a pid as argument") + END OBJ_ARG(pid_vmlck, nullptr, "pid_vmlck needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_vmlck; - END OBJ_ARG(pid_vmhwm, 0, "pid_vmhwm needs a pid as argument") + END OBJ_ARG(pid_vmhwm, nullptr, "pid_vmhwm needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_vmhwm; - END OBJ_ARG(pid_vmrss, 0, "pid_vmrss needs a pid as argument") + END OBJ_ARG(pid_vmrss, nullptr, "pid_vmrss needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_vmrss; - END OBJ_ARG(pid_vmdata, 0, "pid_vmdata needs a pid as argument") + END OBJ_ARG(pid_vmdata, nullptr, "pid_vmdata needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_vmdata; - END OBJ_ARG(pid_vmstk, 0, "pid_vmstk needs a pid as argument") + END OBJ_ARG(pid_vmstk, nullptr, "pid_vmstk needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_vmstk; - END OBJ_ARG(pid_vmexe, 0, "pid_vmexe needs a pid as argument") + END OBJ_ARG(pid_vmexe, nullptr, "pid_vmexe needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_vmexe; - END OBJ_ARG(pid_vmlib, 0, "pid_vmlib needs a pid as argument") + END OBJ_ARG(pid_vmlib, nullptr, "pid_vmlib needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_vmlib; - END OBJ_ARG(pid_vmpte, 0, "pid_vmpte needs a pid as argument") + END OBJ_ARG(pid_vmpte, nullptr, "pid_vmpte needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_vmpte; - END OBJ_ARG(pid_write, 0, "pid_write needs a pid as argument") + END OBJ_ARG(pid_write, nullptr, "pid_write needs a pid as argument") extract_object_args_to_sub(obj, arg); obj->callbacks.print = &print_pid_write; #ifdef __DragonFly__ @@ -1283,18 +1297,19 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, &print_running_processes; #endif #endif /* __linux__ */ - END OBJ(shadecolor, 0) -#ifdef BUILD_X11 - obj->data.l = arg ? get_x11_color(arg) : default_shade_color.get(*state); - obj->callbacks.print = &new_bg; -#endif /* BUILD_X11 */ - END OBJ(outlinecolor, 0) + END OBJ(shadecolor, nullptr) #ifdef BUILD_X11 obj->data.l = - arg ? get_x11_color(arg) : default_outline_color.get(*state); + arg != nullptr ? get_x11_color(arg) : default_shade_color.get(*state); + obj->callbacks.print = &new_bg; +#endif /* BUILD_X11 */ + END OBJ(outlinecolor, nullptr) +#ifdef BUILD_X11 + obj->data.l = + arg != nullptr ? get_x11_color(arg) : default_outline_color.get(*state); obj->callbacks.print = &new_outline; #endif /* BUILD_X11 */ - END OBJ(stippled_hr, 0) + END OBJ(stippled_hr, nullptr) #ifdef BUILD_X11 scan_stippled_hr(obj, arg); obj->callbacks.print = &new_stippled_hr; @@ -1307,14 +1322,14 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, END OBJ(swapbar, &update_meminfo) scan_bar(obj, arg, 1); obj->callbacks.barval = &swap_barval; /* XXX: swapgraph, swapgauge? */ - END OBJ(sysname, 0) obj->callbacks.print = &print_sysname; - END OBJ(time, 0) scan_time(obj, arg); + END OBJ(sysname, nullptr) obj->callbacks.print = &print_sysname; + END OBJ(time, nullptr) scan_time(obj, arg); obj->callbacks.print = &print_time; obj->callbacks.free = &free_time; - END OBJ(utime, 0) scan_time(obj, arg); + END OBJ(utime, nullptr) scan_time(obj, arg); obj->callbacks.print = &print_utime; obj->callbacks.free = &free_time; - END OBJ(tztime, 0) scan_tztime(obj, arg); + END OBJ(tztime, nullptr) scan_tztime(obj, arg); obj->callbacks.print = &print_tztime; obj->callbacks.free = &free_tztime; #ifdef BUILD_ICAL @@ -1342,17 +1357,17 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, END OBJ(totalup, &update_net_stats) parse_net_stat_arg(obj, arg, free_at_crash); obj->callbacks.print = &print_totalup; - END OBJ(updates, 0) obj->callbacks.print = &print_updates; - END OBJ_IF(if_updatenr, 0) obj->data.i = arg ? atoi(arg) : 0; + END OBJ(updates, nullptr) obj->callbacks.print = &print_updates; + END OBJ_IF(if_updatenr, nullptr) obj->data.i = arg != nullptr ? atoi(arg) : 0; if (obj->data.i == 0) CRIT_ERR(obj, free_at_crash, "if_updatenr needs a number above 0 as argument"); set_updatereset(obj->data.i > get_updatereset() ? obj->data.i : get_updatereset()); obj->callbacks.iftest = &updatenr_iftest; - END OBJ(alignr, 0) obj->data.l = arg ? atoi(arg) : 1; + END OBJ(alignr, nullptr) obj->data.l = arg != nullptr ? atoi(arg) : 1; obj->callbacks.print = &new_alignr; - END OBJ(alignc, 0) obj->data.l = arg ? atoi(arg) : 0; + END OBJ(alignc, nullptr) obj->data.l = arg != nullptr ? atoi(arg) : 0; obj->callbacks.print = &new_alignc; END OBJ(upspeed, &update_net_stats) parse_net_stat_arg(obj, arg, free_at_crash); @@ -1393,16 +1408,16 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, END OBJ(apm_battery_life, 0) obj->callbacks.print = &print_apm_battery_life; END OBJ(apm_battery_time, 0) obj->callbacks.print = &print_apm_battery_time; #endif /* __FreeBSD__ */ - END OBJ(imap_unseen, 0) parse_imap_mail_args(obj, arg); + END OBJ(imap_unseen, nullptr) parse_imap_mail_args(obj, arg); obj->callbacks.print = &print_imap_unseen; obj->callbacks.free = &free_mail_obj; - END OBJ(imap_messages, 0) parse_imap_mail_args(obj, arg); + END OBJ(imap_messages, nullptr) parse_imap_mail_args(obj, arg); obj->callbacks.print = &print_imap_messages; obj->callbacks.free = &free_mail_obj; - END OBJ(pop3_unseen, 0) parse_pop3_mail_args(obj, arg); + END OBJ(pop3_unseen, nullptr) parse_pop3_mail_args(obj, arg); obj->callbacks.print = &print_pop3_unseen; obj->callbacks.free = &free_mail_obj; - END OBJ(pop3_used, 0) parse_pop3_mail_args(obj, arg); + END OBJ(pop3_used, nullptr) parse_pop3_mail_args(obj, arg); obj->callbacks.print = &print_pop3_used; obj->callbacks.free = &free_mail_obj; #ifdef BUILD_IBM @@ -1445,49 +1460,50 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, else \ NORM_ERR(#name ": invalid length argument"); \ } - END OBJ(mpd_artist, 0) mpd_set_maxlen(mpd_artist); + END OBJ(mpd_artist, nullptr) mpd_set_maxlen(mpd_artist); obj->callbacks.print = &print_mpd_artist; - END OBJ(mpd_albumartist, 0) mpd_set_maxlen(mpd_albumartist); + END OBJ(mpd_albumartist, nullptr) mpd_set_maxlen(mpd_albumartist); obj->callbacks.print = &print_mpd_albumartist; - END OBJ(mpd_title, 0) mpd_set_maxlen(mpd_title); + END OBJ(mpd_title, nullptr) mpd_set_maxlen(mpd_title); obj->callbacks.print = &print_mpd_title; - END OBJ(mpd_date, 0) mpd_set_maxlen(mpd_date); + END OBJ(mpd_date, nullptr) mpd_set_maxlen(mpd_date); obj->callbacks.print = &print_mpd_date; - END OBJ(mpd_random, 0) obj->callbacks.print = &print_mpd_random; - END OBJ(mpd_repeat, 0) obj->callbacks.print = &print_mpd_repeat; - END OBJ(mpd_elapsed, 0) obj->callbacks.print = &print_mpd_elapsed; - END OBJ(mpd_length, 0) obj->callbacks.print = &print_mpd_length; - END OBJ(mpd_track, 0) mpd_set_maxlen(mpd_track); + END OBJ(mpd_random, nullptr) obj->callbacks.print = &print_mpd_random; + END OBJ(mpd_repeat, nullptr) obj->callbacks.print = &print_mpd_repeat; + END OBJ(mpd_elapsed, nullptr) obj->callbacks.print = &print_mpd_elapsed; + END OBJ(mpd_length, nullptr) obj->callbacks.print = &print_mpd_length; + END OBJ(mpd_track, nullptr) mpd_set_maxlen(mpd_track); obj->callbacks.print = &print_mpd_track; - END OBJ(mpd_name, 0) mpd_set_maxlen(mpd_name); + END OBJ(mpd_name, nullptr) mpd_set_maxlen(mpd_name); obj->callbacks.print = &print_mpd_name; - END OBJ(mpd_file, 0) mpd_set_maxlen(mpd_file); + END OBJ(mpd_file, nullptr) mpd_set_maxlen(mpd_file); obj->callbacks.print = &print_mpd_file; - END OBJ(mpd_percent, 0) obj->callbacks.percentage = &mpd_percentage; - END OBJ(mpd_album, 0) mpd_set_maxlen(mpd_album); + END OBJ(mpd_percent, nullptr) obj->callbacks.percentage = &mpd_percentage; + END OBJ(mpd_album, nullptr) mpd_set_maxlen(mpd_album); obj->callbacks.print = &print_mpd_album; - END OBJ(mpd_vol, 0) obj->callbacks.print = &print_mpd_vol; - END OBJ(mpd_bitrate, 0) obj->callbacks.print = &print_mpd_bitrate; - END OBJ(mpd_status, 0) obj->callbacks.print = &print_mpd_status; - END OBJ(mpd_bar, 0) scan_bar(obj, arg, 1); + END OBJ(mpd_vol, nullptr) obj->callbacks.print = &print_mpd_vol; + END OBJ(mpd_bitrate, nullptr) obj->callbacks.print = &print_mpd_bitrate; + END OBJ(mpd_status, nullptr) obj->callbacks.print = &print_mpd_status; + END OBJ(mpd_bar, nullptr) scan_bar(obj, arg, 1); obj->callbacks.barval = &mpd_barval; - END OBJ(mpd_smart, 0) mpd_set_maxlen(mpd_smart); + END OBJ(mpd_smart, nullptr) mpd_set_maxlen(mpd_smart); obj->callbacks.print = &print_mpd_smart; - END OBJ_IF(if_mpd_playing, 0) obj->callbacks.iftest = &check_mpd_playing; + END OBJ_IF(if_mpd_playing, nullptr) obj->callbacks.iftest = + &check_mpd_playing; #undef mpd_set_maxlen #endif /* BUILD_MPD */ #ifdef BUILD_MOC - END OBJ(moc_state, 0) obj->callbacks.print = &print_moc_state; - END OBJ(moc_file, 0) obj->callbacks.print = &print_moc_file; - END OBJ(moc_title, 0) obj->callbacks.print = &print_moc_title; - END OBJ(moc_artist, 0) obj->callbacks.print = &print_moc_artist; - END OBJ(moc_song, 0) obj->callbacks.print = &print_moc_song; - END OBJ(moc_album, 0) obj->callbacks.print = &print_moc_album; - END OBJ(moc_totaltime, 0) obj->callbacks.print = &print_moc_totaltime; - END OBJ(moc_timeleft, 0) obj->callbacks.print = &print_moc_timeleft; - END OBJ(moc_curtime, 0) obj->callbacks.print = &print_moc_curtime; - END OBJ(moc_bitrate, 0) obj->callbacks.print = &print_moc_bitrate; - END OBJ(moc_rate, 0) obj->callbacks.print = &print_moc_rate; + END OBJ(moc_state, nullptr) obj->callbacks.print = &print_moc_state; + END OBJ(moc_file, nullptr) obj->callbacks.print = &print_moc_file; + END OBJ(moc_title, nullptr) obj->callbacks.print = &print_moc_title; + END OBJ(moc_artist, nullptr) obj->callbacks.print = &print_moc_artist; + END OBJ(moc_song, nullptr) obj->callbacks.print = &print_moc_song; + END OBJ(moc_album, nullptr) obj->callbacks.print = &print_moc_album; + END OBJ(moc_totaltime, nullptr) obj->callbacks.print = &print_moc_totaltime; + END OBJ(moc_timeleft, nullptr) obj->callbacks.print = &print_moc_timeleft; + END OBJ(moc_curtime, nullptr) obj->callbacks.print = &print_moc_curtime; + END OBJ(moc_bitrate, nullptr) obj->callbacks.print = &print_moc_bitrate; + END OBJ(moc_rate, nullptr) obj->callbacks.print = &print_moc_rate; #endif /* BUILD_MOC */ #ifdef BUILD_CMUS END OBJ(cmus_state, 0) obj->callbacks.print = &print_cmus_state; @@ -1647,21 +1663,21 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, obj->callbacks.print = &print_weather_forecast; obj->callbacks.free = &free_weather; #endif /* BUILD_WEATHER_XOAP */ - END OBJ_ARG(lua, 0, + END OBJ_ARG(lua, nullptr, "lua needs arguments: [function parameters]") obj->data.s = strndup(arg, text_buffer_size.get(*state)); obj->callbacks.print = &print_lua; obj->callbacks.free = &gen_free_opaque; END OBJ_ARG( - lua_parse, 0, + lua_parse, nullptr, "lua_parse needs arguments: [function parameters]") obj->data.s = strndup(arg, text_buffer_size.get(*state)); obj->callbacks.print = &print_lua_parse; obj->callbacks.free = &gen_free_opaque; - END OBJ_ARG(lua_bar, 0, + END OBJ_ARG(lua_bar, nullptr, "lua_bar needs arguments: , " "[function parameters]") arg = scan_bar(obj, arg, 100); - if (arg) { + if (arg != nullptr) { obj->data.s = strndup(arg, text_buffer_size.get(*state)); } else { CRIT_ERR(obj, free_at_crash, @@ -1672,11 +1688,11 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, obj->callbacks.free = &gen_free_opaque; #ifdef BUILD_X11 END OBJ_ARG( - lua_graph, 0, + lua_graph, nullptr, "lua_graph needs arguments: [height],[width] [gradient " - "colour 1] [gradient colour 2] [scale] [-t] [-l]") char *buf = 0; + "colour 1] [gradient colour 2] [scale] [-t] [-l]") char *buf = nullptr; buf = scan_graph(obj, arg, 100); - if (buf) { + if (buf != nullptr) { obj->data.s = buf; } else { CRIT_ERR(obj, free_at_crash, @@ -1685,10 +1701,10 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, } obj->callbacks.graphval = &lua_barval; obj->callbacks.free = &gen_free_opaque; - END OBJ_ARG(lua_gauge, 0, + END OBJ_ARG(lua_gauge, nullptr, "lua_gauge needs arguments: , " "[function parameters]") arg = scan_gauge(obj, arg, 100); - if (arg) { + if (arg != nullptr) { obj->data.s = strndup(arg, text_buffer_size.get(*state)); } else { CRIT_ERR(obj, free_at_crash, @@ -1718,12 +1734,12 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, &print_entropy_poolsize; END OBJ(entropy_bar, &update_entropy) scan_bar(obj, arg, 1); obj->callbacks.barval = &entropy_barval; - END OBJ_ARG(blink, 0, "blink needs a argument") obj->sub = - (text_object *)malloc(sizeof(struct text_object)); + END OBJ_ARG(blink, nullptr, "blink needs a argument") obj->sub = + static_cast(malloc(sizeof(struct text_object))); extract_variable_text_internal(obj->sub, arg); obj->callbacks.print = &print_blink; - END OBJ_ARG(to_bytes, 0, "to_bytes needs a argument") obj->sub = - (text_object *)malloc(sizeof(struct text_object)); + END OBJ_ARG(to_bytes, nullptr, "to_bytes needs a argument") obj->sub = + static_cast(malloc(sizeof(struct text_object))); extract_variable_text_internal(obj->sub, arg); obj->callbacks.print = &print_to_bytes; #ifdef BUILD_CURL @@ -1731,14 +1747,14 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, obj->callbacks.print = &print_stock; obj->callbacks.free = &free_stock; #endif /* BUILD_CURL */ - END OBJ(scroll, 0) + END OBJ(scroll, nullptr) #ifdef BUILD_X11 /* allocate a follower to reset any color changes */ #endif /* BUILD_X11 */ parse_scroll_arg(obj, arg, free_at_crash, s); obj->callbacks.print = &print_scroll; obj->callbacks.free = &free_scroll; - END OBJ(combine, 0) try { + END OBJ(combine, nullptr) try { parse_combine_arg(obj, arg); } catch (combine_needs_2_args_error &e) { free(obj); @@ -1791,7 +1807,8 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, #ifdef BUILD_APCUPSD END OBJ_ARG( apcupsd, &update_apcupsd, - "apcupsd needs arguments: ") if (apcupsd_scan_arg(arg)) { + "apcupsd needs arguments: ") if (apcupsd_scan_arg(arg) != + 0) { CRIT_ERR(obj, free_at_crash, "apcupsd needs arguments: "); } obj->callbacks.print = &gen_print_nothing; @@ -1812,7 +1829,7 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, END OBJ(apcupsd_loadbar, &update_apcupsd) scan_bar(obj, arg, 100); obj->callbacks.barval = &apcupsd_loadbarval; #ifdef BUILD_X11 - END OBJ(apcupsd_loadgraph, &update_apcupsd) char *buf = 0; + END OBJ(apcupsd_loadgraph, &update_apcupsd) char *buf = nullptr; buf = scan_graph(obj, arg, 100); free_and_zero(buf); obj->callbacks.graphval = &apcupsd_loadbarval; @@ -1866,7 +1883,7 @@ struct text_object *construct_text_object(char *s, const char *arg, long line, init_pulseaudio(obj); #endif /* BUILD_PULSEAUDIO */ END { - char *buf = (char *)malloc(text_buffer_size.get(*state)); + auto *buf = static_cast(malloc(text_buffer_size.get(*state))); NORM_ERR("unknown variable '$%s'", s); snprintf(buf, text_buffer_size.get(*state), "${%s}", s); @@ -1897,8 +1914,12 @@ static size_t remove_comment(char *string, char *last) { while (*end != '\0' && *end != '\n') { ++end; } - if (last) *last = *end; - if (*end == '\n') end++; + if (last != nullptr) { + *last = *end; + } + if (*end == '\n') { + end++; + } strfold(string, end - string); return end - string; } @@ -1912,7 +1933,7 @@ size_t remove_comments(char *string) { strfold(curplace, 1); folded += 1; } else if (*curplace == '#') { - folded += remove_comment(curplace, 0); + folded += remove_comment(curplace, nullptr); } } return folded; @@ -1923,13 +1944,13 @@ int extract_variable_text_internal(struct text_object *retval, struct text_object *obj; char *p, *s, *orig_p; long line; - void *ifblock_opaque = NULL; + void *ifblock_opaque = nullptr; char *tmp_p; - char *arg = 0; + char *arg = nullptr; size_t len = 0; p = strndup(const_p, max_user_text.get(*state) - 1); - while (text_contains_templates(p)) { + while (text_contains_templates(p) != 0) { char *tmp; tmp = find_and_replace_templates(p); free(p); @@ -1937,7 +1958,7 @@ int extract_variable_text_internal(struct text_object *retval, } s = orig_p = p; - if (strcmp(p, const_p)) { + if (static_cast(strcmp(p, const_p) != 0) != 0) { DBGP2("replaced all templates in text: input is\n'%s'\noutput is\n'%s'", const_p, p); } else { @@ -1948,14 +1969,14 @@ int extract_variable_text_internal(struct text_object *retval, line = global_text_lines; - while (*p) { + while (*p != 0) { if (*p == '\n') { line++; } if (*p == '$') { *p = '\0'; obj = create_plain_text(s); - if (obj != NULL) { + if (obj != nullptr) { append_object(retval, obj); } *p = '$'; @@ -1963,7 +1984,7 @@ int extract_variable_text_internal(struct text_object *retval, s = p; if (*p != '$') { - char *buf = (char *)malloc(text_buffer_size.get(*state)); + auto *buf = static_cast(malloc(text_buffer_size.get(*state))); const char *var; /* variable is either $foo or ${foo} */ @@ -1972,7 +1993,7 @@ int extract_variable_text_internal(struct text_object *retval, p++; s = p; - while (*p && brl != brr) { + while ((*p != 0) && brl != brr) { if (*p == '{') { brl++; } @@ -1987,14 +2008,15 @@ int extract_variable_text_internal(struct text_object *retval, if (*p == '#') { p++; } - while (*p && (isalnum((int)*p) || *p == '_')) { + while ((*p != 0) && + ((isalnum(static_cast(*p)) != 0) || *p == '_')) { p++; } } /* copy variable to buffer */ - len = (p - s > (int)text_buffer_size.get(*state) - 1) - ? (int)text_buffer_size.get(*state) - 1 + len = (p - s > static_cast(text_buffer_size.get(*state)) - 1) + ? static_cast(text_buffer_size.get(*state)) - 1 : (p - s); strncpy(buf, s, len); buf[len] = '\0'; @@ -2007,9 +2029,9 @@ int extract_variable_text_internal(struct text_object *retval, /* search for variable in environment */ var = getenv(buf); - if (var) { + if (var != nullptr) { obj = create_plain_text(var); - if (obj) { + if (obj != nullptr) { append_object(retval, obj); } free(buf); @@ -2018,24 +2040,24 @@ int extract_variable_text_internal(struct text_object *retval, /* if variable wasn't found in environment, use some special */ - arg = 0; + arg = nullptr; /* split arg */ - if (strchr(buf, ' ')) { + if (strchr(buf, ' ') != nullptr) { arg = strchr(buf, ' '); *arg = '\0'; arg++; - while (isspace((int)*arg)) { + while (isspace(static_cast(*arg)) != 0) { arg++; } - if (!*arg) { - arg = 0; + if (*arg == 0) { + arg = nullptr; } } /* lowercase variable name */ tmp_p = buf; - while (*tmp_p) { + while (*tmp_p != 0) { *tmp_p = tolower(*tmp_p); tmp_p++; } @@ -2047,23 +2069,23 @@ int extract_variable_text_internal(struct text_object *retval, free(orig_p); throw e; } - if (obj != NULL) { + if (obj != nullptr) { append_object(retval, obj); } free(buf); continue; - } else { + } obj = create_plain_text("$"); s = p + 1; - if (obj != NULL) { + if (obj != nullptr) { append_object(retval, obj); } - } + } else if (*p == '\\' && *(p + 1) == '#') { strfold(p, 1); } else if (*p == '#') { char c; - if (remove_comment(p, &c) && p >= orig_p && c == '\n') { + if ((remove_comment(p, &c) != 0u) && p >= orig_p && c == '\n') { /* if remove_comment removed a newline, we need to 'back up' with p */ p--; } @@ -2071,11 +2093,11 @@ int extract_variable_text_internal(struct text_object *retval, p++; } obj = create_plain_text(s); - if (obj != NULL) { + if (obj != nullptr) { append_object(retval, obj); } - if (!ifblock_stack_empty(&ifblock_opaque)) { + if (ifblock_stack_empty(&ifblock_opaque) == 0) { NORM_ERR("one or more $endif's are missing"); } @@ -2084,7 +2106,8 @@ int extract_variable_text_internal(struct text_object *retval, } void extract_object_args_to_sub(struct text_object *obj, const char *args) { - obj->sub = (struct text_object *)malloc(sizeof(struct text_object)); + obj->sub = + static_cast(malloc(sizeof(struct text_object))); memset(obj->sub, 0, sizeof(struct text_object)); extract_variable_text_internal(obj->sub, args); } @@ -2093,10 +2116,10 @@ void extract_object_args_to_sub(struct text_object *obj, const char *args) { void free_text_objects(struct text_object *root) { struct text_object *obj; - if (root && root->prev) { - for (obj = root->prev; obj; obj = root->prev) { + if ((root != nullptr) && (root->prev != nullptr)) { + for (obj = root->prev; obj != nullptr; obj = root->prev) { root->prev = obj->prev; - if (obj->callbacks.free) { + if (obj->callbacks.free != nullptr) { (*obj->callbacks.free)(obj); } free_text_objects(obj->sub); diff --git a/src/darwin.cc b/src/darwin.cc index b4f66c4b..678d3e49 100644 --- a/src/darwin.cc +++ b/src/darwin.cc @@ -53,7 +53,7 @@ #include -#include +#include #include // statfs #include @@ -65,12 +65,12 @@ #include // update_total_processes +#include "top.h" // get_top_info #include // get_top_info #include // get_top_info -#include "top.h" // get_top_info -#include // update_net_stats #include "net_stat.h" // update_net_stats +#include // update_net_stats #include "darwin_sip.h" // sip status @@ -88,7 +88,7 @@ /* (E)nhanced printf */ #ifdef DEBUG_MODE -#include +#include void eprintf(const char *fmt, ...) { va_list args; va_start(args, fmt); @@ -110,7 +110,7 @@ static conky::simple_config_setting 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(&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(&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(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(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(&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( + 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(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(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(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(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(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(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(used - cpu[0].oldused)) / + static_cast(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(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(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"); diff --git a/src/darwin.h b/src/darwin.h index 83def954..55491228 100644 --- a/src/darwin.h +++ b/src/darwin.h @@ -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); diff --git a/src/data-source.cc b/src/data-source.cc index aff56f02..461fcb07 100644 --- a/src/data-source.cc +++ b/src/data-source.cc @@ -49,11 +49,14 @@ typedef std::unordered_map 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(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"); diff --git a/src/diskio.cc b/src/diskio.cc index b511a309..19d9e483 100644 --- a/src/diskio.cc +++ b/src/diskio.cc @@ -28,8 +28,8 @@ */ #include "diskio.h" -#include #include +#include #include #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 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(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(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(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(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(samples); + ds->current_read = sum_r / static_cast(samples); + ds->current_write = sum_w / static_cast(samples); /* shift sample history */ for (i = samples - 1; i > 0; i--) { diff --git a/src/dragonfly.cc b/src/dragonfly.cc index e3c5aca0..689ceb34 100644 --- a/src/dragonfly.cc +++ b/src/dragonfly.cc @@ -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; diff --git a/src/entropy.cc b/src/entropy.cc index 0b412cd2..9884b262 100644 --- a/src/entropy.cc +++ b/src/entropy.cc @@ -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(entropy.avail) * 100.0 / + static_cast(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(entropy.avail) / entropy.poolsize; } diff --git a/src/eve.cc b/src/eve.cc index 657e1247..a7fbb080 100644 --- a/src/eve.cc +++ b/src/eve.cc @@ -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; diff --git a/src/exec.cc b/src/exec.cc index df29c180..3eeb13b3 100644 --- a/src/exec.cc +++ b/src/exec.cc @@ -28,11 +28,12 @@ */ #include "exec.h" -#include +#include #include #include #include #include +#include #include #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 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 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* 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( conky::register_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(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( @@ -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(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; } diff --git a/src/fonts.cc b/src/fonts.cc index 8e2c0881..4a00ab1f 100644 --- a/src/fonts.cc +++ b/src/fonts.cc @@ -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 { - typedef conky::simple_config_setting Base; + using Base = conky::simple_config_setting; 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"); } } } diff --git a/src/fonts.h b/src/fonts.h index 92e5fbab..f9e5c465 100644 --- a/src/fonts.h +++ b/src/fonts.h @@ -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 { diff --git a/src/freebsd.cc b/src/freebsd.cc index cac80615..84283e68 100644 --- a/src/freebsd.cc +++ b/src/freebsd.cc @@ -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; diff --git a/src/fs.cc b/src/fs.cc index a79363c9..8d053626 100644 --- a/src/fs.cc +++ b/src/fs.cc @@ -28,11 +28,11 @@ */ #include "fs.h" -#include -#include #include #include #include +#include +#include #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(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(s.f_bavail) * s.f_bsize; + fs->free = static_cast(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(obj->data.opaque); + auto *fs = static_cast(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(obj->data.opaque); - if (fs) snprintf(p, p_max_size, "%s", fs->type); + if (fs != nullptr) { + snprintf(p, p_max_size, "%s", fs->type); + } } diff --git a/src/fs.h b/src/fs.h index eb5e5cdc..5c01ef4c 100644 --- a/src/fs.h +++ b/src/fs.h @@ -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 */ diff --git a/src/haiku.cc b/src/haiku.cc index 9db49c5e..2049211c 100644 --- a/src/haiku.cc +++ b/src/haiku.cc @@ -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 diff --git a/src/hddtemp.cc b/src/hddtemp.cc index 21d8c408..1913831b 100644 --- a/src/hddtemp.cc +++ b/src/hddtemp.cc @@ -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; } diff --git a/src/i8k.cc b/src/i8k.cc index 257a936a..38fa3b9d 100644 --- a/src/i8k.cc +++ b/src/i8k.cc @@ -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; } diff --git a/src/ibm.cc b/src/ibm.cc index 8464bc09..fafc6610 100644 --- a/src/ibm.cc +++ b/src/ibm.cc @@ -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)); diff --git a/src/ical.cc b/src/ical.cc index 3cdeaf6f..bad24a04 100644 --- a/src/ical.cc +++ b/src/ical.cc @@ -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); diff --git a/src/iconv_tools.cc b/src/iconv_tools.cc index e1b263bb..bdfa7786 100644 --- a/src/iconv_tools.cc +++ b/src/iconv_tools.cc @@ -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); diff --git a/src/imlib2.cc b/src/imlib2.cc index 01ad9793..bd2773a6 100644 --- a/src/imlib2.cc +++ b/src/imlib2.cc @@ -28,11 +28,11 @@ #include "text_object.h" #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #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(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: ' (-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); diff --git a/src/imlib2.h b/src/imlib2.h index e4f1b67d..4e538d78 100644 --- a/src/imlib2.h +++ b/src/imlib2.h @@ -28,7 +28,7 @@ #include -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); diff --git a/src/irc.cc b/src/irc.cc index ac7d6694..132e5f18 100644 --- a/src/irc.cc +++ b/src/irc.cc @@ -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); diff --git a/src/journal.cc b/src/journal.cc index 24f6726d..d26e0e7a 100644 --- a/src/journal.cc +++ b/src/journal.cc @@ -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; diff --git a/src/libmpdclient.cc b/src/libmpdclient.cc index 84300aea..ee4f94b4 100644 --- a/src/libmpdclient.cc +++ b/src/libmpdclient.cc @@ -36,10 +36,10 @@ #include "libmpdclient.h" #include "conky.h" -#include -#include +#include +#include +#include #include -#include #include #include #include @@ -59,6 +59,10 @@ #define SUN_LEN(a) sizeof(a) #endif +#ifndef SOCK_CLOEXEC +# define SOCK_CLOEXEC O_CLOEXEC +#endif /* SOCK_CLOEXEC */ + /* (bits + 1) / 3 (plus the sign character) */ #define INTLEN ((sizeof(int) * CHAR_BIT + 1) / 3 + 1) #define LONGLONGLEN ((sizeof(long long) * CHAR_BIT + 1) / 3 + 1) @@ -116,19 +120,19 @@ static int do_connect_fail(mpd_Connection *connection, int flags = fcntl(connection->sock, F_GETFL, 0); fcntl(connection->sock, F_SETFL, flags | O_NONBLOCK); - return (connect(connection->sock, serv_addr, addrlen) < 0 && - errno != EINPROGRESS); + return static_cast(connect(connection->sock, serv_addr, addrlen) < 0 && + errno != EINPROGRESS); } #endif /* !WIN32 */ static int uds_connect(mpd_Connection *connection, const char *host, float timeout) { - struct sockaddr_un addr; + struct sockaddr_un addr {}; strncpy(addr.sun_path, host, sizeof(addr.sun_path) - 1); addr.sun_family = AF_UNIX; addr.sun_path[sizeof(addr.sun_path) - 1] = 0; - connection->sock = socket(AF_UNIX, SOCK_STREAM, 0); + connection->sock = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); if (connection->sock < 0) { snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH, @@ -140,7 +144,8 @@ static int uds_connect(mpd_Connection *connection, const char *host, mpd_setConnectionTimeout(connection, timeout); /* connect stuff */ - if (do_connect_fail(connection, (struct sockaddr *)&addr, SUN_LEN(&addr))) { + if (do_connect_fail(connection, reinterpret_cast(&addr), + SUN_LEN(&addr)) != 0) { snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH, "problems connecting socket: %s", strerror(errno)); closesocket(connection->sock); @@ -157,11 +162,13 @@ static int mpd_connect(mpd_Connection *connection, const char *host, int port, float timeout) { int error; char service[INTLEN + 1]; - struct addrinfo hints; - struct addrinfo *res = NULL; - struct addrinfo *addrinfo = NULL; + struct addrinfo hints {}; + struct addrinfo *res = nullptr; + struct addrinfo *addrinfo = nullptr; - if (*host == '/') return uds_connect(connection, host, timeout); + if (*host == '/') { + return uds_connect(connection, host, timeout); + } /* Setup hints */ hints.ai_flags = AI_ADDRCONFIG; @@ -169,27 +176,28 @@ static int mpd_connect(mpd_Connection *connection, const char *host, int port, hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_addrlen = 0; - hints.ai_addr = NULL; - hints.ai_canonname = NULL; - hints.ai_next = NULL; + hints.ai_addr = nullptr; + hints.ai_canonname = nullptr; + hints.ai_next = nullptr; snprintf(service, sizeof(service), "%i", port); error = getaddrinfo(host, service, &hints, &addrinfo); - if (error) { + if (error != 0) { snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH, "host \"%s\" not found: %s", host, gai_strerror(error)); connection->error = MPD_ERROR_UNKHOST; return -1; } - for (res = addrinfo; res; res = res->ai_next) { + for (res = addrinfo; res != nullptr; res = res->ai_next) { /* create socket */ if (connection->sock > -1) { closesocket(connection->sock); } - connection->sock = socket(res->ai_family, SOCK_STREAM, res->ai_protocol); + connection->sock = + socket(res->ai_family, SOCK_STREAM | SOCK_CLOEXEC, res->ai_protocol); if (connection->sock < 0) { snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH, "problems creating socket: %s", strerror(errno)); @@ -201,7 +209,7 @@ static int mpd_connect(mpd_Connection *connection, const char *host, int port, mpd_setConnectionTimeout(connection, timeout); /* connect stuff */ - if (do_connect_fail(connection, res->ai_addr, res->ai_addrlen)) { + if (do_connect_fail(connection, res->ai_addr, res->ai_addrlen) != 0) { /* try the next address family */ closesocket(connection->sock); connection->sock = -1; @@ -300,12 +308,12 @@ const char *mpdTagItemKeys[MPD_TAG_NUM_OF_ITEM_TYPES] = { static char *mpd_sanitizeArg(const char *arg) { size_t i; char *ret; - register const char *c; - register char *rc; + const char *c; + char *rc; /* instead of counting in that loop above, * just use a bit more memory and halve running time */ - ret = (char *)malloc(strlen(arg) * 2 + 1); + ret = static_cast(malloc(strlen(arg) * 2 + 1)); c = arg; rc = ret; @@ -321,8 +329,8 @@ static char *mpd_sanitizeArg(const char *arg) { static mpd_ReturnElement *mpd_newReturnElement(const char *name, const char *value) { - mpd_ReturnElement *ret = - (mpd_ReturnElement *)malloc(sizeof(mpd_ReturnElement)); + auto *ret = + static_cast(malloc(sizeof(mpd_ReturnElement))); ret->name = strndup(name, text_buffer_size.get(*state)); ret->value = strndup(value, text_buffer_size.get(*state)); @@ -337,9 +345,9 @@ static void mpd_freeReturnElement(mpd_ReturnElement *re) { } void mpd_setConnectionTimeout(mpd_Connection *connection, float timeout) { - connection->timeout.tv_sec = (int)timeout; + connection->timeout.tv_sec = static_cast(timeout); connection->timeout.tv_usec = - (int)((timeout - connection->timeout.tv_sec) * 1e6 + 0.5); + static_cast((timeout - connection->timeout.tv_sec) * 1e6 + 0.5); } static int mpd_parseWelcome(mpd_Connection *connection, const char *host, @@ -348,7 +356,8 @@ static int mpd_parseWelcome(mpd_Connection *connection, const char *host, char *test; int i; - if (strncmp(output, MPD_WELCOME_MESSAGE, strlen(MPD_WELCOME_MESSAGE))) { + if (static_cast(strncmp(output, MPD_WELCOME_MESSAGE, + strlen(MPD_WELCOME_MESSAGE)) != 0) != 0) { snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH, "mpd not running on port %i on host \"%s\"", port, host); connection->error = MPD_ERROR_NOTMPD; @@ -358,11 +367,11 @@ static int mpd_parseWelcome(mpd_Connection *connection, const char *host, tmp = &output[strlen(MPD_WELCOME_MESSAGE)]; for (i = 0; i < 3; i++) { - if (tmp) { + if (tmp != nullptr) { connection->version[i] = strtol(tmp, &test, 10); } - if (!tmp || (test[0] != '.' && test[0] != '\0')) { + if ((tmp == nullptr) || (test[0] != '.' && test[0] != '\0')) { snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH, "error parsing version number at \"%s\"", &output[strlen(MPD_WELCOME_MESSAGE)]); @@ -378,9 +387,10 @@ static int mpd_parseWelcome(mpd_Connection *connection, const char *host, mpd_Connection *mpd_newConnection(const char *host, int port, float timeout) { int err; char *rt; - char *output = NULL; - mpd_Connection *connection = (mpd_Connection *)malloc(sizeof(mpd_Connection)); - struct timeval tv; + char *output = nullptr; + auto *connection = + static_cast(malloc(sizeof(mpd_Connection))); + struct timeval tv {}; fd_set fds; strcpy(connection->buffer, ""); @@ -393,8 +403,8 @@ mpd_Connection *mpd_newConnection(const char *host, int port, float timeout) { connection->listOks = 0; connection->doneListOk = 0; connection->sock = -1; - connection->returnElement = NULL; - connection->request = NULL; + connection->returnElement = nullptr; + connection->request = nullptr; if (winsock_dll_error(connection)) { return connection; @@ -404,12 +414,13 @@ mpd_Connection *mpd_newConnection(const char *host, int port, float timeout) { return connection; } - while (!(rt = strstr(connection->buffer, "\n"))) { + while ((rt = strstr(connection->buffer, "\n")) == nullptr) { tv.tv_sec = connection->timeout.tv_sec; tv.tv_usec = connection->timeout.tv_usec; FD_ZERO(&fds); FD_SET(connection->sock, &fds); - if ((err = select(connection->sock + 1, &fds, NULL, NULL, &tv)) == 1) { + if ((err = select(connection->sock + 1, &fds, nullptr, nullptr, &tv)) == + 1) { int readed; readed = recv(connection->sock, &(connection->buffer[connection->buflen]), @@ -461,7 +472,7 @@ void mpd_clearError(mpd_Connection *connection) { } void mpd_closeConnection(mpd_Connection *connection) { - if (connection) { + if (connection != nullptr) { closesocket(connection->sock); free_and_zero(connection->returnElement); free_and_zero(connection->request); @@ -473,12 +484,12 @@ void mpd_closeConnection(mpd_Connection *connection) { static void mpd_executeCommand(mpd_Connection *connection, const char *command) { int ret; - struct timeval tv; + struct timeval tv {}; fd_set fds; const char *commandPtr = command; int commandLen = strlen(command); - if (!connection->doneProcessing && !connection->commandList) { + if ((connection->doneProcessing == 0) && (connection->commandList == 0)) { strcpy(connection->errorStr, "not done processing current command"); connection->error = 1; return; @@ -491,7 +502,8 @@ static void mpd_executeCommand(mpd_Connection *connection, tv.tv_sec = connection->timeout.tv_sec; tv.tv_usec = connection->timeout.tv_usec; - while ((ret = select(connection->sock + 1, NULL, &fds, NULL, &tv) == 1) || + while (((ret = static_cast(select(connection->sock + 1, nullptr, &fds, + nullptr, &tv) == 1)) != 0) || (ret == -1 && SELECT_ERRNO_IGNORE)) { ret = send(connection->sock, commandPtr, commandLen, MSG_DONTWAIT); if (ret <= 0) { @@ -502,10 +514,9 @@ static void mpd_executeCommand(mpd_Connection *connection, "problems giving command \"%s\"", command); connection->error = MPD_ERROR_SENDING; return; - } else { + } commandPtr += ret; commandLen -= ret; - } if (commandLen <= 0) { break; @@ -520,7 +531,7 @@ static void mpd_executeCommand(mpd_Connection *connection, return; } - if (!connection->commandList) { + if (connection->commandList == 0) { connection->doneProcessing = 0; } else if (connection->commandList == COMMAND_LIST_OK) { connection->listOks++; @@ -528,25 +539,25 @@ static void mpd_executeCommand(mpd_Connection *connection, } static void mpd_getNextReturnElement(mpd_Connection *connection) { - char *output = NULL; - char *rt = NULL; - char *name = NULL; - char *value = NULL; + char *output = nullptr; + char *rt = nullptr; + char *name = nullptr; + char *value = nullptr; fd_set fds; - struct timeval tv; - char *tok = NULL; + struct timeval tv {}; + char *tok = nullptr; int readed; - char *bufferCheck = NULL; + char *bufferCheck = nullptr; int err; int pos; - if (connection->returnElement) { + if (connection->returnElement != nullptr) { mpd_freeReturnElement(connection->returnElement); } - connection->returnElement = NULL; + connection->returnElement = nullptr; - if (connection->doneProcessing || - (connection->listOks && connection->doneListOk)) { + if ((connection->doneProcessing != 0) || + ((connection->listOks != 0) && (connection->doneListOk != 0))) { strcpy(connection->errorStr, "already done processing current command"); connection->error = 1; return; @@ -554,7 +565,7 @@ static void mpd_getNextReturnElement(mpd_Connection *connection) { bufferCheck = connection->buffer + connection->bufstart; while (connection->bufstart >= connection->buflen || - !(rt = strchr(bufferCheck, '\n'))) { + ((rt = strchr(bufferCheck, '\n')) == nullptr)) { if (connection->buflen >= MPD_BUFFER_MAX_LENGTH) { memmove(connection->buffer, connection->buffer + connection->bufstart, connection->buflen - connection->bufstart + 1); @@ -573,7 +584,8 @@ static void mpd_getNextReturnElement(mpd_Connection *connection) { tv.tv_usec = connection->timeout.tv_usec; FD_ZERO(&fds); FD_SET(connection->sock, &fds); - if ((err = select(connection->sock + 1, &fds, NULL, NULL, &tv) == 1)) { + if ((err = static_cast(select(connection->sock + 1, &fds, nullptr, + nullptr, &tv) == 1)) != 0) { readed = recv(connection->sock, connection->buffer + connection->buflen, MPD_BUFFER_MAX_LENGTH - connection->buflen, MSG_DONTWAIT); if (readed < 0 && SENDRECV_ERRNO_IGNORE) { @@ -615,7 +627,7 @@ static void mpd_getNextReturnElement(mpd_Connection *connection) { } if (strcmp(output, "list_OK") == 0) { - if (!connection->listOks) { + if (connection->listOks == 0) { strcpy(connection->errorStr, "got an unexpected list_OK"); connection->error = 1; } else { @@ -638,7 +650,7 @@ static void mpd_getNextReturnElement(mpd_Connection *connection) { connection->doneListOk = 0; needle = strchr(output, '['); - if (!needle) { + if (needle == nullptr) { return; } val = strtol(needle + 1, &test, 10); @@ -655,7 +667,7 @@ static void mpd_getNextReturnElement(mpd_Connection *connection) { } tok = strchr(output, ':'); - if (!tok) { + if (tok == nullptr) { return; } pos = tok - output; @@ -673,8 +685,8 @@ static void mpd_getNextReturnElement(mpd_Connection *connection) { } void mpd_finishCommand(mpd_Connection *connection) { - while (connection && !connection->doneProcessing) { - if (connection->doneListOk) { + while ((connection != nullptr) && (connection->doneProcessing == 0)) { + if (connection->doneListOk != 0) { connection->doneListOk = 0; } mpd_getNextReturnElement(connection); @@ -682,18 +694,18 @@ void mpd_finishCommand(mpd_Connection *connection) { } static void mpd_finishListOkCommand(mpd_Connection *connection) { - while (!connection->doneProcessing && connection->listOks && - !connection->doneListOk) { + while ((connection->doneProcessing == 0) && (connection->listOks != 0) && + (connection->doneListOk == 0)) { mpd_getNextReturnElement(connection); } } int mpd_nextListOkCommand(mpd_Connection *connection) { mpd_finishListOkCommand(connection); - if (!connection->doneProcessing) { + if (connection->doneProcessing == 0) { connection->doneListOk = 0; } - if (connection->listOks == 0 || connection->doneProcessing) { + if (connection->listOks == 0 || (connection->doneProcessing != 0)) { return -1; } return 0; @@ -708,19 +720,19 @@ mpd_Status *mpd_getStatus(mpd_Connection *connection) { /* mpd_executeCommand(connection, "status\n"); if (connection->error) { - return NULL; + return nullptr; } */ - if (connection->doneProcessing || - (connection->listOks && connection->doneListOk)) { - return NULL; + if ((connection->doneProcessing != 0) || + ((connection->listOks != 0) && (connection->doneListOk != 0))) { + return nullptr; } - if (!connection->returnElement) { + if (connection->returnElement == nullptr) { mpd_getNextReturnElement(connection); } - status = (mpd_Status *)malloc(sizeof(mpd_Status)); + status = static_cast(malloc(sizeof(mpd_Status))); status->volume = -1; status->repeat = 0; status->random = 0; @@ -736,14 +748,14 @@ mpd_Status *mpd_getStatus(mpd_Connection *connection) { status->bits = 0; status->channels = 0; status->crossfade = -1; - status->error = NULL; + status->error = nullptr; status->updatingDb = 0; - if (connection->error) { + if (connection->error != 0) { free(status); - return NULL; + return nullptr; } - while (connection->returnElement) { + while (connection->returnElement != nullptr) { mpd_ReturnElement *re = connection->returnElement; if (strcmp(re->name, "volume") == 0) { @@ -753,7 +765,7 @@ mpd_Status *mpd_getStatus(mpd_Connection *connection) { } else if (strcmp(re->name, "random") == 0) { status->random = atoi(re->value); } else if (strcmp(re->name, "playlist") == 0) { - status->playlist = strtol(re->value, NULL, 10); + status->playlist = strtol(re->value, nullptr, 10); } else if (strcmp(re->name, "playlistlength") == 0) { status->playlistLength = atoi(re->value); } else if (strcmp(re->name, "bitrate") == 0) { @@ -776,7 +788,7 @@ mpd_Status *mpd_getStatus(mpd_Connection *connection) { char *tok = strchr(re->value, ':'); /* the second strchr below is a safety check */ - if (tok && (strchr(tok, 0) > (tok + 1))) { + if ((tok != nullptr) && (strchr(tok, 0) > (tok + 1))) { /* atoi stops at the first non-[0-9] char: */ status->elapsedTime = atoi(re->value); status->totalTime = atoi(tok + 1); @@ -790,31 +802,32 @@ mpd_Status *mpd_getStatus(mpd_Connection *connection) { } else if (strcmp(re->name, "audio") == 0) { char *tok = strchr(re->value, ':'); - if (tok && (strchr(tok, 0) > (tok + 1))) { + if ((tok != nullptr) && (strchr(tok, 0) > (tok + 1))) { status->sampleRate = atoi(re->value); status->bits = atoi(++tok); tok = strchr(tok, ':'); - if (tok && (strchr(tok, 0) > (tok + 1))) { + if ((tok != nullptr) && (strchr(tok, 0) > (tok + 1))) { status->channels = atoi(tok + 1); } } } mpd_getNextReturnElement(connection); - if (connection->error) { + if (connection->error != 0) { free(status); - return NULL; + return nullptr; } } - if (connection->error) { + if (connection->error != 0) { free(status); - return NULL; - } else if (status->state < 0) { + return nullptr; + } + if (status->state < 0) { strcpy(connection->errorStr, "state not found"); connection->error = 1; free(status); - return NULL; + return nullptr; } return status; @@ -834,19 +847,19 @@ mpd_Stats *mpd_getStats(mpd_Connection *connection) { /* mpd_executeCommand(connection, "stats\n"); if (connection->error) { - return NULL; + return nullptr; } */ - if (connection->doneProcessing || - (connection->listOks && connection->doneListOk)) { - return NULL; + if ((connection->doneProcessing != 0) || + ((connection->listOks != 0) && (connection->doneListOk != 0))) { + return nullptr; } - if (!connection->returnElement) { + if (connection->returnElement == nullptr) { mpd_getNextReturnElement(connection); } - stats = (mpd_Stats *)malloc(sizeof(mpd_Stats)); + stats = static_cast(malloc(sizeof(mpd_Stats))); stats->numberOfArtists = 0; stats->numberOfAlbums = 0; stats->numberOfSongs = 0; @@ -855,11 +868,11 @@ mpd_Stats *mpd_getStats(mpd_Connection *connection) { stats->playTime = 0; stats->dbPlayTime = 0; - if (connection->error) { + if (connection->error != 0) { free(stats); - return NULL; + return nullptr; } - while (connection->returnElement) { + while (connection->returnElement != nullptr) { mpd_ReturnElement *re = connection->returnElement; if (strcmp(re->name, "artists") == 0) { @@ -869,25 +882,25 @@ mpd_Stats *mpd_getStats(mpd_Connection *connection) { } else if (strcmp(re->name, "songs") == 0) { stats->numberOfSongs = atoi(re->value); } else if (strcmp(re->name, "uptime") == 0) { - stats->uptime = strtol(re->value, NULL, 10); + stats->uptime = strtol(re->value, nullptr, 10); } else if (strcmp(re->name, "db_update") == 0) { - stats->dbUpdateTime = strtol(re->value, NULL, 10); + stats->dbUpdateTime = strtol(re->value, nullptr, 10); } else if (strcmp(re->name, "playtime") == 0) { - stats->playTime = strtol(re->value, NULL, 10); + stats->playTime = strtol(re->value, nullptr, 10); } else if (strcmp(re->name, "db_playtime") == 0) { - stats->dbPlayTime = strtol(re->value, NULL, 10); + stats->dbPlayTime = strtol(re->value, nullptr, 10); } mpd_getNextReturnElement(connection); - if (connection->error) { + if (connection->error != 0) { free(stats); - return NULL; + return nullptr; } } - if (connection->error) { + if (connection->error != 0) { free(stats); - return NULL; + return nullptr; } return stats; @@ -899,42 +912,42 @@ mpd_SearchStats *mpd_getSearchStats(mpd_Connection *connection) { mpd_SearchStats *stats; mpd_ReturnElement *re; - if (connection->doneProcessing || - (connection->listOks && connection->doneListOk)) { - return NULL; + if ((connection->doneProcessing != 0) || + ((connection->listOks != 0) && (connection->doneListOk != 0))) { + return nullptr; } - if (!connection->returnElement) { + if (connection->returnElement == nullptr) { mpd_getNextReturnElement(connection); } - if (connection->error) { - return NULL; + if (connection->error != 0) { + return nullptr; } - stats = (mpd_SearchStats *)malloc(sizeof(mpd_SearchStats)); + stats = static_cast(malloc(sizeof(mpd_SearchStats))); stats->numberOfSongs = 0; stats->playTime = 0; - while (connection->returnElement) { + while (connection->returnElement != nullptr) { re = connection->returnElement; if (strcmp(re->name, "songs") == 0) { stats->numberOfSongs = atoi(re->value); } else if (strcmp(re->name, "playtime") == 0) { - stats->playTime = strtol(re->value, NULL, 10); + stats->playTime = strtol(re->value, nullptr, 10); } mpd_getNextReturnElement(connection); - if (connection->error) { + if (connection->error != 0) { free(stats); - return NULL; + return nullptr; } } - if (connection->error) { + if (connection->error != 0) { free(stats); - return NULL; + return nullptr; } return stats; @@ -943,20 +956,20 @@ mpd_SearchStats *mpd_getSearchStats(mpd_Connection *connection) { void mpd_freeSearchStats(mpd_SearchStats *stats) { free(stats); } static void mpd_initSong(mpd_Song *song) { - song->file = NULL; - song->artist = NULL; - song->albumartist = NULL; - song->album = NULL; - song->track = NULL; - song->title = NULL; - song->name = NULL; - song->date = NULL; + song->file = nullptr; + song->artist = nullptr; + song->albumartist = nullptr; + song->album = nullptr; + song->track = nullptr; + song->title = nullptr; + song->name = nullptr; + song->date = nullptr; /* added by Qball */ - song->genre = NULL; - song->composer = NULL; - song->performer = NULL; - song->disc = NULL; - song->comment = NULL; + song->genre = nullptr; + song->composer = nullptr; + song->performer = nullptr; + song->disc = nullptr; + song->comment = nullptr; song->time = MPD_SONG_NO_TIME; song->pos = MPD_SONG_NO_NUM; @@ -978,8 +991,8 @@ static void mpd_finishSong(mpd_Song *song) { free_and_zero(song->comment); } -mpd_Song *mpd_newSong(void) { - mpd_Song *ret = (mpd_Song *)malloc(sizeof(mpd_Song)); +mpd_Song *mpd_newSong() { + auto *ret = static_cast(malloc(sizeof(mpd_Song))); mpd_initSong(ret); @@ -994,40 +1007,40 @@ void mpd_freeSong(mpd_Song *song) { mpd_Song *mpd_songDup(mpd_Song *song) { mpd_Song *ret = mpd_newSong(); - if (song->file) { + if (song->file != nullptr) { ret->file = strndup(song->file, text_buffer_size.get(*state)); } - if (song->artist) { + if (song->artist != nullptr) { ret->artist = strndup(song->artist, text_buffer_size.get(*state)); } - if (song->albumartist) { + if (song->albumartist != nullptr) { ret->artist = strndup(song->albumartist, text_buffer_size.get(*state)); } - if (song->album) { + if (song->album != nullptr) { ret->album = strndup(song->album, text_buffer_size.get(*state)); } - if (song->title) { + if (song->title != nullptr) { ret->title = strndup(song->title, text_buffer_size.get(*state)); } - if (song->track) { + if (song->track != nullptr) { ret->track = strndup(song->track, text_buffer_size.get(*state)); } - if (song->name) { + if (song->name != nullptr) { ret->name = strndup(song->name, text_buffer_size.get(*state)); } - if (song->date) { + if (song->date != nullptr) { ret->date = strndup(song->date, text_buffer_size.get(*state)); } - if (song->genre) { + if (song->genre != nullptr) { ret->genre = strndup(song->genre, text_buffer_size.get(*state)); } - if (song->composer) { + if (song->composer != nullptr) { ret->composer = strndup(song->composer, text_buffer_size.get(*state)); } - if (song->disc) { + if (song->disc != nullptr) { ret->disc = strndup(song->disc, text_buffer_size.get(*state)); } - if (song->comment) { + if (song->comment != nullptr) { ret->comment = strndup(song->comment, text_buffer_size.get(*state)); } ret->time = song->time; @@ -1038,15 +1051,15 @@ mpd_Song *mpd_songDup(mpd_Song *song) { } static void mpd_initDirectory(mpd_Directory *directory) { - directory->path = NULL; + directory->path = nullptr; } static void mpd_finishDirectory(mpd_Directory *directory) { free_and_zero(directory->path); } -mpd_Directory *mpd_newDirectory(void) { - mpd_Directory *directory = (mpd_Directory *)malloc(sizeof(mpd_Directory)); +mpd_Directory *mpd_newDirectory() { + auto *directory = static_cast(malloc(sizeof(mpd_Directory))); mpd_initDirectory(directory); @@ -1062,7 +1075,7 @@ void mpd_freeDirectory(mpd_Directory *directory) { mpd_Directory *mpd_directoryDup(mpd_Directory *directory) { mpd_Directory *ret = mpd_newDirectory(); - if (directory->path) { + if (directory->path != nullptr) { ret->path = strndup(directory->path, text_buffer_size.get(*state)); } @@ -1070,16 +1083,16 @@ mpd_Directory *mpd_directoryDup(mpd_Directory *directory) { } static void mpd_initPlaylistFile(mpd_PlaylistFile *playlist) { - playlist->path = NULL; + playlist->path = nullptr; } static void mpd_finishPlaylistFile(mpd_PlaylistFile *playlist) { free_and_zero(playlist->path); } -mpd_PlaylistFile *mpd_newPlaylistFile(void) { - mpd_PlaylistFile *playlist = - (mpd_PlaylistFile *)malloc(sizeof(mpd_PlaylistFile)); +mpd_PlaylistFile *mpd_newPlaylistFile() { + auto *playlist = + static_cast(malloc(sizeof(mpd_PlaylistFile))); mpd_initPlaylistFile(playlist); @@ -1094,7 +1107,7 @@ void mpd_freePlaylistFile(mpd_PlaylistFile *playlist) { mpd_PlaylistFile *mpd_playlistFileDup(mpd_PlaylistFile *playlist) { mpd_PlaylistFile *ret = mpd_newPlaylistFile(); - if (playlist->path) { + if (playlist->path != nullptr) { ret->path = strndup(playlist->path, text_buffer_size.get(*state)); } @@ -1102,11 +1115,11 @@ mpd_PlaylistFile *mpd_playlistFileDup(mpd_PlaylistFile *playlist) { } static void mpd_initInfoEntity(mpd_InfoEntity *entity) { - entity->info.directory = NULL; + entity->info.directory = nullptr; } static void mpd_finishInfoEntity(mpd_InfoEntity *entity) { - if (entity->info.directory) { + if (entity->info.directory != nullptr) { if (entity->type == MPD_INFO_ENTITY_TYPE_DIRECTORY) { mpd_freeDirectory(entity->info.directory); } else if (entity->type == MPD_INFO_ENTITY_TYPE_SONG) { @@ -1117,8 +1130,8 @@ static void mpd_finishInfoEntity(mpd_InfoEntity *entity) { } } -mpd_InfoEntity *mpd_newInfoEntity(void) { - mpd_InfoEntity *entity = (mpd_InfoEntity *)malloc(sizeof(mpd_InfoEntity)); +mpd_InfoEntity *mpd_newInfoEntity() { + auto *entity = static_cast(malloc(sizeof(mpd_InfoEntity))); mpd_initInfoEntity(entity); @@ -1135,18 +1148,18 @@ static void mpd_sendInfoCommand(mpd_Connection *connection, char *command) { } mpd_InfoEntity *mpd_getNextInfoEntity(mpd_Connection *connection) { - mpd_InfoEntity *entity = NULL; + mpd_InfoEntity *entity = nullptr; - if (connection->doneProcessing || - (connection->listOks && connection->doneListOk)) { - return NULL; + if ((connection->doneProcessing != 0) || + ((connection->listOks != 0) && (connection->doneListOk != 0))) { + return nullptr; } - if (!connection->returnElement) { + if (connection->returnElement == nullptr) { mpd_getNextReturnElement(connection); } - if (connection->returnElement) { + if (connection->returnElement != nullptr) { if (strcmp(connection->returnElement->name, "file") == 0) { entity = mpd_newInfoEntity(); entity->type = MPD_INFO_ENTITY_TYPE_SONG; @@ -1173,44 +1186,53 @@ mpd_InfoEntity *mpd_getNextInfoEntity(mpd_Connection *connection) { } else { connection->error = 1; strcpy(connection->errorStr, "problem parsing song info"); - return NULL; + return nullptr; } } else { - return NULL; + return nullptr; } mpd_getNextReturnElement(connection); - while (connection->returnElement) { + while (connection->returnElement != nullptr) { mpd_ReturnElement *re = connection->returnElement; if (strcmp(re->name, "file") == 0) { return entity; - } else if (strcmp(re->name, "directory") == 0) { + } + if (strcmp(re->name, "directory") == 0) { return entity; - } else if (strcmp(re->name, "playlist") == 0) { + } + if (strcmp(re->name, "playlist") == 0) { return entity; - } else if (strcmp(re->name, "cpos") == 0) { + } + if (strcmp(re->name, "cpos") == 0) { return entity; } - if (entity->type == MPD_INFO_ENTITY_TYPE_SONG && strlen(re->value)) { - if (!entity->info.song->artist && strcmp(re->name, "Artist") == 0) { + if (entity->type == MPD_INFO_ENTITY_TYPE_SONG && + (strlen(re->value) != 0u)) { + if ((entity->info.song->artist == nullptr) && + strcmp(re->name, "Artist") == 0) { entity->info.song->artist = strndup(re->value, text_buffer_size.get(*state)); - } else if (!entity->info.song->albumartist && + } else if ((entity->info.song->albumartist == nullptr) && strcmp(re->name, "AlbumArtist") == 0) { entity->info.song->albumartist = strndup(re->value, text_buffer_size.get(*state)); - } else if (!entity->info.song->album && strcmp(re->name, "Album") == 0) { + } else if ((entity->info.song->album == nullptr) && + strcmp(re->name, "Album") == 0) { entity->info.song->album = strndup(re->value, text_buffer_size.get(*state)); - } else if (!entity->info.song->title && strcmp(re->name, "Title") == 0) { + } else if ((entity->info.song->title == nullptr) && + strcmp(re->name, "Title") == 0) { entity->info.song->title = strndup(re->value, text_buffer_size.get(*state)); - } else if (!entity->info.song->track && strcmp(re->name, "Track") == 0) { + } else if ((entity->info.song->track == nullptr) && + strcmp(re->name, "Track") == 0) { entity->info.song->track = strndup(re->value, text_buffer_size.get(*state)); - } else if (!entity->info.song->name && strcmp(re->name, "Name") == 0) { + } else if ((entity->info.song->name == nullptr) && + strcmp(re->name, "Name") == 0) { entity->info.song->name = strndup(re->value, text_buffer_size.get(*state)); } else if (entity->info.song->time == MPD_SONG_NO_TIME && @@ -1222,24 +1244,27 @@ mpd_InfoEntity *mpd_getNextInfoEntity(mpd_Connection *connection) { } else if (entity->info.song->id == MPD_SONG_NO_ID && strcmp(re->name, "Id") == 0) { entity->info.song->id = atoi(re->value); - } else if (!entity->info.song->date && strcmp(re->name, "Date") == 0) { + } else if ((entity->info.song->date == nullptr) && + strcmp(re->name, "Date") == 0) { entity->info.song->date = strndup(re->value, text_buffer_size.get(*state)); - } else if (!entity->info.song->genre && strcmp(re->name, "Genre") == 0) { + } else if ((entity->info.song->genre == nullptr) && + strcmp(re->name, "Genre") == 0) { entity->info.song->genre = strndup(re->value, text_buffer_size.get(*state)); - } else if (!entity->info.song->composer && + } else if ((entity->info.song->composer == nullptr) && strcmp(re->name, "Composer") == 0) { entity->info.song->composer = strndup(re->value, text_buffer_size.get(*state)); - } else if (!entity->info.song->performer && + } else if ((entity->info.song->performer == nullptr) && strcmp(re->name, "Performer") == 0) { entity->info.song->performer = strndup(re->value, text_buffer_size.get(*state)); - } else if (!entity->info.song->disc && strcmp(re->name, "Disc") == 0) { + } else if ((entity->info.song->disc == nullptr) && + strcmp(re->name, "Disc") == 0) { entity->info.song->disc = strndup(re->value, text_buffer_size.get(*state)); - } else if (!entity->info.song->comment && + } else if ((entity->info.song->comment == nullptr) && strcmp(re->name, "Comment") == 0) { entity->info.song->comment = strndup(re->value, text_buffer_size.get(*state)); @@ -1256,13 +1281,13 @@ mpd_InfoEntity *mpd_getNextInfoEntity(mpd_Connection *connection) { static char *mpd_getNextReturnElementNamed(mpd_Connection *connection, const char *name) { - if (connection->doneProcessing || - (connection->listOks && connection->doneListOk)) { - return NULL; + if ((connection->doneProcessing != 0) || + ((connection->listOks != 0) && (connection->doneListOk != 0))) { + return nullptr; } mpd_getNextReturnElement(connection); - while (connection->returnElement) { + while (connection->returnElement != nullptr) { mpd_ReturnElement *re = connection->returnElement; if (strcmp(re->name, name) == 0) { @@ -1271,13 +1296,13 @@ static char *mpd_getNextReturnElementNamed(mpd_Connection *connection, mpd_getNextReturnElement(connection); } - return NULL; + return nullptr; } char *mpd_getNextTag(mpd_Connection *connection, int type) { if (type < 0 || type >= MPD_TAG_NUM_OF_ITEM_TYPES || type == MPD_TAG_ITEM_ANY) { - return NULL; + return nullptr; } if (type == MPD_TAG_ITEM_FILENAME) { return mpd_getNextReturnElementNamed(connection, "file"); @@ -1295,7 +1320,7 @@ char *mpd_getNextAlbum(mpd_Connection *connection) { void mpd_sendPlaylistInfoCommand(mpd_Connection *connection, int songPos) { int len = strlen("playlistinfo") + 2 + INTLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "playlistinfo \"%i\"\n", songPos); mpd_sendInfoCommand(connection, string); @@ -1304,7 +1329,7 @@ void mpd_sendPlaylistInfoCommand(mpd_Connection *connection, int songPos) { void mpd_sendPlaylistIdCommand(mpd_Connection *connection, int id) { int len = strlen("playlistid") + 2 + INTLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "playlistid \"%i\"\n", id); mpd_sendInfoCommand(connection, string); @@ -1313,7 +1338,7 @@ void mpd_sendPlaylistIdCommand(mpd_Connection *connection, int id) { void mpd_sendPlChangesCommand(mpd_Connection *connection, long long playlist) { int len = strlen("plchanges") + 2 + LONGLONGLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "plchanges \"%lld\"\n", playlist); mpd_sendInfoCommand(connection, string); @@ -1323,7 +1348,7 @@ void mpd_sendPlChangesCommand(mpd_Connection *connection, long long playlist) { void mpd_sendPlChangesPosIdCommand(mpd_Connection *connection, long long playlist) { int len = strlen("plchangesposid") + 2 + LONGLONGLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "plchangesposid \"%lld\"\n", playlist); mpd_sendInfoCommand(connection, string); @@ -1333,7 +1358,7 @@ void mpd_sendPlChangesPosIdCommand(mpd_Connection *connection, void mpd_sendListallCommand(mpd_Connection *connection, const char *dir) { char *sDir = mpd_sanitizeArg(dir); int len = strlen("listall") + 2 + strlen(sDir) + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "listall \"%s\"\n", sDir); mpd_sendInfoCommand(connection, string); @@ -1344,7 +1369,7 @@ void mpd_sendListallCommand(mpd_Connection *connection, const char *dir) { void mpd_sendListallInfoCommand(mpd_Connection *connection, const char *dir) { char *sDir = mpd_sanitizeArg(dir); int len = strlen("listallinfo") + 2 + strlen(sDir) + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "listallinfo \"%s\"\n", sDir); mpd_sendInfoCommand(connection, string); @@ -1355,7 +1380,7 @@ void mpd_sendListallInfoCommand(mpd_Connection *connection, const char *dir) { void mpd_sendLsInfoCommand(mpd_Connection *connection, const char *dir) { char *sDir = mpd_sanitizeArg(dir); int len = strlen("lsinfo") + 2 + strlen(sDir) + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "lsinfo \"%s\"\n", sDir); mpd_sendInfoCommand(connection, string); @@ -1396,16 +1421,16 @@ void mpd_sendListCommand(mpd_Connection *connection, int table, strcpy(connection->errorStr, "unknown table for list"); return; } - if (arg1) { + if (arg1 != nullptr) { char *sanitArg1 = mpd_sanitizeArg(arg1); len = strlen("list") + 1 + strlen(sanitArg1) + 2 + strlen(st) + 3; - string = (char *)malloc(len); + string = static_cast(malloc(len)); snprintf(string, len, "list %s \"%s\"\n", st, sanitArg1); free(sanitArg1); } else { len = strlen("list") + 1 + strlen(st) + 2; - string = (char *)malloc(len); + string = static_cast(malloc(len)); snprintf(string, len, "list %s\n", st); } mpd_sendInfoCommand(connection, string); @@ -1415,7 +1440,7 @@ void mpd_sendListCommand(mpd_Connection *connection, int table, void mpd_sendAddCommand(mpd_Connection *connection, const char *file) { char *sFile = mpd_sanitizeArg(file); int len = strlen("add") + 2 + strlen(sFile) + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "add \"%s\"\n", sFile); mpd_executeCommand(connection, string); @@ -1427,7 +1452,7 @@ int mpd_sendAddIdCommand(mpd_Connection *connection, const char *file) { int retval = -1; char *sFile = mpd_sanitizeArg(file); int len = strlen("addid") + 2 + strlen(sFile) + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "addid \"%s\"\n", sFile); mpd_sendInfoCommand(connection, string); @@ -1435,7 +1460,7 @@ int mpd_sendAddIdCommand(mpd_Connection *connection, const char *file) { free(sFile); string = mpd_getNextReturnElementNamed(connection, "Id"); - if (string) { + if (string != nullptr) { retval = atoi(string); free(string); } @@ -1445,7 +1470,7 @@ int mpd_sendAddIdCommand(mpd_Connection *connection, const char *file) { void mpd_sendDeleteCommand(mpd_Connection *connection, int songPos) { int len = strlen("delete") + 2 + INTLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "delete \"%i\"\n", songPos); mpd_sendInfoCommand(connection, string); @@ -1454,7 +1479,7 @@ void mpd_sendDeleteCommand(mpd_Connection *connection, int songPos) { void mpd_sendDeleteIdCommand(mpd_Connection *connection, int id) { int len = strlen("deleteid") + 2 + INTLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "deleteid \"%i\"\n", id); mpd_sendInfoCommand(connection, string); @@ -1464,7 +1489,7 @@ void mpd_sendDeleteIdCommand(mpd_Connection *connection, int id) { void mpd_sendSaveCommand(mpd_Connection *connection, const char *name) { char *sName = mpd_sanitizeArg(name); int len = strlen("save") + 2 + strlen(sName) + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "save \"%s\"\n", sName); mpd_executeCommand(connection, string); @@ -1475,7 +1500,7 @@ void mpd_sendSaveCommand(mpd_Connection *connection, const char *name) { void mpd_sendLoadCommand(mpd_Connection *connection, const char *name) { char *sName = mpd_sanitizeArg(name); int len = strlen("load") + 2 + strlen(sName) + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "load \"%s\"\n", sName); mpd_executeCommand(connection, string); @@ -1486,7 +1511,7 @@ void mpd_sendLoadCommand(mpd_Connection *connection, const char *name) { void mpd_sendRmCommand(mpd_Connection *connection, const char *name) { char *sName = mpd_sanitizeArg(name); int len = strlen("rm") + 2 + strlen(sName) + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "rm \"%s\"\n", sName); mpd_executeCommand(connection, string); @@ -1499,7 +1524,7 @@ void mpd_sendRenameCommand(mpd_Connection *connection, const char *from, char *sFrom = mpd_sanitizeArg(from); char *sTo = mpd_sanitizeArg(to); int len = strlen("rename") + 2 + strlen(sFrom) + 3 + strlen(sTo) + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "rename \"%s\" \"%s\"\n", sFrom, sTo); mpd_executeCommand(connection, string); @@ -1518,7 +1543,7 @@ void mpd_sendClearCommand(mpd_Connection *connection) { void mpd_sendPlayCommand(mpd_Connection *connection, int songPos) { int len = strlen("play") + 2 + INTLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "play \"%i\"\n", songPos); mpd_sendInfoCommand(connection, string); @@ -1527,7 +1552,7 @@ void mpd_sendPlayCommand(mpd_Connection *connection, int songPos) { void mpd_sendPlayIdCommand(mpd_Connection *connection, int id) { int len = strlen("playid") + 2 + INTLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "playid \"%i\"\n", id); mpd_sendInfoCommand(connection, string); @@ -1540,7 +1565,7 @@ void mpd_sendStopCommand(mpd_Connection *connection) { void mpd_sendPauseCommand(mpd_Connection *connection, int pauseMode) { int len = strlen("pause") + 2 + INTLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "pause \"%i\"\n", pauseMode); mpd_executeCommand(connection, string); @@ -1553,7 +1578,7 @@ void mpd_sendNextCommand(mpd_Connection *connection) { void mpd_sendMoveCommand(mpd_Connection *connection, int from, int to) { int len = strlen("move") + 2 + INTLEN + 3 + INTLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "move \"%i\" \"%i\"\n", from, to); mpd_sendInfoCommand(connection, string); @@ -1562,7 +1587,7 @@ void mpd_sendMoveCommand(mpd_Connection *connection, int from, int to) { void mpd_sendMoveIdCommand(mpd_Connection *connection, int id, int to) { int len = strlen("moveid") + 2 + INTLEN + 3 + INTLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "moveid \"%i\" \"%i\"\n", id, to); mpd_sendInfoCommand(connection, string); @@ -1571,7 +1596,7 @@ void mpd_sendMoveIdCommand(mpd_Connection *connection, int id, int to) { void mpd_sendSwapCommand(mpd_Connection *connection, int song1, int song2) { int len = strlen("swap") + 2 + INTLEN + 3 + INTLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "swap \"%i\" \"%i\"\n", song1, song2); mpd_sendInfoCommand(connection, string); @@ -1580,7 +1605,7 @@ void mpd_sendSwapCommand(mpd_Connection *connection, int song1, int song2) { void mpd_sendSwapIdCommand(mpd_Connection *connection, int id1, int id2) { int len = strlen("swapid") + 2 + INTLEN + 3 + INTLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "swapid \"%i\" \"%i\"\n", id1, id2); mpd_sendInfoCommand(connection, string); @@ -1589,7 +1614,7 @@ void mpd_sendSwapIdCommand(mpd_Connection *connection, int id1, int id2) { void mpd_sendSeekCommand(mpd_Connection *connection, int song, int seek_time) { int len = strlen("seek") + 2 + INTLEN + 3 + INTLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "seek \"%i\" \"%i\"\n", song, seek_time); mpd_sendInfoCommand(connection, string); @@ -1598,7 +1623,7 @@ void mpd_sendSeekCommand(mpd_Connection *connection, int song, int seek_time) { void mpd_sendSeekIdCommand(mpd_Connection *connection, int id, int seek_time) { int len = strlen("seekid") + 2 + INTLEN + 3 + INTLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "seekid \"%i\" \"%i\"\n", id, seek_time); mpd_sendInfoCommand(connection, string); @@ -1608,7 +1633,7 @@ void mpd_sendSeekIdCommand(mpd_Connection *connection, int id, int seek_time) { void mpd_sendUpdateCommand(mpd_Connection *connection, char *path) { char *sPath = mpd_sanitizeArg(path); int len = strlen("update") + 2 + strlen(sPath) + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "update \"%s\"\n", sPath); mpd_sendInfoCommand(connection, string); @@ -1621,7 +1646,7 @@ int mpd_getUpdateId(mpd_Connection *connection) { int ret = 0; jobid = mpd_getNextReturnElementNamed(connection, "updating_db"); - if (jobid) { + if (jobid != nullptr) { ret = atoi(jobid); free(jobid); } @@ -1635,7 +1660,7 @@ void mpd_sendPrevCommand(mpd_Connection *connection) { void mpd_sendRepeatCommand(mpd_Connection *connection, int repeatMode) { int len = strlen("repeat") + 2 + INTLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "repeat \"%i\"\n", repeatMode); mpd_executeCommand(connection, string); @@ -1644,7 +1669,7 @@ void mpd_sendRepeatCommand(mpd_Connection *connection, int repeatMode) { void mpd_sendRandomCommand(mpd_Connection *connection, int randomMode) { int len = strlen("random") + 2 + INTLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "random \"%i\"\n", randomMode); mpd_executeCommand(connection, string); @@ -1653,7 +1678,7 @@ void mpd_sendRandomCommand(mpd_Connection *connection, int randomMode) { void mpd_sendSetvolCommand(mpd_Connection *connection, int volumeChange) { int len = strlen("setvol") + 2 + INTLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "setvol \"%i\"\n", volumeChange); mpd_executeCommand(connection, string); @@ -1662,7 +1687,7 @@ void mpd_sendSetvolCommand(mpd_Connection *connection, int volumeChange) { void mpd_sendVolumeCommand(mpd_Connection *connection, int volumeChange) { int len = strlen("volume") + 2 + INTLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "volume \"%i\"\n", volumeChange); mpd_executeCommand(connection, string); @@ -1671,7 +1696,7 @@ void mpd_sendVolumeCommand(mpd_Connection *connection, int volumeChange) { void mpd_sendCrossfadeCommand(mpd_Connection *connection, int seconds) { int len = strlen("crossfade") + 2 + INTLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "crossfade \"%i\"\n", seconds); mpd_executeCommand(connection, string); @@ -1681,7 +1706,7 @@ void mpd_sendCrossfadeCommand(mpd_Connection *connection, int seconds) { void mpd_sendPasswordCommand(mpd_Connection *connection, const char *pass) { char *sPass = mpd_sanitizeArg(pass); int len = strlen("password") + 2 + strlen(sPass) + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "password \"%s\"\n", sPass); mpd_executeCommand(connection, string); @@ -1690,7 +1715,7 @@ void mpd_sendPasswordCommand(mpd_Connection *connection, const char *pass) { } void mpd_sendCommandListBegin(mpd_Connection *connection) { - if (connection->commandList) { + if (connection->commandList != 0) { strcpy(connection->errorStr, "already in command list mode"); connection->error = 1; return; @@ -1700,7 +1725,7 @@ void mpd_sendCommandListBegin(mpd_Connection *connection) { } void mpd_sendCommandListOkBegin(mpd_Connection *connection) { - if (connection->commandList) { + if (connection->commandList != 0) { strcpy(connection->errorStr, "already in command list mode"); connection->error = 1; return; @@ -1711,7 +1736,7 @@ void mpd_sendCommandListOkBegin(mpd_Connection *connection) { } void mpd_sendCommandListEnd(mpd_Connection *connection) { - if (!connection->commandList) { + if (connection->commandList == 0) { strcpy(connection->errorStr, "not in command list mode"); connection->error = 1; return; @@ -1725,31 +1750,31 @@ void mpd_sendOutputsCommand(mpd_Connection *connection) { } mpd_OutputEntity *mpd_getNextOutput(mpd_Connection *connection) { - mpd_OutputEntity *output = NULL; + mpd_OutputEntity *output = nullptr; - if (connection->doneProcessing || - (connection->listOks && connection->doneListOk)) { - return NULL; + if ((connection->doneProcessing != 0) || + ((connection->listOks != 0) && (connection->doneListOk != 0))) { + return nullptr; } - if (connection->error) { - return NULL; + if (connection->error != 0) { + return nullptr; } - output = (mpd_OutputEntity *)malloc(sizeof(mpd_OutputEntity)); + output = static_cast(malloc(sizeof(mpd_OutputEntity))); output->id = -10; - output->name = NULL; + output->name = nullptr; output->enabled = 0; - if (!connection->returnElement) { + if (connection->returnElement == nullptr) { mpd_getNextReturnElement(connection); } - while (connection->returnElement) { + while (connection->returnElement != nullptr) { mpd_ReturnElement *re = connection->returnElement; if (strcmp(re->name, "outputid") == 0) { - if (output != NULL && output->id >= 0) { + if (output != nullptr && output->id >= 0) { return output; } output->id = atoi(re->value); @@ -1760,9 +1785,9 @@ mpd_OutputEntity *mpd_getNextOutput(mpd_Connection *connection) { } mpd_getNextReturnElement(connection); - if (connection->error) { + if (connection->error != 0) { free(output); - return NULL; + return nullptr; } } @@ -1771,7 +1796,7 @@ mpd_OutputEntity *mpd_getNextOutput(mpd_Connection *connection) { void mpd_sendEnableOutputCommand(mpd_Connection *connection, int outputId) { int len = strlen("enableoutput") + 2 + INTLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "enableoutput \"%i\"\n", outputId); mpd_executeCommand(connection, string); @@ -1780,7 +1805,7 @@ void mpd_sendEnableOutputCommand(mpd_Connection *connection, int outputId) { void mpd_sendDisableOutputCommand(mpd_Connection *connection, int outputId) { int len = strlen("disableoutput") + 2 + INTLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "disableoutput \"%i\"\n", outputId); mpd_executeCommand(connection, string); @@ -1824,13 +1849,13 @@ char *mpd_getNextTagType(mpd_Connection *connection) { } void mpd_startSearch(mpd_Connection *connection, int exact) { - if (connection->request) { + if (connection->request != nullptr) { strcpy(connection->errorStr, "search already in progress"); connection->error = 1; return; } - if (exact) { + if (exact != 0) { connection->request = strndup("find", text_buffer_size.get(*state)); } else { connection->request = strndup("search", text_buffer_size.get(*state)); @@ -1838,7 +1863,7 @@ void mpd_startSearch(mpd_Connection *connection, int exact) { } void mpd_startStatsSearch(mpd_Connection *connection) { - if (connection->request) { + if (connection->request != nullptr) { strcpy(connection->errorStr, "search already in progress"); connection->error = 1; return; @@ -1848,13 +1873,13 @@ void mpd_startStatsSearch(mpd_Connection *connection) { } void mpd_startPlaylistSearch(mpd_Connection *connection, int exact) { - if (connection->request) { + if (connection->request != nullptr) { strcpy(connection->errorStr, "search already in progress"); connection->error = 1; return; } - if (exact) { + if (exact != 0) { connection->request = strndup("playlistfind", text_buffer_size.get(*state)); } else { connection->request = @@ -1866,7 +1891,7 @@ void mpd_startFieldSearch(mpd_Connection *connection, int type) { const char *strtype; int len; - if (connection->request) { + if (connection->request != nullptr) { strcpy(connection->errorStr, "search already in progress"); connection->error = 1; return; @@ -1881,7 +1906,7 @@ void mpd_startFieldSearch(mpd_Connection *connection, int type) { strtype = mpdTagItemKeys[type]; len = 5 + strlen(strtype) + 1; - connection->request = (char *)malloc(len); + connection->request = static_cast(malloc(len)); snprintf(connection->request, len, "list %c%s", tolower(strtype[0]), strtype + 1); @@ -1894,7 +1919,7 @@ void mpd_addConstraintSearch(mpd_Connection *connection, int type, int len; char *string; - if (!connection->request) { + if (connection->request == nullptr) { strcpy(connection->errorStr, "no search in progress"); connection->error = 1; return; @@ -1906,7 +1931,7 @@ void mpd_addConstraintSearch(mpd_Connection *connection, int type, return; } - if (name == NULL) { + if (name == nullptr) { strcpy(connection->errorStr, "no name specified"); connection->error = 1; return; @@ -1917,7 +1942,7 @@ void mpd_addConstraintSearch(mpd_Connection *connection, int type, arg = mpd_sanitizeArg(name); len = strlen(string) + 1 + strlen(strtype) + 2 + strlen(arg) + 2; - connection->request = (char *)realloc(connection->request, len); + connection->request = static_cast(realloc(connection->request, len)); snprintf(connection->request, len, "%s %c%s \"%s\"", string, tolower(strtype[0]), strtype + 1, arg); @@ -1928,14 +1953,14 @@ void mpd_addConstraintSearch(mpd_Connection *connection, int type, void mpd_commitSearch(mpd_Connection *connection) { int len; - if (!connection->request) { + if (connection->request == nullptr) { strcpy(connection->errorStr, "no search in progress"); connection->error = 1; return; } len = strlen(connection->request) + 2; - connection->request = (char *)realloc(connection->request, len); + connection->request = static_cast(realloc(connection->request, len)); connection->request[len - 2] = '\n'; connection->request[len - 1] = '\0'; mpd_sendInfoCommand(connection, connection->request); @@ -1951,7 +1976,7 @@ void mpd_commitSearch(mpd_Connection *connection) { void mpd_sendListPlaylistInfoCommand(mpd_Connection *connection, char *path) { char *arg = mpd_sanitizeArg(path); int len = strlen("listplaylistinfo") + 2 + strlen(arg) + 3; - char *query = (char *)malloc(len); + auto *query = static_cast(malloc(len)); snprintf(query, len, "listplaylistinfo \"%s\"\n", arg); mpd_sendInfoCommand(connection, query); @@ -1967,7 +1992,7 @@ void mpd_sendListPlaylistInfoCommand(mpd_Connection *connection, char *path) { void mpd_sendListPlaylistCommand(mpd_Connection *connection, char *path) { char *arg = mpd_sanitizeArg(path); int len = strlen("listplaylist") + 2 + strlen(arg) + 3; - char *query = (char *)malloc(len); + auto *query = static_cast(malloc(len)); snprintf(query, len, "listplaylist \"%s\"\n", arg); mpd_sendInfoCommand(connection, query); @@ -1978,7 +2003,7 @@ void mpd_sendListPlaylistCommand(mpd_Connection *connection, char *path) { void mpd_sendPlaylistClearCommand(mpd_Connection *connection, char *path) { char *sPath = mpd_sanitizeArg(path); int len = strlen("playlistclear") + 2 + strlen(sPath) + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "playlistclear \"%s\"\n", sPath); mpd_executeCommand(connection, string); @@ -1992,7 +2017,7 @@ void mpd_sendPlaylistAddCommand(mpd_Connection *connection, char *playlist, char *sPath = mpd_sanitizeArg(path); int len = strlen("playlistadd") + 2 + strlen(sPlaylist) + 3 + strlen(sPath) + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "playlistadd \"%s\" \"%s\"\n", sPlaylist, sPath); mpd_executeCommand(connection, string); @@ -2006,7 +2031,7 @@ void mpd_sendPlaylistMoveCommand(mpd_Connection *connection, char *playlist, char *sPlaylist = mpd_sanitizeArg(playlist); int len = strlen("playlistmove") + 2 + strlen(sPlaylist) + 3 + INTLEN + 3 + INTLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "playlistmove \"%s\" \"%i\" \"%i\"\n", sPlaylist, from, to); @@ -2019,7 +2044,7 @@ void mpd_sendPlaylistDeleteCommand(mpd_Connection *connection, char *playlist, int pos) { char *sPlaylist = mpd_sanitizeArg(playlist); int len = strlen("playlistdelete") + 2 + strlen(sPlaylist) + 3 + INTLEN + 3; - char *string = (char *)malloc(len); + auto *string = static_cast(malloc(len)); snprintf(string, len, "playlistdelete \"%s\" \"%i\"\n", sPlaylist, pos); mpd_executeCommand(connection, string); diff --git a/src/libmpdclient.h b/src/libmpdclient.h index 44f9cda8..419f286b 100644 --- a/src/libmpdclient.h +++ b/src/libmpdclient.h @@ -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); diff --git a/src/libtcp-portmon.cc b/src/libtcp-portmon.cc index 5dc67f03..e40fcb7a 100644 --- a/src/libtcp-portmon.cc +++ b/src/libtcp-portmon.cc @@ -114,12 +114,12 @@ struct _tcp_port_monitor_t { _tcp_port_monitor_t(int max_connections) : hash(), - p_peek(max_connections, static_cast(NULL)) {} + p_peek(max_connections, static_cast(nullptr)) {} _tcp_port_monitor_t(const _tcp_port_monitor_t &other) : hash(other.hash), p_peek(other.p_peek.size(), - static_cast(NULL)) { + static_cast(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(NULL)); + static_cast(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; } diff --git a/src/linux.cc b/src/linux.cc index 78263ed5..c9829594 100644 --- a/src/linux.cc +++ b/src/linux.cc @@ -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��ll� 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); diff --git a/src/llua.cc b/src/llua.cc index 8c86a59b..3e92ba30 100644 --- a/src/llua.cc +++ b/src/llua.cc @@ -22,10 +22,10 @@ */ #include "llua.h" -#include #include "build.h" #include "conky.h" #include "logging.h" +#include #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 { - typedef conky::simple_config_setting Base; + using Base = conky::simple_config_setting; 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 { ++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 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(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(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; diff --git a/src/luamm.cc b/src/luamm.cc index d413eb3f..8353d351 100644 --- a/src/luamm.cc +++ b/src/luamm.cc @@ -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(lua_touserdata(l, -1)); + auto *ptr = static_cast(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(lua_touserdata(l, -1)); + auto *L = static_cast(lua_touserdata(l, -1)); lua_pop(l, 1); try { - cpp_function *fn = - static_cast(L->touserdata(lua_upvalueindex(1))); + auto *fn = static_cast(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(lua_touserdata(l, -1)); + auto *L = static_cast(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(touserdata(-3)); + auto *ptr = static_cast(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, 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 diff --git a/src/luamm.hh b/src/luamm.hh index 26589930..2d62a1ec 100644 --- a/src/luamm.hh +++ b/src/luamm.hh @@ -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 @@ -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); } diff --git a/src/mail.cc b/src/mail.cc index 4415abe5..1f16dbb7 100644 --- a/src/mail.cc +++ b/src/mail.cc @@ -36,13 +36,13 @@ #include "logging.h" #include "text_object.h" -#include -#include -#include +#include +#include +#include +#include +#include #include #include -#include -#include #include #include #include @@ -53,6 +53,7 @@ #include #include +#include #include #include @@ -81,7 +82,9 @@ struct local_mail_s { std::pair 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()); - if (int res = getaddrinfo(get().c_str(), portbuf, &hints, &ai)) + if (int res = getaddrinfo(get().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(other); + void merge(callback_base &&other) override { + auto &&o = dynamic_cast(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(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( + 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(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(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 parse_mail_args(mail_type type, const char *arg) { @@ -513,26 +529,28 @@ std::unique_ptr 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(); get(*mail) = host; get(*mail) = user; get(*mail) = pass; // now we check for optional args - tmp = (char *)strstr(arg, "-r "); - if (tmp) { + tmp = const_cast(strstr(arg, "-r ")); + if (tmp != nullptr) { tmp += 3; sscanf(tmp, "%" SCNu16, &mail->retries); } else { @@ -540,15 +558,15 @@ std::unique_ptr parse_mail_args(mail_type type, } float interval = DEFAULT_MAIL_INTERVAL; - tmp = (char *)strstr(arg, "-i "); - if (tmp) { + tmp = const_cast(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(strstr(arg, "-p ")); + if (tmp != nullptr) { tmp += 3; sscanf(tmp, "%" SCNu16, &get(*mail)); } else { @@ -559,12 +577,12 @@ std::unique_ptr parse_mail_args(mail_type type, } } if (type == IMAP_TYPE) { - tmp = (char *)strstr(arg, "-f "); - if (tmp) { + tmp = const_cast(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(*mail).assign(tmp, len); @@ -572,13 +590,13 @@ std::unique_ptr parse_mail_args(mail_type type, get(*mail) = "INBOX"; // default imap inbox } } - tmp = (char *)strstr(arg, "-e "); - if (tmp) { + tmp = const_cast(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(*mail).assign(tmp + 1, len); } @@ -589,8 +607,8 @@ std::unique_ptr 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 { - typedef conky::simple_config_setting Base; + using Base = conky::simple_config_setting; 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(!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(obj->data.opaque); + auto *mail = static_cast(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 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() << " {" << get().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().c_str(), get().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(obj->data.opaque); - if (!mail) return; + if (mail == nullptr) { + return; + } auto cb = conky::register_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(obj->data.opaque); - if (!mail) return; + if (mail == nullptr) { + return; + } auto cb = conky::register_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().c_str(), get().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(obj->data.opaque); - if (!mail) return; + if (mail == nullptr) { + return; + } auto cb = conky::register_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(obj->data.opaque); - if (!mail) return; + if (mail == nullptr) { + return; + } auto cb = conky::register_cb(mail->period, *mail, mail->retries); diff --git a/src/mboxscan.cc b/src/mboxscan.cc index bcfe0c12..bcc2f881 100644 --- a/src/mboxscan.cc +++ b/src/mboxscan.cc @@ -27,9 +27,9 @@ * */ -#include #include #include +#include #include #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 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 ] " "[-fw ] [-sw ] " "[-t 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(malloc(sizeof(struct ring_list))); + curr->from = static_cast(malloc(from_width + 1)); + curr->subject = static_cast(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(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(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(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(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); diff --git a/src/mixer.cc b/src/mixer.cc index 430e4370..16ba0c39 100644 --- a/src/mixer.cc +++ b/src/mixer.cc @@ -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); } } diff --git a/src/moc.cc b/src/moc.cc index e6c39069..073b20f7 100644 --- a/src/moc.cc +++ b/src/moc.cc @@ -24,10 +24,10 @@ #include "logging.h" #include "text_object.h" -#include -#include -#include #include +#include +#include +#include #include #include "update-cb.hh" @@ -48,13 +48,13 @@ struct moc_result { }; class moc_cb : public conky::callback { - typedef conky::callback Base; + using Base = conky::callback; 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(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, "??") diff --git a/src/mpd.cc b/src/mpd.cc index 270e3918..87bdf665 100644 --- a/src/mpd.cc +++ b/src/mpd.cc @@ -27,13 +27,13 @@ */ #include "mpd.h" -#include -#include #include "conky.h" #include "libmpdclient.h" #include "logging.h" #include "timeinfo.h" #include "update-cb.hh" +#include +#include namespace { @@ -41,10 +41,10 @@ namespace { bool mpd_environment_host = false; class mpd_host_setting : public conky::simple_config_setting { - typedef conky::simple_config_setting Base; + using Base = conky::simple_config_setting; 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 { - typedef conky::simple_config_setting Base; + using Base = conky::simple_config_setting; 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 { - typedef conky::callback Base; + using Base = conky::callback; 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(!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(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(!mpd_info.artist.empty()) != 0u) && + (static_cast(!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(!get_mpd().title.empty()) != 0u) { snprintf(p, len, "%s", mpd_info.title.c_str()); - } else if (mpd_info.artist.size()) { + } else if (static_cast(!mpd_info.artist.empty()) != 0u) { snprintf(p, len, "%s", mpd_info.artist.c_str()); - } else if (mpd_info.file.size()) { + } else if (static_cast(!mpd_info.file.empty()) != 0u) { snprintf(p, len, "%s", mpd_info.file.c_str()); } else { *p = 0; diff --git a/src/mysql.cc b/src/mysql.cc index 0676430d..8767a1ef 100644 --- a/src/mysql.cc +++ b/src/mysql.cc @@ -45,9 +45,9 @@ conky::simple_config_setting 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(); diff --git a/src/nc.cc b/src/nc.cc index c9b21f7b..2e785861 100644 --- a/src/nc.cc +++ b/src/nc.cc @@ -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(); } diff --git a/src/net_stat.cc b/src/net_stat.cc index 3d37058b..31dc61f5 100644 --- a/src/net_stat.cc +++ b/src/net_stat.cc @@ -28,10 +28,10 @@ */ #include "net_stat.h" -#include -#include #include #include +#include +#include #include "conky.h" #include "logging.h" #include "net/if.h" @@ -44,6 +44,9 @@ #include #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(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(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(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(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(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(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(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(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(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(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(&(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( + 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]); + } } diff --git a/src/netbsd.cc b/src/netbsd.cc index e87ee7b9..e2ee9154 100644 --- a/src/netbsd.cc +++ b/src/netbsd.cc @@ -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"); } diff --git a/src/nvidia.cc b/src/nvidia.cc index 49bab7b3..ed8b70a2 100644 --- a/src/nvidia.cc +++ b/src/nvidia.cc @@ -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); } } diff --git a/src/openbsd.cc b/src/openbsd.cc index c9f6d83a..8629eb70 100644 --- a/src/openbsd.cc +++ b/src/openbsd.cc @@ -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 -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); diff --git a/src/prioqueue.cc b/src/prioqueue.cc index bf0119f1..e0295893 100644 --- a/src/prioqueue.cc +++ b/src/prioqueue.cc @@ -31,9 +31,9 @@ * */ -#include /* INT_MAX */ -#include -#include +#include /* INT_MAX */ +#include +#include #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(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(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); } diff --git a/src/prioqueue.h b/src/prioqueue.h index 070b7571..9c00bbca 100644 --- a/src/prioqueue.h +++ b/src/prioqueue.h @@ -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 */ diff --git a/src/proc.cc b/src/proc.cc index 71f1900b..eaafd51b 100644 --- a/src/proc.cc +++ b/src/proc.cc @@ -28,9 +28,9 @@ */ #include "proc.h" -#include #include #include +#include #include #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(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(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 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 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 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 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 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 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(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(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(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 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 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 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 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 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 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 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 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 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 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 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); diff --git a/src/prss.cc b/src/prss.cc index ed278a7e..33787fd9 100644 --- a/src/prss.cc +++ b/src/prss.cc @@ -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 doc( - xmlReadMemory(xml_data.c_str(), xml_data.length(), "", NULL, + xmlReadMemory(xml_data.c_str(), xml_data.length(), "", nullptr, PARSE_OPTIONS), xmlFreeDoc); diff --git a/src/pulseaudio.cc b/src/pulseaudio.cc index 9add3bf7..72f19074 100644 --- a/src/pulseaudio.cc +++ b/src/pulseaudio.cc @@ -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) { diff --git a/src/pulseaudio.h b/src/pulseaudio.h index 35d79685..f1ee8058 100644 --- a/src/pulseaudio.h +++ b/src/pulseaudio.h @@ -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, diff --git a/src/read_tcpip.cc b/src/read_tcpip.cc index 719a25a1..55309476 100644 --- a/src/read_tcpip.cc +++ b/src/read_tcpip.cc @@ -27,19 +27,23 @@ * */ -#include #include #include #include -#include #include #include +#include #include +#include #include #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( + 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(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(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(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(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(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(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(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(obj->data.opaque); - if (!addr) return; + if (addr == nullptr) { + return; + } free_and_zero(obj->data.opaque); } diff --git a/src/scroll.cc b/src/scroll.cc index d9dc10ee..cdce85bd 100644 --- a/src/scroll.cc +++ b/src/scroll.cc @@ -26,13 +26,13 @@ * along with this program. If not, see . * */ -#include #include "conky.h" #include "core.h" #include "logging.h" #include "specials.h" #include "text_object.h" #include "x11.h" +#include /** * 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(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(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(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(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(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(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(obj->data.opaque); unsigned int j, colorchanges = 0, frontcolorchanges = 0, visibcolorchanges = 0, strend; unsigned int visiblechars = 0; char *pwithcolors; - std::vector buf(max_user_text.get(*state), (char)0); + std::vector buf(max_user_text.get(*state), static_cast(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(sd->start); j++) { + if (buf[j] == SPECIAL_CHAR) { + frontcolorchanges++; + } } - pwithcolors = - (char *)malloc(strlen(p) + 4 + colorchanges - visibcolorchanges); + pwithcolors = static_cast( + 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(obj->data.opaque); - if (!sd) return; + if (sd == nullptr) { + return; + } free_and_zero(sd->text); free_text_objects(obj->sub); diff --git a/src/semaphore.hh b/src/semaphore.hh index 5c716d1f..48180ff9 100644 --- a/src/semaphore.hh +++ b/src/semaphore.hh @@ -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; diff --git a/src/setting.cc b/src/setting.cc index fdf0a236..23237b7a 100644 --- a/src/setting.cc +++ b/src/setting.cc @@ -27,6 +27,7 @@ #include #include #include +#include #include namespace conky { @@ -34,7 +35,7 @@ namespace conky { namespace { typedef std::unordered_map settings_map; -typedef std::vector settings_vector; +using settings_vector = std::vector; /* * 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); } diff --git a/src/setting.hh b/src/setting.hh index 6436ac05..4aee9518 100644 --- a/src/setting.hh +++ b/src/setting.hh @@ -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() {} /* diff --git a/src/smapi.cc b/src/smapi.cc index 8edf19d6..59323752 100644 --- a/src/smapi.cc +++ b/src/smapi.cc @@ -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,,'"); - 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); diff --git a/src/solaris.cc b/src/solaris.cc index 59628f77..1b3cf776 100644 --- a/src/solaris.cc +++ b/src/solaris.cc @@ -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; } diff --git a/src/sony.cc b/src/sony.cc index 95d3bd80..98c5e424 100644 --- a/src/sony.cc +++ b/src/sony.cc @@ -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)); diff --git a/src/specials.cc b/src/specials.cc index e6ae26ec..0560a138 100644 --- a/src/specials.cc +++ b/src/specials.cc @@ -30,18 +30,18 @@ #ifdef BUILD_X11 #include "fonts.h" #endif /* BUILD_X11 */ -#include +#include #include "logging.h" #include "nc.h" #include "specials.h" #ifdef HAVE_SYS_PARAM_H #include #endif /* HAVE_SYS_PARAM_H */ +#include "colours.h" #include #include -#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(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(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(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(strrchr(args, '"'))) && _ptr != args) { + if (((_ptr = const_cast(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(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(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(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(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(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( + auto *graph = static_cast( 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(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(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(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(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(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(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(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; diff --git a/src/tailhead.cc b/src/tailhead.cc index 9820d324..900aed8c 100644 --- a/src/tailhead.cc +++ b/src/tailhead.cc @@ -27,11 +27,11 @@ * */ -#include #include -#include #include #include +#include +#include #include #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(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 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(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; } diff --git a/src/tcp-portmon.cc b/src/tcp-portmon.cc index d8b33829..843341ea 100644 --- a/src/tcp-portmon.cc +++ b/src/tcp-portmon.cc @@ -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 max_port_monitor_connections( "max_port_monitor_connections", 0, std::numeric_limits::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; } diff --git a/src/temphelper.cc b/src/temphelper.cc index ccc63dfc..84a3d03e 100644 --- a/src/temphelper.cc +++ b/src/temphelper.cc @@ -21,11 +21,11 @@ * */ #include "temphelper.h" -#include -#include -#include -#include #include +#include +#include +#include +#include #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(!(plen >= p_max_size)); } diff --git a/src/template.cc b/src/template.cc index dd207af2..fe173132 100644 --- a/src/template.cc +++ b/src/template.cc @@ -26,8 +26,8 @@ * along with this program. If not, see . * */ -#include -#include +#include +#include #include #include "conky.h" #include "logging.h" @@ -39,12 +39,12 @@ conky::simple_config_setting _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(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(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(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(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(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(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(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(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; } diff --git a/src/text_object.cc b/src/text_object.cc index 0e562d29..ec46103e 100644 --- a/src/text_object.cc +++ b/src/text_object.cc @@ -26,8 +26,8 @@ * */ #include "text_object.h" -#include -#include +#include +#include #include #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( + 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(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(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(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(*opaque == nullptr); +} void obj_be_plain_text(struct text_object *obj, const char *text) { obj->data.s = strdup(text); diff --git a/src/text_object.h b/src/text_object.h index ec211e44..6e879569 100644 --- a/src/text_object.h +++ b/src/text_object.h @@ -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 *); diff --git a/src/timeinfo.cc b/src/timeinfo.cc index b9563404..12b36b24 100644 --- a/src/timeinfo.cc +++ b/src/timeinfo.cc @@ -31,10 +31,10 @@ #include "timeinfo.h" -#include -#include -#include -#include +#include +#include +#include +#include #include "conky.h" #include "logging.h" #include "text_object.h" @@ -50,15 +50,16 @@ conky::simple_config_setting 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(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(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(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(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(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(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 { diff --git a/src/top.cc b/src/top.cc index 9f082f53..a6e6082b 100644 --- a/src/top.cc +++ b/src/top.cc @@ -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( + 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(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(va), + *b = static_cast(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(va), + *b = static_cast(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(va), + *b = static_cast(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(va), + *b = static_cast(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(pop_prio_elem(cpu_queue)); + } + if (top_mem != 0) { + mem[i] = static_cast(pop_prio_elem(mem_queue)); + } + if (top_time != 0) { + ptime[i] = static_cast(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(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 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(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(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(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(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(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(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(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); diff --git a/src/update-cb.cc b/src/update-cb.cc index 93d403f5..dfb0489c 100644 --- a/src/update-cb.cc +++ b/src/update-cb.cc @@ -25,8 +25,8 @@ #include "update-cb.hh" -#include #include +#include 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 diff --git a/src/update-cb.hh b/src/update-cb.hh index ab83374c..bdabd5d8 100644 --- a/src/update-cb.hh +++ b/src/update-cb.hh @@ -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), diff --git a/src/user.cc b/src/user.cc index 012cb173..6e24e532 100644 --- a/src/user.cc +++ b/src/user.cc @@ -29,9 +29,9 @@ #include -#include #include #include +#include #include #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); diff --git a/src/users.cc b/src/users.cc index 8d689ec8..ca451125 100644 --- a/src/users.cc +++ b/src/users.cc @@ -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)); diff --git a/src/weather.cc b/src/weather.cc index db14a721..6c0dd2c8 100644 --- a/src/weather.cc +++ b/src/weather.cc @@ -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"; diff --git a/src/x11.cc b/src/x11.cc index ffbcb313..ebce26b2 100644 --- a/src/x11.cc +++ b/src/x11.cc @@ -32,11 +32,11 @@ #include "conky.h" #include "logging.h" +#include "x11.h" #include #include #include #include -#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::Map conky::lua_traits::map = { std::pair window_hints_traits::convert( lua::state &l, int index, const std::string &name) { - typedef conky::lua_traits Traits; + using Traits = conky::lua_traits; lua::stack_sentry s(l); l.checkstack(1); @@ -273,7 +280,9 @@ std::pair window_hints_traits::convert( if (newpos > pos) { l.pushstring(hints.substr(pos, newpos - pos)); auto t = conky::lua_traits::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(!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(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(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(&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(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(&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(&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(&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(&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(&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(&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(&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(&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(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(&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(&sizes), 12); } } } #endif /* OWN_WINDOW */ #ifdef BUILD_XDBE -void xdbe_swap_buffers(void) { +void xdbe_swap_buffers() { if (use_xdbe.get(*state)) { XdbeSwapInfo swap; diff --git a/src/x11.h b/src/x11.h index 5cdaa031..35b716b2 100644 --- a/src/x11.h +++ b/src/x11.h @@ -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); diff --git a/src/xmms2.cc b/src/xmms2.cc index 457e084c..97f6e717 100644 --- a/src/xmms2.cc +++ b/src/xmms2.cc @@ -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;