How do you get the icon, MIME type, and application associated with a file in the Linux Desktop?
Here is an example of using GLib/GIO to get the information you want.
#include <gio/gio.h>
#include <stdio.h>
int
main (int argc, char **argv)
{
g_thread_init (NULL);
g_type_init ();
if (argc < 2)
return -1;
GError *error;
GFile *file = g_file_new_for_path (argv[1]);
GFileInfo *file_info = g_file_query_info (file,
"standard::*",
0,
NULL,
&error);
const char *content_type = g_file_info_get_content_type (file_info);
char *desc = g_content_type_get_description (content_type);
GAppInfo *app_info = g_app_info_get_default_for_type (
content_type,
FALSE);
/* you'd have to use g_loadable_icon_load to get the actual icon */
GIcon *icon = g_file_info_get_icon (file_info);
printf ("File: %s\nDescription: %s\nDefault Application: %s\n",
argv[1],
desc,
g_app_info_get_executable (app_info));
return 0;
}
You can use the tools available from xdg for that, in particular xdg-mime query
.
To find out the filetype of e.g. a file index.html
you would
$ xdg-mime query filetype index.html
This will return the mimetype. To query what application is associated with that mimetye use e.g.
$ xdg-mime query default text/html
This returns epiphany.desktop
here, i.e. $APPNAME.desktop
, so it is easy to get the application name from it. If you would just want to open the file in the default app you could of course just run
$ xdg-open index.html
which would fire up epiphany.
Query functions for icon resources do not seem to be available in xdg-utils
, but you could write a small python script using pyxdg that offers tons of additional functionality, too.
For C bindings you will probably need to have a look into the portland code linked on the xdg page.
EDIT:
Concerning libmagic
and friends, you will need to decide on your preferences: While libmagic seems to be more complete (and accurate) in terms of coverage for filetypes, it does not care at all about default applications or icons. It also does not provide you with tools to install extra mimetypes.
In Qt >= 4.6, there is a new function for X11 systems
QIcon QIcon::fromTheme ( const QString & name, const QIcon & fallback = QIcon() ) [static]
You can use this function. Documentation here / (Qt 5)