xaizek / pms (License: GPLv3+) (since 2018-12-07)
Older version of Practical Music Search written in C++.
<root> / src / pms.cpp (c7a4e3682d15eac0cbd1927d794f33fbfec65b4c) (34KiB) (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 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
/* vi:set ts=8 sts=8 sw=8 noet:
 *
 * PMS	<<Practical Music Search>>
 * Copyright (C) 2006-2015  Kim Tore Jensen
 *
 * 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 3 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, see <http://www.gnu.org/licenses/>.
 *
 *
 * pms.cpp - The PMS main class
 *
 */

#include "pms.h"
#include "zeromq.h"

#include <mpd/client.h>
#include <unistd.h>
#include <zmq.h>
#include <time.h>

/* Maximum time to spend waiting for events in main loop */
#define MAIN_LOOP_INTERVAL 1000

using namespace std;

Pms *		pms;


/*
 * 1..2..3..
 */
int main(int argc, char *argv[])
{
	int		exitcode;

	pms = new Pms(argc, argv);
	if (!pms)
	{
		printf("Not enough memory, aborting.\n");
		return PMS_EXIT_LOMEM;
	}

	exitcode = pms->init();
	if (exitcode == 0)
	{
		exitcode = pms->main();
	}
	delete pms;
	return exitcode;	
}

/**
 * Return the time difference between two timespec structs.
 */
struct timespec difftime(struct timespec start, struct timespec end)
{
	struct timespec temp;

	if ((end.tv_nsec - start.tv_nsec) < 0) {
		temp.tv_sec = end.tv_sec - start.tv_sec - 1;
		temp.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec;
	} else {
		temp.tv_sec = end.tv_sec - start.tv_sec;
		temp.tv_nsec = end.tv_nsec - start.tv_nsec;
	}

	return temp;
}

/**
 * MPD IDLE thread. Reads the reply from MPD's IDLE command, and makes sure the
 * main thread gets to know about it.
 */
void *
idle_thread_main(void * zeromq_context)
{
	enum mpd_idle idle_reply;
	void * socket;
	int rc;

	socket = zmq_socket(zeromq_context, ZMQ_REP);
	assert(socket != NULL);

	rc = zmq_bind(socket, ZEROMQ_SOCKET_IDLE);
	assert(rc == 0);

	do {
		/* Receive from main thread */
		rc = zmq_recv(socket, NULL, 0, 0);
		if (rc == -1) {
			if (errno == EINTR) {
				continue;
			}
			abort();
		}

		/* Receive IDLE reply */
		pms->log(MSG_DEBUG, 0, "Waiting for IDLE reply from server...\n");
		idle_reply = mpd_recv_idle(pms->conn->h(), true);
		pms->log(MSG_DEBUG, 0, "IDLE reply received from server, code = %d\n", idle_reply);

		/* Send reply to main thread */
		while(true) {
			rc = zmq_send(socket, (void *)&idle_reply, sizeof(enum mpd_idle *), 0);
			if (rc == -1) {
				if (errno == EINTR) {
					continue;
				}
				abort();
			}
			break;
		}

	} while(1);

	return NULL;
}

/**
 * Input thread. Handles all user input and makes sure the
 * main thread gets to know about it.
 */
void *
input_thread_main(void * zeromq_context)
{
	wchar_t ch;
	void * socket;
	int rc;

	socket = zmq_socket(zeromq_context, ZMQ_PUB);
	assert(socket != NULL);

	rc = zmq_connect(socket, ZEROMQ_SOCKET_INPUT);
	assert(rc == 0);

	do {
		/* Poll for user input */
		pms->log(MSG_DEBUG, 0, "Waiting for input keystroke from ncurses...\n");
		ch = pms->input->get_keystroke();
		pms->log(MSG_DEBUG, 0, "Keystroke registered: chr(%d) = '%c'\n", ch, ch);

		/* Send keystroke to main thread */
		rc = zmq_send(socket, (void *)&ch, sizeof(wchar_t *), 0);
		if (rc == -1) {
			if (errno == EINTR) {
				continue;
			}
			abort();
		}

	} while(1);

	return NULL;
}

/*
 * Init
 */
Pms::Pms(int c, char **v)
{
	argc = c;
	argv = v;
	disp = NULL;
}

/*
 * Unit
 */
Pms::~Pms()
{
}

struct timespec
Pms::get_clock()
{
	struct timespec now;

	if (clock_gettime(CLOCK_MONOTONIC, &now) != 0) {
		perror("Failed to increase internal timer");
		abort();
	}

	return now;
}

/**
 * Check if there is an MPD IDLE event on the ZeroMQ socket.
 * Set pending flags on the Control class, and sets real idle status.
 *
 * Returns true if there was an IDLE event, false if none.
 */
bool
Pms::run_has_idle_events()
{
	enum mpd_idle idle_reply;

	if (!zeromq->has_idle_events()) {
		return false;
	}

	idle_reply = zeromq->get_idle_events();
	comm->set_mpd_idle_events(idle_reply);
	comm->set_is_idle(false);
	timer_elapsed = get_clock();

	return true;
}

/**
 * Check if currently playing song has changed since last call.
 *
 * Returns true if song has changed, false if not.
 */
bool
Pms::song_changed()
{
	Song * song;
	static song_t last_song_id = MPD_SONG_NO_ID;
	song_t current_song_id;
	bool rc;

	song = cursong();
	if (song) {
		current_song_id = song->id;
	} else {
		current_song_id = MPD_SONG_NO_ID;
	}

	rc = (current_song_id != last_song_id);

	last_song_id = current_song_id;

	return rc;
}

/**
 * Center the cursor on the currently playing song.
 */
void
Pms::run_cursor_follow_playback()
{
	pms_window * win;

	win = disp->findwlist(comm->activelist());
	if (!win) {
		return;
	}

	setwin(win);
	win->gotocurrent();
}

/*
 * Connection and main loop
 */
int
Pms::main()
{
	string			t_str;
	pms_pending_keys	pending = PEND_NONE;
	char			pass[512] = "";
	bool			songchanged = false;
	time_t			timer = 0;
	int			rc;
	bool need_init_follow_playback = true;

	/* Error codes returned from MPD */
	enum mpd_error		error;
	enum mpd_server_error	server_error;

	/* Connection */
	printf(_("Connecting to host %s, port %ld..."), options->get_string("host").c_str(), options->get_long("port"));

	if (conn->connect() != MPD_ERROR_SUCCESS)
	{
		printf(_("failed.\n"));
		printf("%s\n", mpd_connection_get_error_message(conn->h()));

		return PMS_EXIT_CANTCONNECT;
	}

	printf(_("connected.\n"));

	/* Password? */
	if (options->get_string("password").size() > 0)
	{
		printf(_("Sending password..."));
		if (comm->sendpassword(options->get_string("password"))) {
			printf(_("password accepted.\n"));
		} else {
			printf(_("wrong password.\n"));
			conn->clear_error();
		}
	}

	do {
		if (!comm->get_available_commands()) {
			printf(_("Failed to get a list of available commands, retrying...\n"));
			conn->clear_error();
			sleep(1);
			continue;
		}

		if (comm->authlevel() & AUTH_READ) {
			break;
		}

		printf(_("This mpd server requires a password.\n"));
		printf(_("Password: "));

		fgets(pass, 512, stdin) ? 1 : 0; //ternary here is a hack to get rid of a warn_unused_result warning
		if (pass[strlen(pass)-1] == '\n') {
			pass[strlen(pass)-1] = '\0';
		}

		options->set_string("password", pass);
		if (!comm->sendpassword(pass)) {
			printf(_("Wrong password, try again.\n"));
			conn->clear_error();
		}
	} while(true);

	printf(_("Successfully logged in.\n"));

	_shutdown = false;
	if (!disp->init())
	{
		printf(_("Can't initialize display!\n"));
		return PMS_EXIT_NODISPLAY;
	}

	/* Workaround for buggy ncurses clearing the screen on first getch() */
	//getch();

	/* Set up library and playlist windows */
	playlist = disp->create_playlist();
	library = disp->create_playlist();

	assert(playlist != NULL);
	assert(library != NULL);

	playlist->settitle(_("Playlist"));
	library->settitle(_("Library"));
	playlist->list = comm->playlist();
	library->list = comm->library();

	playlist->set_column_size();
	library->set_column_size();

	connect_window_list();

	/* Focus startup list */
	comm->activatelist(comm->playlist());
	t_str = options->get_string("startuplist");
	if (t_str == "library")
	{
		comm->activatelist(comm->library());
	}
	else if (t_str.size() > 0 && t_str != "playlist")
	{
		comm->activatelist(comm->findplaylist(t_str));
	}
	disp->activate(disp->findwlist(comm->activelist()));

	disp->forcedraw();
	disp->refresh();

	/* Set up inter-thread communication */
	zeromq = new ZeroMQ();
	zeromq->start_thread_idle(idle_thread_main);
	zeromq->start_thread_input(input_thread_main);

	/* Reset all clocks */
	timer_now = get_clock();
	timer_elapsed = get_clock();

	/*
	 * Main loop
	 * FIXME: reduce the size of this behemoth
	 */
	do
	{
		/* Set timer */
		timer_now = get_clock();

		/* For debugging the main loop */
		log(MSG_DEBUG, 0, "--> Main loop iteration, clock = %ld.%ld\n", timer_now.tv_sec, timer_now.tv_nsec);

		/* Test if some error has occurred */
		if ((error = mpd_connection_get_error(conn->h())) != MPD_ERROR_SUCCESS) {

			log(MSG_STATUS, STERR, "MPD error: %s", mpd_connection_get_error_message(conn->h()));

			/* Try to recover from error. If the error is
			 * non-recoverable, reconnect to the MPD server.
			 */
			if (!mpd_connection_clear_error(conn->h())) {

				/* FIXME: gradually increase connection attempts? */
				/* FIXME: use reconnectdelay setting */
				/* FIXME: separate thread */
				sleep(1);
				conn->connect();
				continue;
			}
		}

		/* Increase time elapsed. */
		if (comm->status()->state == MPD_STATE_PLAY) {
			timer_tmp = difftime(timer_elapsed, timer_now);
			comm->status()->increase_time_elapsed(timer_tmp);
			disp->topbar->wantdraw = true;
		}
		timer_elapsed = get_clock();

		/* Run any pending updates */
		if (!comm->run_pending_updates()) {
			log(MSG_DEBUG, 0, "Failed running pending updates, MPD error follows in next main loop iteration\n");
			continue;
		}

		/* Library updates triggers re-calculation of column sizes,
		 * triggers draw, etc. */
		/* FIXME: move responsibilities? */
		if (comm->has_finished_update(MPD_IDLE_DATABASE)) {
			log(MSG_STATUS, STOK, _("Library has been updated."));
			disp->actwin()->wantdraw = true;
			library->list->sort(options->get_string("sort"));
			library->set_column_size();
			connect_window_list();
			comm->clear_finished_update(MPD_IDLE_DATABASE);
		}

		/* Playlist updates triggers re-calculation of column sizes,
		 * triggers draw, etc. */
		/* FIXME: move responsibilities? */
		if (comm->has_finished_update(MPD_IDLE_PLAYLIST)) {
			disp->actwin()->wantdraw = true;
			playlist->set_column_size();
			comm->clear_finished_update(MPD_IDLE_PLAYLIST);
		}

		/* Draw topbar on mixer update. */
		if (comm->has_finished_update(MPD_IDLE_MIXER)) {
			disp->topbar->wantdraw = true;
			comm->clear_finished_update(MPD_IDLE_MIXER);
		}

		/* Draw statusbar and topbar on player update. */
		if (comm->has_finished_update(MPD_IDLE_PLAYER)) {

			/* Shell command when song finishes */
			/* FIXME: move into separate function */
			if (comm->status()->state == MPD_STATE_STOP && pending != PEND_STOP) {
				if (options->get_string("onplaylistfinish").size() > 0 && cursong() && cursong()->pos == comm->playlist()->end()) {
					log(MSG_CONSOLE, STOK, _("Reached end of playlist, running automation command: %s"), options->get_string("onplaylistfinish").c_str());
					int code = system(options->get_string("onplaylistfinish").c_str());
				}
			}

			/* Execute 'cursor follows playback'. */
			if (song_changed() && (need_init_follow_playback || options->get_bool("followplayback"))) {
				run_cursor_follow_playback();
				need_init_follow_playback = false;
			}

			disp->topbar->wantdraw = true;
			disp->actwin()->wantdraw = true;
			drawstatus();
			comm->clear_finished_update(MPD_IDLE_PLAYER);
		}

		/* Draw topbar on options update. */
		if (comm->has_finished_update(MPD_IDLE_OPTIONS)) {
			disp->topbar->wantdraw = true;
			comm->clear_finished_update(MPD_IDLE_OPTIONS);
		}

		/* Reset status */
		if (needs_statusbar_reset()) {
			drawstatus();
		}

		/* Redraw the screen. */
		/* FIXME: where to put this? */
		if (mediator->changed("redraw")) {
			disp->forcedraw();
		} else {
			disp->draw();
		}
		disp->refresh();


		/**
		 * Start IDLE mode and polling. Keep this code at the end of
		 * the main loop.
		 */

		/* Ensure that we are in IDLE mode. */
		if (!comm->is_idle()) {
			if (!comm->idle()) {
				continue;
			}
			zeromq->continue_idle();
		}

		/* Block until events received or timeout reached. */
		zeromq->poll_events(MAIN_LOOP_INTERVAL);

		/* Process events from the IDLE socket. */
		run_has_idle_events();

		/* Process events from the input socket. */
		if (zeromq->has_input_events()) {
			zeromq->get_input_events();
			pending = input->dispatch();
			if (pending != PEND_NONE) {
				handle_command(pending);
			}
		}

		/* Draw XTerm window title */
		/* FIXME: only draw when needed */
		disp->set_xterm_title();

		/* Progress to next song if applicable, and make sure we are
		 * synched with IDLE events before doing it. */
		if (!comm->has_pending_updates()) {
			progress_nextsong();
		}

		/* Check out mediator events */
		/* FIXME: implement this functionality with ZeroMQ */
		if (mediator->changed("setting.sort"))
			comm->library()->sort(options->get_string("sort"));
		else if (mediator->changed("setting.ignorecase"))
			comm->library()->sort(options->get_string("sort"));
		else if (mediator->changed("setting.columns"))
			disp->actwin()->set_column_size();
		else if (mediator->changed("setting.mouse"))
			disp->setmousemask();
		else if (mediator->changed("redraw.topbar"))
			disp->resized();
		else if (mediator->changed("topbarvisible"))
			disp->resized();
		else if (mediator->changed("topbarborders"))
			disp->resized();
		else if (mediator->changed("topbarspace"))
			disp->resized();
		else if (mediator->changed("columnspace"))
			disp->resized();
		else if (mediator->changed("setting.topbarclear"))
		{
			if (options->get_bool("topbarclear"))
				options->topbar.clear();
		}
	}
	while (!_shutdown);

	log(MSG_CONSOLE, STOK, _("Shutting down program.\n"));

	delete disp;
	delete comm;
	delete conn;

	/* Unclutter the prompt */
	printf("\n");

	return PMS_EXIT_SUCCESS;
}

/*
 * Set up neccessary variables
 */
int			Pms::init()
{
	string			str;
	vector<string> *	tok;

	int			exitcode = PMS_EXIT_SUCCESS;
	char *			host;
	char *			port;
	char *			password;
	const char *		charset = NULL;
	
	/* Internal pointers */
	msg = new Message();
	mediator = new Mediator();
	interface = new Interface();
	formatter = new Formatter();

	/* Setup locales and internationalization */
	setlocale(LC_ALL, "");
	setlocale(LC_CTYPE, "");
	g_get_charset(&charset);
	bindtextdomain(GETTEXT_PACKAGE, LOCALE_DIR);
	bind_textdomain_codeset(GETTEXT_PACKAGE, charset);
	textdomain(GETTEXT_PACKAGE);

	/* Print program header */
	printf("%s v%s\n%s\n", PMS_NAME, PACKAGE_VERSION, PMS_COPYRIGHT);

	/* Read important environment variables */
	host = getenv("MPD_HOST");
	port = getenv("MPD_PORT");
	password = getenv("MPD_PASSWORD");

	/* Set up field types */
	fieldtypes = new Fieldtypes();
	fieldtypes->add("num", _("#"), FIELD_NUM, 0, NULL);
	fieldtypes->add("file", _("Filename"), FIELD_FILE, 0, sort_compare_file);
	fieldtypes->add("artist", _("Artist"), FIELD_ARTIST, 0, sort_compare_artist);
	fieldtypes->add("artistsort", _("Artist sort name"), FIELD_ARTISTSORT, 0, sort_compare_artistsort);
	fieldtypes->add("albumartist", _("Album artist"), FIELD_ALBUMARTIST, 0, sort_compare_albumartist);
	fieldtypes->add("albumartistsort", _("Album artist sort name"), FIELD_ALBUMARTISTSORT, 0, sort_compare_albumartistsort);
	fieldtypes->add("title", _("Title"), FIELD_TITLE, 0, sort_compare_title);
	fieldtypes->add("album", _("Album"), FIELD_ALBUM, 0, sort_compare_album);
	fieldtypes->add("track", _("Track"), FIELD_TRACK, 6, sort_compare_track);
	fieldtypes->add("trackshort", _("No"), FIELD_TRACKSHORT, 3, sort_compare_track);
	fieldtypes->add("length", _("Length"), FIELD_TIME, 7, sort_compare_length);
	fieldtypes->add("date", _("Date"), FIELD_DATE, 11, sort_compare_date);
	fieldtypes->add("year", _("Year"), FIELD_YEAR, 5, sort_compare_year);
	fieldtypes->add("name", _("Name"), FIELD_NAME, 0, sort_compare_name);
	fieldtypes->add("genre", _("Genre"), FIELD_GENRE, 0, sort_compare_genre);
	fieldtypes->add("composer", _("Composer"), FIELD_COMPOSER, 0, sort_compare_composer);
	fieldtypes->add("performer", _("Performer"), FIELD_PERFORMER, 0, sort_compare_performer);
	fieldtypes->add("disc", _("Disc"), FIELD_DISC, 5, sort_compare_disc);
	fieldtypes->add("comment", _("Comment"), FIELD_COMMENT, 0, sort_compare_comment);

	/* Set up default bindings */
	if (!init_commandmap())
	{
		return PMS_EXIT_NOCOMMAND;
	}
	options = new Options();
	init_default_keymap();

	/* Our configuration */
	config = new Configurator(options, bindings);

	/* Some default options */
	options->set_string("host", (host ? host : "127.0.0.1"));
	if (!password && host)
	{
		tok = splitstr(host, "@");
		if (tok->size() == 2)
		{
			options->set_string("host", (*tok)[0]);
			options->set_string("password", (*tok)[1]);
		}
		delete tok;
	}
	if (options->get_string("password").size() == 0)
	{
		options->set_string("password", (password ? password : ""));
	}
	options->set_long("port", (port ? atoi(port) : 6600));

	if (options->get_long("port") <= 0 || options->get_long("port") > 65535)
	{
		printf(_("Error: port number in environment variable MPD_PORT must be from 1-65535\n"));
		return PMS_EXIT_BADARGS;
	}

	/* Parse command-line */
	if (parse_args(argc, argv) == false)
	{
		return PMS_EXIT_BADARGS;
	}

	if (!config->loadconfigs())
		return PMS_EXIT_CONFIGERR;

	/* Seed random number generator */
	srand(time(NULL));

	/* Setup some important stuff */
	conn	= new Connection(options->get_string("host"), options->get_long("port"), options->get_long("mpd_timeout") * 1000);
	comm	= new Control(conn);
	disp	= new Display(comm);
	input	= new Input();
	if (!conn || !comm || !disp || !input)
		return PMS_EXIT_LOMEM;

	/* Initialization finished */
	return PMS_EXIT_SUCCESS;
}






/*
 * Converts long to string
 */
string			Pms::tostring(long number)
{
	ostringstream s;
	s << number;
	return s.str();
}

/*
 * Converts size_t to string
 */
string			Pms::tostring(size_t number)
{
	ostringstream s;
	s << number;
	return s.str();
}

/*
 * Converts int to string
 */
string			Pms::tostring(int number)
{
	ostringstream s;
	s << number;
	return s.str();
}

/**
 * Convert a const char * to string
 */
string
Pms::tostring(const char *src)
{
	return src ? src : "";
}

/*
 * Split a string into tokens
 */
vector<string> *	Pms::splitstr(string str, string delimiter)
{
	vector<string> *	tokens = new vector<string>;

	string::size_type last	= str.find_first_not_of(delimiter, 0);
	string::size_type pos	= str.find_first_of(delimiter, last);

	while (string::npos != pos || string::npos != last)
	{
		tokens->push_back(str.substr(last, pos - last));
		last = str.find_first_not_of(delimiter, pos);
		pos = str.find_first_of(delimiter, last);
	}
	
	return tokens;
}

/*
 * Join tokens into a string
 */
string			Pms::joinstr(vector<string> * source, vector<string>::iterator start, vector<string>::iterator end, string delimiter)
{
	string			dest = "";

	while (start != source->end())
	{
		dest += *start;

		if (start == end)
			break;

		if (++start != end)
		{
			dest += delimiter;
		}
	}
	
	return dest;
}

/*
 * Formats seconds into the format Dd H:MM:SS.
 */
string			Pms::timeformat(int seconds)
{
	static const int	day	= (60 * 60 * 24);
	static const int	hour	= (60 * 60);
	static const int	minute	= 60;

	int		i;
	string		s = "";

	/* No time */
	if (seconds < 0)
	{
		s = "--:--";
		return s;
	}

	/* days */
	if (seconds >= day)
	{
		i = seconds / day;
		s = Pms::tostring(i) + "d ";
		seconds %= day;
	}

	/* hours */
	if (seconds >= hour)
	{
		i = seconds / hour;
		s += zeropad(i, 1) + ":";
		seconds %= hour;
	}

	/* minutes */
	i = seconds / minute;
	s = s + zeropad(i, 2) + ":";
	seconds %= minute;

	/* seconds */
	s += zeropad(seconds, 2);

	return s;
}

/*
 * Return "song" or "songs" based on plural or not
 */
string			Pms::pluralformat(unsigned int i)
{
	if (i == 1)
		return _("song");
	else
		return _("songs");
}
/*
 * Pad integer with zeroes up to target length
 */
string			Pms::zeropad(int i, unsigned int target)
{
	string s;
	s = Pms::tostring(i);
	while(s.size() < target)
		s = '0' + s;
	return s;
}

/*
 * Replaces % with %%
 */
string			Pms::formtext(string text)
{
	string::const_iterator	i;
	string			nutext;

	i = text.begin();
	nutext.clear();

	while (i != text.end())
	{
		nutext += *i;
		if (*i == '%')
			nutext += *i;
		++i;
	}

	return nutext;
}

/*
 * Return true if the terminal supports Unicode
 */
bool			Pms::unicode()
{
	const char *		charset = NULL;

	g_get_charset(&charset);
	return strcmp(charset, "UTF-8") == 0;
}










/*
 * Run a shell command
 *
 * FIXME: perhaps this command should be within Interface class?
 * TODO: add %artist% tags through the field pattern parser: meaning %file% -> filename, not % -> filename
 *	...but current implementation is nice and vim-like
 */
bool			Pms::run_shell(string cmd)
{
	string				search;
	string				replace;
	string::size_type		pos;
	int				i;
	Songlist *			list;
	char				c;

	msg->clear();

	/*
	 * %: path to current song, not enclosed in quotes
	 */
	if (cursong())
	{
		search = "%";
		replace = options->get_string("libraryroot");
		replace += cursong()->file;
		pos = 0;
		while ((pos = cmd.find(search, pos)) != string::npos)
		{
			if (pos == 0 || cmd[pos - 1] != '\\')
				cmd.replace(pos, search.size(), replace);
			pos++;
		}
	}

	/*
	 * ##: path to each song in selection (or each song on the current 
	 * playlist if there is no selection), each enclosed with doublequotes 
	 * and separated by spaces
	 */
	list = disp->actwin()->plist();
	search = "##";
	if (cmd.find(search, 0) != string::npos && list && list->size())
	{
		replace = "";
		for (i = 0; i < list->size(); i++)
		{
			if (!list->selection.size || list->song(i)->selected)
			{
				replace += options->get_string("libraryroot");
				replace += list->song(i)->file;
				replace += "\" \"";
			}
		}
		if (replace.size() > 0)
		{
			replace = "\"" + replace.substr(0, replace.size() - 2);
			pos = 0;
			while ((pos = cmd.find(search, pos)) != string::npos)
			{
				if (pos == 0 || cmd[pos - 1] != '\\')
					cmd.replace(pos, search.size(), replace);
				pos++;
			}
		}
	}

	/*
	 * #: path to song the cursor is on, not enclosed in quotes
	 */
	if (disp->cursorsong())
	{
		search = "#";
		replace = options->get_string("libraryroot");
		replace += disp->cursorsong()->file;
		pos = 0;
		while ((pos = cmd.find(search, pos)) != string::npos)
		{
			if (pos == 0 || cmd[pos - 1] != '\\')
				cmd.replace(pos, search.size(), replace);
			pos++;
		}
	}

	//pms->log(MSG_DEBUG, 0, "running shell command '%s'\n", cmd.c_str());
	endwin();

	msg->code = system(cmd.c_str());
	msg->code = WEXITSTATUS(msg->code);

	pms->log(MSG_DEBUG, 0, "Shell returned %d\n", msg->code);
	if (msg->code != 0)
		printf(_("\nShell returned %d\n"), msg->code);

	printf(_("\nPress ENTER to continue"));
	fflush(stdout);
	{
		/* soak up return value to suppress warning */
		int key = scanf("%c", &c);
	}

	reset_prog_mode();
	refresh();

	return true;
}

/*
 * Returns the currently playing song
 */
Song *			Pms::cursong()
{
	assert(comm != NULL);
	return comm->song();
}

/* 
 * Reset status to its natural state.
 */
void
Pms::drawstatus()
{
	if (input->mode() == INPUT_JUMP) {
		log(MSG_STATUS, STOK, "/%s", formtext(input->text).c_str());
	} else if (input->mode() == INPUT_FILTER) {
		log(MSG_STATUS, STOK, ":g/%s", formtext(input->text).c_str());
	} else if (input->mode() == INPUT_COMMAND) {
		log(MSG_STATUS, STOK, ":%s", formtext(input->text).c_str());
	} else {
		log(MSG_STATUS, STOK, "%s", playstring().c_str());
	}

	/* Do not redraw statusbar anymore */
	timer_statusbar.tv_sec = 0;
	timer_statusbar.tv_nsec = 0;
}

/**
 * Determine whether the statusbar text should be reset to its natural state.
 *
 * Returns true if the statusbar is due for an update, false if not.
 */
bool
Pms::needs_statusbar_reset()
{
	/* Check if redraw is disabled */
	if (timer_statusbar.tv_sec == 0 && timer_statusbar.tv_nsec == 0) {
		return false;
	}

	timer_tmp = difftime(timer_statusbar, timer_now);
	return (timer_tmp.tv_sec >= options->get_long("resetstatus"));
}

/*
 * Return a textual description on how song progression works.
 *
 * FIXME: this function is a mess. De-duplicate and use common code for this
 * function and progress_nextsong().
 */
string
Pms::playstring()
{
	string		s;
	string		list_name = "<unknown>";
	bool		is_last_in_playlist;
	bool		playlist_is_active;
	bool		library_is_active;
	Mpd_status *	status;

	status = comm->status();

	assert(status != NULL);

	if (!conn->connected()) {
		s = "Not connected.";
		return s;
	}

	if (status->state == MPD_STATE_STOP || !cursong()) {
		s = "Stopped.";
		return s;
	}

	if (status->state == MPD_STATE_PAUSE) {
		s = "Paused...";
		return s;
	}

	if (comm->activelist()) {
		list_name = comm->activelist()->filename;
	}

	playlist_is_active = (comm->activelist() == comm->playlist());
	library_is_active = (comm->activelist() == comm->library());

	/* FIXME: playlist should give the correct name in a name() function */
	if (list_name.size() == 0) {
		if (playlist_is_active) {
			list_name = "playlist";
		} else if (library_is_active) {
			list_name = "library";
		}
	}

	s = "Playing ";

	if (status->consume) {
		s += "and consuming ";
	}

	if (status->random) {
		s += "random songs from playlist.";
		return s;
	}

	if (status->single) {
		if (status->repeat && !status->consume) {
			s += "the current song repeatedly.";
		} else {
			s += "this song, then stopping.";
		}
		return s;
	}

	/* FIXME: separate function? */
	is_last_in_playlist = (cursong()->pos == static_cast<song_t>(comm->playlist()->end()));

	if (status->repeat) {
		s += "songs from playlist repeatedly.";
		return s;
	}

	if (playlist_is_active) {
		if (is_last_in_playlist) {
			s += "this song, then stopping.";
		} else {
			s += "songs from playlist.";
		}
		return s;
	}

	if (is_last_in_playlist) {
		s += "this song, then ";
		if (!status->repeat && playlist_is_active) {
			s += "stopping.";
			return s;
		}
	}

	if (!is_last_in_playlist) {
		if (!status->consume) {
			s += "through ";
		}
		s += "playlist, then ";
	}

	if (!playlist_is_active && options->get_bool("followcursor")) {
		s += "following cursor.";
		return s;
	}

	s += "songs from " + list_name + ".";

	return s;
}

/*
 * Put an arbitrary message into the message log
 */
void			Pms::putlog(Message * m)
{
	if (m->code == 0 && m->str.size() == 0)
		return;

	log(MSG_CONSOLE, m->code, m->str.c_str());
}

/*
 * Log a message.
 * Verbosity levels:
 *  0 = statusbar
 *  1 = console
 *  2 = debug
 */
void
Pms::log(int verbosity, long code, const char * format, ...)
{
	long		loglines;
	va_list		ap;
	char		buffer[1024];
	char		tbuffer[20];
	string		level;
	Message *	m;
	tm *		timeinfo;
	color *		pair;

	if (verbosity >= MSG_DEBUG && !pms->options->get_bool("debug"))
		return;

	m = new Message();
	if (m == NULL)
		return;

	va_start(ap, format);
	vsprintf(buffer, format, ap);
	va_end(ap);

	m->str = buffer;
	m->code = code;

	if (verbosity == MSG_STATUS)
	{
		m->str += "\n";

		if (code == STOK)
			pair = options->colors->status;
		else
			pair = options->colors->status_error;

		disp->statusbar->clear(false, pair);
		colprint(disp->statusbar, 0, 0, pair, "%s", buffer);
		timer_statusbar = get_clock();
		disp->refresh();
	}

	if (verbosity <= MSG_DEBUG && pms->options->get_bool("debug"))
	{
		timeinfo = localtime(&(m->timestamp));
		strftime(tbuffer, 20, "%Y-%m-%d %H:%M:%S", timeinfo);
		if (verbosity == MSG_STATUS)
			level = "status";
		else if (verbosity == MSG_CONSOLE)
			level = "console";
		else if (verbosity == MSG_DEBUG)
			level = "debug";
		fprintf(stderr, "%s /%s/ %s", tbuffer, level.c_str(), m->str.c_str());
	}

	if (!disp && verbosity < MSG_DEBUG)
	{
		printf("%s", buffer);
	}

	msglog.push_back(m);
	loglines = options->get_long("msg_buffer_size");
	if (loglines > 0 && msglog.size() > loglines)
		msglog.erase(msglog.begin());
}

/*
 * Checks if time is right for song progression, and takes necessary action.
 *
 * FIXME: split into two functions
 * FIXME: dubious return value
 */
bool			Pms::progress_nextsong()
{
	static song_t		last_song_id = MPD_SONG_NO_ID;
	static Song *		lastcursor = NULL;
	Songlist *		list = NULL;
	unsigned int		song_time_remaining;
	Mpd_status *		status = comm->status();

	/* No song progression without an active song, probably meaning that
	 * the player is stopped or something is wrong. */
	if (!cursong()) {
		return false;
	}

	/* No song progression if not playing. */
	if (status->state != MPD_STATE_PLAY) {
		return false;
	}

	/* If the active list is the playlist, PMS doesn't need to do anything,
	 * because MPD handles the rest. */
	list = comm->activelist();
	assert(list != NULL);
	if (list == comm->playlist()) {
		return false;
	}

	/* Only add songs when there the currently playing song is near the end. */
	song_time_remaining = status->time_total - status->time_elapsed - status->crossfade;
	if (song_time_remaining > options->get_long("nextinterval")) {
		return false;
	}

	/* No auto-progression in single mode */
	if (status->single) {
		return false;
	}

	/* Defeat desync with server */
	last_song_id = cursong()->id;

	/* Normal progression: reached end of playlist */
	if (cursong()->pos == static_cast<int>(playlist->list->end())) { 

		pms->log(MSG_DEBUG, 0, "Auto-progressing to next song.\n");

		/* Playback follows cursor */
		if (options->get_bool("followcursor") && lastcursor != disp->cursorsong() && disp->cursorsong()->file != cursong()->file)
		{
			pms->log(MSG_DEBUG, 0, "Playback follows cursor: last cursor=%p, now cursor=%p.\n", lastcursor, disp->cursorsong());
			lastcursor = disp->cursorsong();
			last_song_id = comm->add(comm->playlist(), lastcursor);
		}

		/* Normal song progression */
		last_song_id = playnext(false);
	}

	if (lastcursor == NULL) {
		lastcursor = disp->cursorsong();
	}

	return (last_song_id != MPD_SONG_NO_ID);
}

/*
 * Create new windows for each custom playlist
 */
bool			Pms::connect_window_list()
{
	bool				ok = true;
	pms_window *			win;
	vector<Songlist *>::iterator	i;

	i = comm->playlists.begin();
	while (i != comm->playlists.end())
	{
		if (disp->findwlist(*i) == NULL)
		{
			win = disp->create_playlist();
			if (win)
				win->setplist(*i);
			else
				ok = false;
		}
		++i;
	}

	return ok;
}

/*
 * Default key bindings
 */
void			Pms::init_default_keymap()
{
	bindings->clear();

	/* Movement */
	bindings->add("up", "move-up");
	bindings->add("down", "move-down");
	bindings->add("pageup", "move-pgup");
	bindings->add("pagedown", "move-pgdn");
	bindings->add("^B", "move-pgup");
	bindings->add("^F", "move-pgdn");
	bindings->add("^U", "move-halfpgup");
	bindings->add("^D", "move-halfpgdn");
	bindings->add("^Y", "scroll-up");
	bindings->add("^E", "scroll-down");
	bindings->add("z", "center-cursor");
	bindings->add("home", "move-home");
	bindings->add("end", "move-end");
	bindings->add("g", "goto-current");
	bindings->add("R", "goto-random");
	bindings->add("j", "move-down");
	bindings->add("k", "move-up");
	bindings->add("t", "prev-window");
	bindings->add("T", "next-window");
	bindings->add("(", "prev-of album");
	bindings->add(")", "next-of album");
	bindings->add("{", "prev-of artist");
	bindings->add("}", "next-of artist");
	bindings->add("1", "change-window playlist");
	bindings->add("2", "change-window library");
	bindings->add("w", "change-window windowlist");
	// TODO: add this for a later version
	//bindings->add("W", "change-window directorylist");
	bindings->add("tab", "last-window");

	/* Searching */
	bindings->add("/", "quick-find");
	bindings->add("n", "next-result");
	bindings->add("N", "prev-result");

	/* Playlist management */
	bindings->add("a", "add");
	bindings->add("A", "add-to");
	bindings->add("b", "add-album");
	bindings->add("B", "play-album");
	bindings->add("delete", "remove");
	bindings->add("C", "crop");
	bindings->add("insert", "toggle-select");
	bindings->add("F12", "activate-list");
	bindings->add("^X", "delete-list");
	bindings->add("J", "move 1");
	bindings->add("K", "move -1");

	/* Controls */
	bindings->add("return", "play");
	bindings->add("kpenter", "play");
	bindings->add("backspace", "stop");
	bindings->add("p", "pause");
	bindings->add("space", "toggle-play");
	bindings->add("l", "next");
	bindings->add("h", "prev");
	bindings->add("M", "mute");
	bindings->add("r", "repeat");
	bindings->add("z", "random");
	bindings->add("c", "consume");
	bindings->add("s", "single");
	bindings->add("+", "volume +5");
	bindings->add("-", "volume -5");
	bindings->add("left", "seek -5");
	bindings->add("right", "seek 5");

	/* Maintenance */
	bindings->add("f", "toggle followcursor");
	bindings->add("F", "toggle followplayback");
	bindings->add("^F", "toggle followwindow");
	bindings->add(":", "command-mode");
	bindings->add("u", "update-library");
	bindings->add("v", "version");
	bindings->add("q", "quit");
	bindings->add("F1", "help");
	bindings->add("^L", "redraw");
}










/*
 * Print the version string
 */
void
Pms::print_version()
{
	printf("Uses libmpdclient (c) 2003-2015 The Music Player Daemon Project.\n");
	printf("This program is licensed under the GNU General Public License version 3.\n");
}

/*
 * Print switch usage
 */
void			Pms::print_usage()
{
	printf("Usage:\n");
	printf("  -%s\t\t\t%s\n", "v", "print version and exit");
	printf("  -%s\t\t%s\n", "? --help", "display command-line options");
	printf("  -%s\t\t\t%s\n", "d", "turn on debugging to stderr");
	printf("  -%s\t\t%s\n", "c <filename>", "use an alternative config file");
	printf("  -%s\t\t%s\n", "h <host>", "connect to this MPD server");
	printf("  -%s\t\t%s\n", "p <port>", "connect to this port");
	printf("  -%s\t\t%s\n", "P <password>", "give this password to MPD server");
}

/*
 * Helper function, prints an error
 */
bool			Pms::require_arg(char c)
{
	printf("Error: option '%c' requires an argument.\n", c);
	print_usage();
	return false;
}

/*
 * Parse command-line arguments
 */
bool			Pms::parse_args(int argc, char * argv[])
{
	int			argn;
	string			value = "";
	string			arg = "";
	bool			switched = false;
	string			s;
	string::iterator	i;

	if (argc <= 1)
		return true;

	for (argn = 1; argn < argc; argn++)
	{
		s = argv[argn];

		if (s == "--help")
		{
			print_usage();
			return false;
		}

		i = s.begin();

		while (i != s.end())
		{
			if (!switched)
				if (*i != '-')
					return false;

			switch (*i)
			{
				case 'd':
					options->set_bool("debug", true);
					break;
				case 'v':
					print_version();
					return false;
				case '?':
					print_usage();
					return false;
				case 'c':
					if (++argn >= argc)
						return require_arg(*i);
					options->set_string("configfile", argv[argn]);
					break;
				case 'h':
					if (++argn >= argc)
						return require_arg(*i);
					options->set_string("host", argv[argn]);
					break;
				case 'p':
					if (++argn >= argc)
						return require_arg(*i);
					options->set_long("port", atoi(argv[argn]));
					if (options->get_long("port") <= 0 || options->get_long("port") > 65535)
					{
						printf(_("Error: port number must be from 1-65535\n"));
						return false;
					}
					break;
				case 'P':
					if (++argn >= argc)
						return require_arg(*i);
					options->set_string("password", argv[argn]);
					break;
				case '-':
					if (switched)
					{
						print_usage();
						return false;
					}
					switched = true;
					break;
				default:
					printf(_("Error: unknown option '%c'\n"), *i);
					print_usage();
					return false;
			}
			++i;
		}
	
		switched = false;
	}

	return true;
}

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/pms

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

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