Skip to content

Commit

Permalink
refactor(WMTheme): clean up detectOpenbox
Browse files Browse the repository at this point in the history
Simplify the code and implement stricter checking of xml contents.
  • Loading branch information
apocelipes authored and CarterLi committed Dec 19, 2023
1 parent 5ede47f commit 61485cb
Showing 1 changed file with 28 additions and 32 deletions.
60 changes: 28 additions & 32 deletions src/detection/wmtheme/wmtheme_linux.c
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include "wmtheme.h"
#include "common/io/io.h"
#include "common/properties.h"
#include "common/parsing.h"
#include "common/settings.h"
Expand Down Expand Up @@ -142,50 +143,45 @@ static bool detectOpenbox(const FFstrbuf* dePrettyName, FFstrbuf* themeOrError)
else
ffStrbufAppendS(&absolutePath, ".config/openbox/rc.xml");

char* line = NULL;
size_t len = 0;

FILE* file = fopen(absolutePath.chars, "r");
if(file == NULL)
FF_STRBUF_AUTO_DESTROY content = ffStrbufCreate();
if (!ffReadFileBuffer(absolutePath.chars, &content))
{
ffStrbufAppendF(themeOrError, "Couldn't open \"%s\"", absolutePath.chars);

ffStrbufAppendF(themeOrError, "Couldn't read \"%s\"", absolutePath.chars);
return false;
}

while(getline(&line, &len, file) != -1)
{
if(strstr(line, "<theme>") != 0)
break;
}
const char *themeStart = strstr(content.chars, "<theme>");
if (themeStart == NULL)
goto theme_not_found;

while(getline(&line, &len, file) != -1)
{
if(strstr(line, "<name>") != 0)
{
ffStrbufAppendS(themeOrError, line);
ffStrbufRemoveStrings(themeOrError, 2, (const char*[]) { "<name>", "</name>" });
ffStrbufTrimRight(themeOrError, '\n');
ffStrbufTrim(themeOrError, ' ');
break;
}
const char *themeEnd = strstr(themeStart, "</theme>");
if (__builtin_expect(themeEnd == NULL, false)) // very rare case
goto theme_not_found;

if(strstr(line, "</theme>") != 0) // sanity check
break;
}
const char *nameStart = strstr(themeStart, "<name>");
if (nameStart == NULL)
goto name_not_found;

if(line != NULL)
free(line);
const char *nameEnd = strstr(nameStart, "</name>");
if (nameEnd == NULL || nameEnd > themeEnd) // (nameEnd > themeEnd) means name is not a theme's child
goto name_not_found;

fclose(file);
nameStart += strlen("<name>");
ffStrbufAppendNS(themeOrError, (uint32_t)(nameEnd - nameStart), nameStart);
ffStrbufTrim(themeOrError, ' ');

if(themeOrError->length == 0)
{
ffStrbufAppendF(themeOrError, "Couldn't find theme name in \"%s\"", absolutePath.chars);
return false;
}
goto name_not_found;

return true;

theme_not_found:
ffStrbufAppendF(themeOrError, "Couldn't find theme node in \"%s\"", absolutePath.chars);
return false;

name_not_found:
ffStrbufAppendF(themeOrError, "Couldn't find theme name in \"%s\"", absolutePath.chars);
return false;
}

bool ffDetectWmTheme(FFstrbuf* themeOrError)
Expand Down

0 comments on commit 61485cb

Please sign in to comment.