~larryprice/ubuntu-app-launch/find-theme-icons

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/*
 * Copyright © 2016 Canonical Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 3, as published
 * by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranties of
 * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors:
 *     Larry Price <larry.price@canonical.com>
 */

#include "application-icon-finder.h"
#include <regex>

namespace ubuntu
{
namespace app_launch
{
namespace
{
constexpr auto HICOLOR_THEME_DIR = "/icons/hicolor/";
constexpr auto HICOLOR_THEME_FILE = "/icons/hicolor/index.theme";
constexpr auto APPLICATIONS_TYPE = "Applications";
constexpr auto SIZE_PROPERTY = "Size";
constexpr auto MAXSIZE_PROPERTY = "MaxSize";
constexpr auto THRESHOLD_PROPERTY = "Threshold";
constexpr auto FIXED_CONTEXT = "Fixed";
constexpr auto SCALABLE_CONTEXT = "Scalable";
constexpr auto THRESHOLD_CONTEXT = "Threshold";
constexpr auto CONTEXT_PROPERTY = "Context";
constexpr auto TYPE_PROPERTY = "Type";
constexpr auto DIRECTORIES_PROPERTY = "Directories";
constexpr auto ICON_THEME_KEY = "Icon Theme";
constexpr auto PIXMAPS_PATH = "/pixmaps/";
constexpr auto ICON_TYPES = {".png", ".svg", ".xpm"};

static const std::regex iconSizeDirname = std::regex("^(\\d+)x\\1$");
}  // anonymous namespace

IconFinder::IconFinder(std::string basePath)
    : _searchPaths(getSearchPaths(basePath))
    , _basePath(basePath)
{
}

/** Finds an icon in the search paths that we have for this path */
Application::Info::IconPath IconFinder::find(const std::string& iconName)
{
    if (iconName[0] == '/')  // explicit icon path received
    {
        return Application::Info::IconPath::from_raw(iconName);
    }

    /* Look in each directory slowly decreasing the size until we find
       an icon */
    auto size = 0;
    std::string iconPath;
    for (const auto& path : _searchPaths)
    {
        if (path.size > size)
        {
            auto foundIcon = findExistingIcon(path.path, iconName);
            if (!foundIcon.empty())
            {
                size = path.size;
                iconPath = foundIcon;
            }
        }
    }

    return Application::Info::IconPath::from_raw(iconPath);
}

/** Check to see if this is an icon name or an icon filename */
bool IconFinder::hasImageExtension(const char* filename)
{
    for (const auto& extension : ICON_TYPES)
    {
        if (g_str_has_suffix(filename, extension))
        {
            return true;
        }
    }
    return false;
}

/** Check in a given path if there is an existing file in it that satifies our name */
std::string IconFinder::findExistingIcon(const std::string& path, const std::string& iconName)
{
    std::string iconPath;

    /* If it already has an extension, only check that one */
    if (hasImageExtension(iconName.c_str()))
    {
        auto fullpath = g_build_filename(path.c_str(), iconName.c_str(), nullptr);
        if (g_file_test(fullpath, G_FILE_TEST_EXISTS))
        {
            iconPath = fullpath;
        }
        g_free(fullpath);
        return iconPath;
    }

    /* Otherwise check all the valid extensions to see if they exist */
    for (const auto& extension : ICON_TYPES)
    {
        auto fullpath = g_build_filename(path.c_str(), (iconName + extension).c_str(), nullptr);
        if (g_file_test(fullpath, G_FILE_TEST_EXISTS))
        {
            iconPath = fullpath;
            g_free(fullpath);
            break;
        }
        g_free(fullpath);
    }
    return iconPath;
}

/** Create a directory item if the directory exists */
std::list<IconFinder::ThemeSubdirectory> IconFinder::validDirectories(const std::string& basePath,
                                                                      gchar* directory,
                                                                      int size)
{
    std::list<IconFinder::ThemeSubdirectory> dirs;
    auto globalHicolorTheme = g_build_filename(basePath.c_str(), HICOLOR_THEME_DIR, directory, nullptr);
    if (g_file_test(globalHicolorTheme, G_FILE_TEST_EXISTS))
    {
        dirs.emplace_back(ThemeSubdirectory{std::string(globalHicolorTheme), size});
    }
    g_free(globalHicolorTheme);

    return dirs;
}

/** Take the data in a directory stanza and turn it into an actual directory */
std::list<IconFinder::ThemeSubdirectory> IconFinder::addSubdirectoryByType(std::shared_ptr<GKeyFile> themefile,
                                                                           gchar* directory,
                                                                           const std::string& basePath)
{
    GError* error = nullptr;
    auto gType = g_key_file_get_string(themefile.get(), directory, TYPE_PROPERTY, &error);
    if (error != nullptr)
    {
        g_error_free(error);
        return std::list<ThemeSubdirectory>{};
    }
    std::string type(gType);
    g_free(gType);

    if (type == FIXED_CONTEXT)
    {
        auto size = g_key_file_get_integer(themefile.get(), directory, SIZE_PROPERTY, &error);
        if (error != nullptr)
        {
            g_error_free(error);
        }
        else
        {
            return validDirectories(basePath, directory, size);
        }
    }
    else if (type == SCALABLE_CONTEXT)
    {
        auto size = g_key_file_get_integer(themefile.get(), directory, MAXSIZE_PROPERTY, &error);
        if (error != nullptr)
        {
            g_error_free(error);
        }
        else
        {
            return validDirectories(basePath, directory, size);
        }
    }
    else if (type == THRESHOLD_CONTEXT)
    {
        auto size = g_key_file_get_integer(themefile.get(), directory, SIZE_PROPERTY, &error);
        if (error != nullptr)
        {
            g_error_free(error);
        }
        else
        {
            auto threshold = g_key_file_get_integer(themefile.get(), directory, THRESHOLD_PROPERTY, &error);
            if (error != nullptr)
            {
                threshold = 2;  // threshold defaults to 2
                g_error_free(error);
            }
            return validDirectories(basePath, directory, size + threshold);
        }
    }
    return std::list<ThemeSubdirectory>{};
}

/** Parse a theme file's various stanzas for each directory */
std::list<IconFinder::ThemeSubdirectory> IconFinder::searchIconPaths(std::shared_ptr<GKeyFile> themefile,
                                                                     gchar** directories,
                                                                     const std::string& basePath)
{
    std::list<ThemeSubdirectory> subdirs;
    for (auto i = 0; directories[i] != nullptr; ++i)
    {
        GError* error = nullptr;
        auto context = g_key_file_get_string(themefile.get(), directories[i], CONTEXT_PROPERTY, &error);
        if (error != nullptr)
        {
            g_error_free(error);
            continue;
        }
        if (g_strcmp0(context, APPLICATIONS_TYPE) == 0)
        {
            auto newDirs = addSubdirectoryByType(themefile, directories[i], basePath);
            subdirs.splice(subdirs.end(), newDirs);
        }
        g_free(context);
    }
    return subdirs;
}

/** Try to get theme subdirectories using .theme file in the hicolor theme file
    if it exists */
std::list<IconFinder::ThemeSubdirectory> IconFinder::themeFileSearchPaths(const std::string& basePath)
{
    std::string themeFilePath = basePath + HICOLOR_THEME_FILE;
    GError* error = nullptr;
    auto themefile = std::shared_ptr<GKeyFile>(g_key_file_new(), g_key_file_free);
    g_key_file_load_from_file(themefile.get(), themeFilePath.c_str(), G_KEY_FILE_NONE, &error);
    if (error != nullptr)
    {
        g_debug("Unable to find Hicolor theme file: %s", themeFilePath.c_str());
        g_error_free(error);
        return std::list<ThemeSubdirectory>();
    }

    g_key_file_set_list_separator(themefile.get(), ',');
    auto directories =
        g_key_file_get_string_list(themefile.get(), ICON_THEME_KEY, DIRECTORIES_PROPERTY, nullptr, &error);
    if (error != nullptr)
    {
        g_debug("Hicolor theme file '%s' didn't have any directories", themeFilePath.c_str());
        g_error_free(error);
        return std::list<ThemeSubdirectory>();
    }

    auto iconPaths = searchIconPaths(themefile, directories, basePath);
    g_strfreev(directories);
    return iconPaths;
}

/** Look into a theme directory and see if we can use the subdirectories
    as icon folders. Sadly inefficient. */
std::list<IconFinder::ThemeSubdirectory> IconFinder::themeDirSearchPaths(const std::string& themeDir)
{
    std::list<IconFinder::ThemeSubdirectory> searchPaths;
    GError* error = nullptr;
    auto gdir = g_dir_open(themeDir.c_str(), 0, &error);

    if (error != nullptr)
    {
        g_debug("Unable to open directory '%s' becuase: %s", themeDir.c_str(), error->message);
        g_error_free(error);
        return searchPaths;
    }

    const gchar* dirname = nullptr;
    while ((dirname = g_dir_read_name(gdir)) != nullptr)
    {
        auto fullPath = g_build_filename(themeDir.c_str(), dirname, "apps", nullptr);
        /* Directories only */
        if (g_file_test(fullPath, G_FILE_TEST_IS_DIR))
        {
            if (g_strcmp0(dirname, "scalable") == 0)
            {
                /* We don't really know what to do with scalable here, let's
                   call them 256 images */
                searchPaths.emplace_back(IconFinder::ThemeSubdirectory{fullPath, 256});
                continue;
            }

            std::smatch match;
            std::string dirstr(dirname);
            /* We want it to match and have the same values for the first and second size */
            if (std::regex_match(dirstr, match, iconSizeDirname))
            {
                searchPaths.emplace_back(IconFinder::ThemeSubdirectory{fullPath, std::atoi(match[1].str().c_str())});
            }
        }
        g_free(fullPath);
    }

    g_dir_close(gdir);
    return searchPaths;
}

/** Gets all the search paths, from either a theme file or just
    looking at the directory. And possibly pixmaps as well */
std::list<IconFinder::ThemeSubdirectory> IconFinder::getSearchPaths(const std::string& basePath)
{
    std::list<IconFinder::ThemeSubdirectory> iconPaths;

    auto hicolorDir = g_build_filename(basePath.c_str(), HICOLOR_THEME_DIR, nullptr);
    if (g_file_test(hicolorDir, G_FILE_TEST_IS_DIR))
    {
        /* If the directory exists, it could have icons of unknown size */
        iconPaths.emplace_back(IconFinder::ThemeSubdirectory{hicolorDir, 1});

        /* Now see if we can get directories from a theme file */
        auto themeDirs = themeFileSearchPaths(basePath);
        if (themeDirs.size() > 0)
        {
            iconPaths.splice(iconPaths.end(), themeDirs);
        }
        else
        {
            /* If we didn't get from a theme file, we need to manually scan the directories */
            auto dirPaths = themeDirSearchPaths(hicolorDir);
            iconPaths.splice(iconPaths.end(), dirPaths);
        }
    }
    g_free(hicolorDir);

    /* Add the pixmaps path as a fallback if it exists */
    std::string pixmapsPath = basePath + PIXMAPS_PATH;
    if (g_file_test(pixmapsPath.c_str(), G_FILE_TEST_IS_DIR))
    {
        iconPaths.emplace_back(IconFinder::ThemeSubdirectory{pixmapsPath, 1});
    }

    // find icons sorted by size, highest to lowest
    iconPaths.sort([](const ThemeSubdirectory& lhs, const ThemeSubdirectory& rhs) { return lhs.size > rhs.size; });
    return iconPaths;
}

}  // namesapce app_launch
}  // namespace ubuntu