summaryrefslogtreecommitdiff
blob: 6eb2d6f9892fb93830f767cac394b79f8544e348 (plain)
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
#include "ufed-curses.h"

#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <locale.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>

#include "ufed-curses-help.h"

/* internal members */
static int     descriptionleft = 0;
static sFlag** faytsave        = NULL;
static size_t  maxDescWidth    = 0;
static char*   lineBuf         = NULL;
static sFlag*  flags           = NULL;

#define mkKey(x) x, sizeof(x)-1
static const sKey keys[] = {
	{ '?',      mkKey("?: Help"),            0 },
	{ '\n',     mkKey("Enter: Save"),        0 },
	{ '\033',   mkKey("Esc: Cancel"),        0 },
	{ -1,       mkKey("Toggle"),             1 },
	{ KEY_F(5), mkKey("F5: Local/Global"),   1 },
	{ KEY_F(6), mkKey("F6: Installed"),      1 },
	{ KEY_F(7), mkKey("F7: Masked/Forced"),  1 },
	{ KEY_F(9), mkKey("F8: Pkg/Desc Order"), 1 },
	{ '\0',     mkKey(""),                   0 }
};
#undef mkKey


/* internal prototypes */
static void free_flags(void);


/* static functions */
static char *getline(FILE *fp)
{
	static size_t size = LINE_MAX;

	if (NULL == lineBuf) {
		lineBuf = malloc(size);
		if (NULL == lineBuf)
			ERROR_EXIT(-1, "Can not allocate %lu bytes for line buffer\n", sizeof(char) * size);
	}

	if(fgets(lineBuf, size, fp) == NULL)
		return NULL;
	else {
		char *p = strchr(lineBuf, '\n');
		if(p != NULL) {
			*p = '\0';
			return lineBuf;
		}
	}
	for(;;) {
		char *newLine = realloc(lineBuf, size + size / 2);
		if(newLine == NULL)
			ERROR_EXIT(-1, "Can not reallocate %lu bytes for line buffer\n",
				(size_t)(sizeof(char) * size * 1.5));
		lineBuf = newLine;
		newLine = NULL;
		if(fgets(lineBuf + size, size / 2, fp) == NULL)
			return NULL;
		else {
			char *p = strchr(lineBuf + size, '\n');
			if(p != NULL) {
				*p = '\0';
				return lineBuf;
			}
		}
		size += size/2;
	}
	return NULL; // never reached.
}

static void read_flags(void)
{
	FILE*  input     = fdopen(3, "r");
	int    lineNum   = 0;
	char*  line      = NULL;
	int    ndescr    = 0;
	char   endChar   = 0;
	size_t fullWidth = 0;
	struct {
		int start, end;
	} name, desc, pkg, state;

	if(input == NULL)
		ERROR_EXIT(-1, "fdopen failed with error %d\n", errno);
	atexit(&free_flags);

	for(line = getline(input); line ; line = getline(input)) {
		name.start  = name.end  = -1;
		state.start = state.end = -1;

		if (sscanf(line, "%n%*s%n [%n%*[ +-]%n] %d",
				&name.start,  &name.end,
				&state.start, &state.end,
				&ndescr) != 1)
			ERROR_EXIT(-1, "Flag read failed on line %d:\n\"%s\"\n", lineNum + 1, line);

		// Check stats
		if ((state.end - state.start) != 2)
			ERROR_EXIT(-1, "Illegal flag stats on line %d:\n\"%s\"\n", lineNum + 1, line);

		// Create a new flag
		line[name.end]  = '\0';
		line[state.end] = '\0';
		sFlag* newFlag = addFlag(&flags, &line[name.start], lineNum, ndescr, &line[state.start]);

		/* The minimum width of the left side display is:
		 * Space + Selection + Space + name + Space + Mask brackets/Force plus.
		 * = 1 + 3 + 1 + strlen(name) + 1 + 2
		 * = strlen(name) + 8
		 */
		if( (name.end - name.start + 8) > minwidth)
			minwidth = name.end - name.start + 8;

		/* read description(s) and determine flag status */
		for (int i = 0; i < ndescr; ++i) {
			desc.start  = desc.end  = -1;
			pkg.start   = pkg.end   = -1;
			state.start = state.end = -1;

			line = getline(input);
			if (!line) break;

			if ( (sscanf(line, "\t%n%*[^\t]%n\t (%n%*[^)]%n) [%n%*[ +-]%n%c",
					&desc.start,  &desc.end,
					&pkg.start,   &pkg.end,
					&state.start, &state.end,
					&endChar) != 1)
			  || (']' != endChar) )
				ERROR_EXIT(-1, "Description read failed on line %d\n\"%s\"\n", lineNum + 1, line);

			// Check stats
			if ((state.end - state.start) != 7)
				ERROR_EXIT(-1, "Illegal description stats on line %d:\n\"%s\"\n", lineNum + 1, line);

			// Add description line to flag:
			line[desc.end]  = '\0';
			line[state.end] = '\0';
			if ( (pkg.end - pkg.start) > 1) {
				line[pkg.end]   = '\0';
				fullWidth = addFlagDesc(newFlag, &line[pkg.start], &line[desc.start], &line[state.start]);
			} else
				fullWidth = addFlagDesc(newFlag, NULL, &line[desc.start], &line[state.start]);

			// Note new max length if this line is longest:
			if (fullWidth > maxDescWidth)
				maxDescWidth = fullWidth;

			// Advance lineNum
			++lineNum;
		} // loop through description lines

		// Update flag states and add data to the list stats
		genFlagStats(newFlag);
		addLineStats(newFlag, &listStats);
	} // loop while input given

	fclose(input);

	if(flags == NULL)
		ERROR_EXIT(-1, "Unable to start: %s\n", "No Input!");

	// Save the last line, it is needed in several places
	bottomline = lineNum;
}

static void free_flags(void)
{
	sFlag* flag = flags->prev;

	// Clear all flags
	while (flags) {
		if (flag)
			destroyFlag(&flags, &flag);
		else
			destroyFlag(&flags, &flags);
		flag = flags ? flags->prev ? flags->prev : flags : NULL;
	}

	// Clear line buffer
	if (lineBuf)
		free(lineBuf);
}


static int drawflag(sFlag* flag, bool highlight)
{
	char buf[wWidth(List)+1];
	char desc[maxDescWidth];
	int idx   = 0;
	int usedY = 0;
	int line  = flag->currline;

	// Return early if there is nothing to display:
	if (!isFlagLegal(flag))
		return 0;

	/* Determine with which description to start.
	 * Overly long description lists might not fit on one screen,
	 * and therefore must be scrolled instead of the flags
	 * themselves.
	 */
	if (line < 0) {
		if (-line < getFlagHeight(flag)) {
			while (line < 0) {
				if (isDescLegal(flag, idx++)) {
					++line;
					++usedY;
				}
			}
		} else
			// Otherwise this item is out of the display area
			return 0;
	}

	memset(buf, 0, sizeof(char) * (wWidth(List)+1));

	// print descriptions according to filters
	if(idx < flag->ndesc) {
		WINDOW* wLst = win(List);
		int  lHeight = wHeight(List);
		int  descLen = wWidth(List) - (minwidth + 8);
		bool hasHead = false;
		char *p, special;

		for( ; (idx < flag->ndesc) && (line < lHeight); ++idx) {
			// Continue if any of the filters apply:
			if (!isDescLegal(flag, idx))
				continue;

			// Set special character if needed:
			if (isDescForced(flag, idx))
				special = 'f';
			else if (isDescMasked(flag, idx))
				special = 'm';
			else
				special = ' ';

			if (hasHead) {
				// Add spaces under the flag display
				for(p = buf; p != buf + minwidth; ++p)
					*p = ' ';
			} else {
				/* print the selection, name and state of the flag */
				sprintf(buf, " %c%c%c %s%s%s%-*s ",
					/* State of selection */
					flag->stateConf == ' ' ? '(' : '[',
					' ', // Filled in later
					flag->stateConf == ' ' ? ')' : ']',
					/* name */
					flag->globalForced ? "(" : flag->globalMasked ? "(-" : "",
					flag->name,
					(flag->globalForced || flag->globalMasked) ? ")" : "",
					/* distance */
					(int)(minwidth
						- (flag->globalForced ? 3 : flag->globalMasked ? 2 : 5)
						- strlen(flag->name)), " ");
					// At this point buf is filled up to minwidth
			} // End of generating left side mask display

			/* Display flag state
			 * The order in which the states are to be displayed is:
			 * 1. [D]efaults (make.defaults, IUSE, package.mask, package.force)
			 *    Note: Filled in later
			 * 2. [P]rofile package.use files
			 * 3. [C]onfiguration (make.conf, users package.use)
			 * 4. global/local
			 * 5. installed/not installed
			 */
			sprintf(buf + minwidth, "  %c%c %c%c ",
				flag->desc[idx].statePackage,
				' ' == flag->desc[idx].statePkgUse ?
					flag->stateConf : flag->desc[idx].statePkgUse,
				flag->desc[idx].isGlobal ? ' ' : 'L',
				flag->desc[idx].isInstalled ? 'i' : ' ');

			// Assemble description line:
			memset(desc, 0, maxDescWidth * sizeof(char));
			if (flag->desc[idx].pkg) {
				if (e_order == eOrder_left)
					sprintf(desc, "(%s) %s", flag->desc[idx].pkg, flag->desc[idx].desc);
				else
					sprintf(desc, "%s (%s)", flag->desc[idx].desc, flag->desc[idx].pkg);
			}
			else
				sprintf(desc, "%s", flag->desc[idx].desc);

			// Now display the description line according to its horizontal position
			sprintf(buf + minwidth + 8, "%-*.*s", descLen, descLen,
				strlen(desc) > (size_t)descriptionleft
					? &desc[descriptionleft]
					: "");

			/* Set correct color set according to highlighting and status*/
			if(highlight)
				wattrset(wLst, COLOR_PAIR(3) | A_BOLD | A_REVERSE);
			else
				wattrset(wLst, COLOR_PAIR(3));

			// Put the line on the screen
			mvwaddstr(wLst, line, 0, buf);
			mvwaddch(wLst, line, minwidth,     ACS_VLINE); // Before state
			mvwaddch(wLst, line, minwidth + 4, ACS_VLINE); // Between state and scope
			mvwaddch(wLst, line, minwidth + 7, ACS_VLINE); // After scope

			// Add (default) selection if this is the header line
			if (!hasHead) {
				hasHead = true;
				if (flag->globalForced) {
					if(highlight)
						wattrset(wLst, COLOR_PAIR(5) | A_REVERSE);
					else
						wattrset(wLst, COLOR_PAIR(5) | A_BOLD);
					mvwaddch(wLst, line, 2, '+');
				} else if (flag->globalMasked) {
					if(highlight)
						wattrset(wLst, COLOR_PAIR(4) | A_REVERSE);
					else
						wattrset(wLst, COLOR_PAIR(4) | A_BOLD);
					mvwaddch(wLst, line, 2, '-');
				} else if (' ' == flag->stateConf)
					mvwaddch(wLst, line, 2, flag->stateDefault);
				else
					mvwaddch(wLst, line, 2, flag->stateConf);
			}

			// Add [D]efault column content
			if ('f' == special) {
				if(highlight)
					wattrset(wLst, COLOR_PAIR(5) | A_REVERSE);
				else
					wattrset(wLst, COLOR_PAIR(5) | A_BOLD);
				mvwaddch(wLst, line, minwidth + 1, special);
			} else if ('m' == special) {
				if(highlight)
					wattrset(wLst, COLOR_PAIR(4) | A_REVERSE);
				else
					wattrset(wLst, COLOR_PAIR(4) | A_BOLD);
				mvwaddch(wLst, line, minwidth + 1, special);
			} else {
				if (' ' == flag->desc[idx].stateDefault)
					mvwaddch(wLst, line, minwidth + 1, flag->stateDefault);
				else
					mvwaddch(wLst, line, minwidth + 1, flag->desc[idx].stateDefault);
			}

			++line;
			++usedY;
		}
	} else {
		memset(buf+minwidth, ' ', wWidth(List)-minwidth);
		buf[wWidth(List)] = '\0';
		waddstr(win(List), buf);
	}

	if(highlight)
		wmove(win(List), max(flag->currline, 0), 2);
	wnoutrefresh(win(List));

	return usedY;
}

static int callback(sFlag** curr, int key)
{
	WINDOW* wInp = win(Input);
	WINDOW* wLst = win(List);
	size_t  fLen = 0;

	if ( fayt[0]
	  && (key != KEY_BACKSPACE)
	  && (key != KEY_DC)
	  && (key != 0177)
	  && ( (key == ' ') || (key != (unsigned char)key) || !isprint(key)) ) {
		fayt[0] = '\0';
		drawStatus(true);
		wrefresh(wInp);
	} else
		wmove(wInp, 0, strlen(fayt));

	// Reset possible side scrolling of the current flags description first
	if(descriptionleft && (key != KEY_LEFT) && (key != KEY_RIGHT) ) {
		descriptionleft = 0;
		drawflag(*curr, TRUE);
	}

	switch(key) {
		case KEY_DC:
		case 0177:
		case KEY_BACKSPACE:
			fLen = strlen(fayt);
			if(0 == fLen)
				break;
			fayt[--fLen] = '\0';
			drawflag(*curr, FALSE);
			*curr = faytsave[fLen];
			if (!scrollcurrent())
				drawflag(*curr, TRUE);
			wattrset(wInp, COLOR_PAIR(5) | A_BOLD);
			mvwaddstr(wInp, 0, 0, fayt);
			whline(wInp, ' ', 2);
			if(fLen == 0)
				wmove(wLst, (*curr)->currline, 2);
			wnoutrefresh(wLst);
			wrefresh(wInp);
			break;
		case '\n':
		case KEY_ENTER:
			if(yesno("Save and exit? (Y/N) "))
				return 0;
			break;
		case '\033':
			if(yesno("Cancel? (Y/N) "))
				return 1;
			break;
		case ' ':
			// Masked flags can be turned off, nothing else
			if ( (*curr)->globalMasked || (*curr)->globalForced ) {
				if (' ' != (*curr)->stateConf)
					(*curr)->stateConf = ' ';
			} else {
				switch ((*curr)->stateConf) {
					case '+':
						(*curr)->stateConf = '-';
						break;
					case '-':
						(*curr)->stateConf = ' ';
						break;
					default:
						(*curr)->stateConf = '+';
						break;
				}
			}
			if (*curr != flags) {
				drawflag(*curr, TRUE);
				wmove(wLst, (*curr)->currline, 2);
				wrefresh(wLst);
			} else
				drawFlags();
			break;
		case KEY_LEFT:
			if(descriptionleft > 0)
				descriptionleft -= min(descriptionleft, (wWidth(List) - minwidth) * 2 / 3);
			drawflag(*curr, TRUE);
			wmove(wLst, (*curr)->currline, 2);
			wrefresh(wLst);
			break;
		case KEY_RIGHT:
			descriptionleft += (wWidth(List) - minwidth) * 2 / 3;
			drawflag(*curr, TRUE);
			wmove(wLst, (*curr)->currline, 2);
			wrefresh(wLst);
			break;

		case KEY_F(5):
			if      (eScope_local  == e_scope) e_scope = eScope_all;
			else if (eScope_global == e_scope) e_scope = eScope_local;
			else                               e_scope = eScope_global;

			if ( !isFlagLegal(*curr)
			  && !setNextItem(0, true)
			  && !setPrevItem(0, true) )
				resetDisplay(true);
			else
				draw(true);
			break;

		case KEY_F(6):
			if      (eState_installed    == e_state) e_state = eState_notinstalled;
			else if (eState_notinstalled == e_state) e_state = eState_all;
			else                                     e_state = eState_installed;

			if ( !isFlagLegal(*curr)
			  && !setNextItem(0, true)
			  && !setPrevItem(0, true) )
				resetDisplay(true);
			else
				draw(true);
			break;

		case KEY_F(7):
			if      (eMask_masked   == e_mask) e_mask = eMask_unmasked;
			else if (eMask_unmasked == e_mask) e_mask = eMask_both;
			else                               e_mask = eMask_masked;

			if ( !isFlagLegal(*curr)
			  && !setNextItem(0, true)
			  && !setPrevItem(0, true) )
				resetDisplay(true);
			else
				draw(true);

			break;

		case KEY_F(9):
			if (eOrder_left == e_order) e_order = eOrder_right;
			else                        e_order = eOrder_left;

			drawFlags();
			wmove(wInp, 0, strlen(fayt));
			break;

#ifdef NCURSES_MOUSE_VERSION
		case KEY_MOUSE:
			// Masked flags can be turned off, nothing else
			if ( (*curr)->globalMasked || (*curr)->globalForced ) {
				if (' ' != (*curr)->stateConf)
					(*curr)->stateConf = ' ';
			} else {
				switch ((*curr)->stateConf) {
					case '+':
						(*curr)->stateConf = '-';
						break;
					case '-':
						(*curr)->stateConf = ' ';
						break;
					default:
						(*curr)->stateConf = '+';
						break;
				}
			}
			if (*curr != flags) {
				drawflag(*curr, TRUE);
				wmove(wLst, (*curr)->currline, 2);
				wrefresh(wLst);
			} else {
				drawFlags();
				wmove(wInp, 0, strlen(fayt));
			}
			break;
#endif
		case '?':
			help();
			break;
		default:
			if( (key == (unsigned char) key) && isprint(key)) {
				sFlag* flag = *curr;
				fLen = strlen(fayt);
				if(fLen && strncasecmp(flag->name, fayt, fLen))
					--fLen;
				fayt[fLen]     = (char) key;
				faytsave[fLen] = *curr;
				fayt[++fLen]   = '\0';

				wmove(wInp, 0, fLen);

				/* if the current flag already matches the input string,
				 * then update the input area only.
				 */
				if(!strncasecmp(flag->name, fayt, fLen)) {
					wattrset(wInp, COLOR_PAIR(5) | A_BOLD);
					mvwaddstr(wInp, 0, 0, fayt);
					wrefresh(wInp);
				}
				/* if the current flag does not match, search one that does. */
				else {
					do flag = flag->next;
					while( (flag != *curr)
					    && ( ( strncasecmp(flag->name, fayt, fLen)
					    	|| !isFlagLegal(flag)) ) );

					/* if there was no match (or the match is filtered),
					 * update the input area to show that there is no match
					 */
					if (flag == *curr) {
						wattrset(wInp, COLOR_PAIR(4) | A_BOLD | A_REVERSE);
						mvwaddstr(wInp, 0, 0, fayt);
						wmove(wInp, 0, fLen - 1);
						wrefresh(wInp);
					} else {
						drawflag(*curr, FALSE);
						*curr = flag;
						if (!scrollcurrent())
							drawflag(*curr, TRUE);
						wattrset(wInp, COLOR_PAIR(5) | A_BOLD);
						mvwaddstr(wInp, 0, 0, fayt);
						wmove(wInp, 0, fLen);
						wrefresh(wInp);
					}
				}
			}
			break;
	}

	return -1;
}

int main(void)
{
	int result;

	read_flags();
	fayt     = (char*)  calloc(minwidth, sizeof(*fayt));
	faytsave = (sFlag**)calloc(minwidth, sizeof(*faytsave));
	if(fayt==NULL || faytsave==NULL)
		ERROR_EXIT(-1, "Unable to allocate %lu bytes for search buffer.\n",
			(minwidth * sizeof(*fayt)) + (minwidth * sizeof(*faytsave)));
	fayt[0] = '\0';

	initcurses();

	result = maineventloop("Select desired USE flags from the list below:",
				&callback, &drawflag, flags, keys, true);

	cursesdone();

	if(0 == result) {
		FILE *output = fdopen(4, "w");
		sFlag *flag = flags;
		do {
			switch(flag->stateConf)
			{
			case '+':
				fprintf(output, "%s\n", flag->name);
				break;
			case '-':
				fprintf(output, "-%s\n", flag->name);
				break;
			}
			flag = flag->next;
		} while(flag != flags);
		fclose(output);
	}

	if (fayt)     free(fayt);
	if (faytsave) free(faytsave);

	return result;
}