xaizek / vifm (License: GPLv2+) (since 2018-12-07)
Vifm is a file manager with curses interface, which provides Vi[m]-like environment for managing objects within file systems, extended with some useful ideas from mutt.
<root> / src / menus / media_menu.c (b5917cf5695c37a0e6577be88fbc95f598be7ce7) (11KiB) (mode 100644) [raw]
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 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
/* vifm
 * Copyright (C) 2018 xaizek.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY 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, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 */

#include "media_menu.h"

#include <stddef.h> /* NULL */
#include <stdlib.h> /* free() */
#include <string.h> /* strdup() */
#include <wchar.h> /* wcscmp() */

#include "../cfg/config.h"
#include "../compat/fs_limits.h"
#include "../compat/reallocarray.h"
#include "../modes/dialogs/msg_dialog.h"
#include "../ui/ui.h"
#include "../utils/fs.h"
#include "../utils/path.h"
#include "../utils/str.h"
#include "../utils/string_array.h"
#include "../utils/utils.h"
#include "../running.h"
#include "menus.h"

/* Example state of the menu:
 *
 *    Items                              Data            Action
 *
 *    /dev/sdc                                           mount /dev/sda3
 *    `-- (not mounted)                  m/dev/sda3      mount /dev/sda3
 *
 *    /dev/sdd {text}
 *    |-- /                              u/              unmount /
 *    `-- /root/tmp                      u/root/tmp      unmount /root/tmp
 *
 *    /dev/sde                                           unmount /media
 *    `-- /media                         u/media         unmount /media
 *
 * Additional keys:
 *  - r -- reload list
 *  - [ -- previous device
 *  - ] -- next device
 *  - m -- mount/unmount
 *
 * Behaviour on Enter:
 *  - navigate inside mount-point or,
 *  - mount device if there are no mount-points or,
 *  - do nothing and keep menu open
 */

/* Description of a single device. */
typedef struct
{
	char *device;   /* Device name in the system. */
	char *text;     /* Arbitrary text next to device name (can be NULL). */
	char **paths;   /* List of paths at which the device is mounted. */
	int path_count; /* Number of elements in the paths array. */
	int has_info;   /* Set when text is set via info=. */
}
media_info_t;

static int execute_media_cb(struct view_t *view, menu_data_t *m);
static KHandlerResponse media_khandler(struct view_t *view, menu_data_t *m,
		const wchar_t keys[]);
static int reload_list(menu_data_t *m);
static void output_handler(const char line[], void *arg);
static void free_info_array(void);
static void position_cursor(menu_data_t *m);
static const char * get_selected_data(menu_data_t *m);
static void path_get_decors(const char path[], FileType type,
		const char **prefix, const char **suffix);
static int mediaprg_mount(const char data[], menu_data_t *m);

/* List of media devices. */
static media_info_t *infos;
/* Number of elements in infos array. */
static int info_count;

int
show_media_menu(struct view_t *view)
{
	static menu_data_t m;
	menus_init_data(&m, view, strdup("Media"), strdup("No media found"));
	m.execute_handler = &execute_media_cb;
	m.key_handler = &media_khandler;

	if(reload_list(&m) != 0)
	{
		return 0;
	}

	position_cursor(&m);

	return menus_enter(&m, view);
}

/* Callback that is called when menu item is selected.  Return non-zero to stay
 * in menu mode and zero otherwise. */
static int
execute_media_cb(struct view_t *view, menu_data_t *m)
{
	const char *data = get_selected_data(m);
	if(data != NULL)
	{
		if(*data == 'u')
		{
			const char *path = data + 1;
			menus_goto_dir(view, path);
			return 0;
		}
		else if(*data == 'm')
		{
			(void)mediaprg_mount(data, m);
		}
	}
	return 1;
}

/* Menu-specific shortcut handler.  Returns code that specifies both taken
 * actions and what should be done next. */
static KHandlerResponse
media_khandler(struct view_t *view, menu_data_t *m, const wchar_t keys[])
{
	if(wcscmp(keys, L"r") == 0)
	{
		reload_list(m);
		menus_set_pos(m->state, m->pos);
		menus_partial_redraw(m->state);
		return KHR_REFRESH_WINDOW;
	}
	else if(wcscmp(keys, L"[") == 0)
	{
		int i = m->pos;
		while(i-- > 0)
		{
			if(m->data[i] == NULL && m->data[i + 1] != NULL)
			{
				menus_set_pos(m->state, i);
				menus_partial_redraw(m->state);
				break;
			}
		}
		return KHR_REFRESH_WINDOW;
	}
	else if(wcscmp(keys, L"]") == 0)
	{
		int i = m->pos;
		while(++i < m->len - 1)
		{
			if(m->data[i] == NULL && m->data[i + 1] != NULL)
			{
				menus_set_pos(m->state, i);
				menus_partial_redraw(m->state);
				break;
			}
		}
		return KHR_REFRESH_WINDOW;
	}
	else if(wcscmp(keys, L"m") == 0)
	{
		const char *data = get_selected_data(m);
		(void)mediaprg_mount(data, m);
		return KHR_REFRESH_WINDOW;
	}
	return KHR_UNHANDLED;
}

/* (Re)loads list of media devices into the menu.  Returns zero on success,
 * otherwise non-zero is returned (empty menu is not considered an error). */
static int
reload_list(menu_data_t *m)
{
	free_string_array(m->data, m->len);
	free_string_array(m->items, m->len);

	m->data = NULL;
	m->items = NULL;
	m->len = 0;

	if(cfg.media_prg[0] == '\0')
	{
		show_error_msg("Listing media devices",
				"'mediaprg' option must not be empty");
		return 1;
	}

	char *cmd = format_str("%s list", cfg.media_prg);
	if(process_cmd_output("Listing media", cmd, NULL, 0, 0, &output_handler,
				&m) != 0)
	{
		show_error_msgf("Listing media devices", "Unable to run: %s", cmd);
		free(cmd);
		return 1;
	}
	free(cmd);

	int i;
	/* The NULL check is for tests. */
	const int menu_rows = (menu_win != NULL ? (getmaxy(menu_win) + 1) - 3 : 100);
	int max_rows_with_blanks = info_count       /* Device lines. */
		                       + (info_count - 1) /* Blank lines. */;
	for(i = 0; i < info_count; ++i)
	{
		max_rows_with_blanks += infos[i].path_count > 0
		                      ? infos[i].path_count /* Mount-points. */
		                      : 1;                  /* "Not mounted" line. */
	}

	for(i = 0; i < info_count; ++i)
	{
		const char *prefix, *suffix;
		media_info_t *info = &infos[i];

		put_into_string_array(&m->data, m->len, NULL);

		path_get_decors(info->device, FT_BLOCK_DEV, &prefix, &suffix);
		m->len = put_into_string_array(&m->items, m->len,
				format_str("%s%s%s %s", prefix, info->device, suffix,
						info->text ? info->text : ""));

		if(info->path_count == 0)
		{
			put_into_string_array(&m->data, m->len, format_str("m%s", info->device));
			m->len = add_to_string_array(&m->items, m->len, "`-- (not mounted)");
		}
		else
		{
			int j;
			for(j = 0; j < info->path_count; ++j)
			{
				put_into_string_array(&m->data, m->len,
						format_str("u%s", info->paths[j]));

				path_get_decors(info->paths[j], FT_DIR, &prefix, &suffix);
				const char *path = (is_root_dir(info->paths[j]) && suffix[0] == '/')
				                 ? ""
				                 : info->paths[j];
				m->len = put_into_string_array(&m->items, m->len,
						format_str("%c-- %s%s%s", j + 1 == info->path_count ? '`' : '|',
								prefix, path, suffix));
			}
		}

		if(i != info_count - 1 && max_rows_with_blanks <= menu_rows)
		{
			put_into_string_array(&m->data, m->len, NULL);
			m->len = add_to_string_array(&m->items, m->len, "");
		}
	}

	free_info_array();

	return 0;
}

/* Implements process_cmd_output() callback that builds array of devices. */
static void
output_handler(const char line[], void *arg)
{
	if(skip_prefix(&line, "device="))
	{
		media_info_t *new_infos = reallocarray(infos, ++info_count, sizeof(*infos));
		if(new_infos != NULL)
		{
			infos = new_infos;
			media_info_t *info = &infos[info_count - 1];
			info->device = strdup(line);
			info->text = NULL;
			info->paths = NULL;
			info->path_count = 0;
			info->has_info = 0;
		}
	}
	else if(info_count > 0)
	{
		media_info_t *info = &infos[info_count - 1];
		if(skip_prefix(&line, "info="))
		{
			replace_string(&info->text, line);
			info->has_info = 1;
		}
		else if(skip_prefix(&line, "label=") && !info->has_info)
		{
			put_string(&info->text, format_str("[%s]", line));
		}
		else if(skip_prefix(&line, "mount-point="))
		{
			info->path_count = add_to_string_array(&info->paths, info->path_count,
					line);
		}
	}
}

/* Releases global data that collects information about media. */
static void
free_info_array(void)
{
	int i;
	for(i = 0; i < info_count; ++i)
	{
		media_info_t *info = &infos[i];
		free(info->device);
		free(info->text);
		free_string_array(info->paths, info->path_count);
	}
	free(infos);
	infos = NULL;
	info_count = 0;
}

/* Puts cursor position to a mount point that corresponds to current path if
 * possible. */
static void
position_cursor(menu_data_t *m)
{
	int i;
	for(i = 0; i < m->len; ++i)
	{
		if(m->data[i] != NULL && *m->data[i] == 'u' &&
				is_in_subtree(m->cwd, m->data[i] + 1, 1))
		{
			m->pos = i;
			break;
		}
	}
}

/* Retrieves decorations for path.  See ui_get_decors(). */
static void
path_get_decors(const char path[], FileType type, const char **prefix,
		const char **suffix)
{
	dir_entry_t entry = {};

	entry.name = get_last_path_component(path);
	/* Avoid memory allocation. */
	if(entry.name != path)
	{
		entry.name[-1] = '\0';
		entry.origin = entry.name;
	}
	else
	{
		entry.origin = (type == FT_BLOCK_DEV ? "/dev" : "/");
	}
	entry.type = type;
	entry.name_dec_num = -1;

	ui_get_decors(&entry, prefix, suffix);

	/* Restore original path. */
	if(entry.name != path)
	{
		entry.name[-1] = '/';
	}
}

/* Retrieves appropriate data for selected item in a human-friendly way. */
static const char *
get_selected_data(menu_data_t *m)
{
	const char *data = m->data[m->pos];
	if(data == NULL)
	{
		char *next_data      = (m->pos + 1 < m->len ? m->data[m->pos + 1] : NULL);
		char *next_next_data = (m->pos + 2 < m->len ? m->data[m->pos + 2] : NULL);
		if(next_data != NULL && next_next_data == NULL)
		{
			data = next_data;
		}
	}
	return data;
}

/* Executes "mount" or "unmount" command on data.  Returns non-zero if program
 * executed successfully and zero otherwise. */
static int
mediaprg_mount(const char data[], menu_data_t *m)
{
	if(data == NULL || (*data != 'm' && *data != 'u') || cfg.media_prg[0] == '\0')
	{
		return 1;
	}

	int error = 0;
	int mount = (*data == 'm');
	const char *path = data + 1;

	if(!mount)
	{
		/* Try to get out of mount point before trying to unmount it. */
		char cwd[PATH_MAX + 1];
		if(get_cwd(cwd, sizeof(cwd)) == cwd && is_in_subtree(cwd, path, 1))
		{
			char out_of_mount_path[PATH_MAX + 1];
			snprintf(out_of_mount_path, sizeof(out_of_mount_path), "%s/..", path);
			(void)vifm_chdir(out_of_mount_path);
		}
	}

	const char *action = (mount ? "mount" : "unmount");
	const char *description = (mount ? "Mounting" : "Unmounting");

	char *escaped_path = shell_arg_escape(path, curr_stats.shell_type);
	char *cmd = format_str("%s %s %s", cfg.media_prg, action, escaped_path);
	if(rn_shell(cmd, PAUSE_NEVER, 0, SHELL_BY_APP) == 0)
	{
		reload_list(m);
	}
	else
	{
		error = 1;
		show_error_msgf("Media operation error", "%s has failed", description);
	}
	free(escaped_path);
	free(cmd);

	menus_partial_redraw(m->state);
	return error;
}

/* vim: set tabstop=2 softtabstop=2 shiftwidth=2 noexpandtab cinoptions-=(0 : */
/* vim: set cinoptions+=t0 : */
Hints

Before first commit, do not forget to setup your git environment:
git config --global user.name "your_name_here"
git config --global user.email "your@email_here"

Clone this repository using HTTP(S):
git clone https://code.reversed.top/user/xaizek/vifm

Clone this repository using ssh (do not forget to upload a key first):
git clone ssh://rocketgit@code.reversed.top/user/xaizek/vifm

You are allowed to anonymously push to this repository.
This means that your pushed commits will automatically be transformed into a pull request:
... clone the repository ...
... make some changes and some commits ...
git push origin master