xref: /haiku/src/bin/pkgman/DecisionProvider.cpp (revision a629567a9001547736cfe892cdf992be16868fed)
1 /*
2  * Copyright 2011, Oliver Tappe <zooey@hirschkaefer.de>
3  * Distributed under the terms of the MIT License.
4  */
5 
6 
7 #include <stdio.h>
8 #include <string.h>
9 
10 #include "DecisionProvider.h"
11 
12 
13 DecisionProvider::DecisionProvider(bool interactive)
14 	:
15 	fInteractive(interactive)
16 {
17 }
18 
19 
20 bool
21 DecisionProvider::YesNoDecisionNeeded(const BString& description,
22 	const BString& question, const BString& yes, const BString& no,
23 	const BString& defaultChoice)
24 {
25 	if (description.Length() > 0)
26 		printf("%s\n", description.String());
27 
28 	bool haveDefault = defaultChoice.Length() > 0;
29 
30 	while (true) {
31 		printf("%s [%s/%s]%s: ", question.String(), yes.String(), no.String(),
32 			haveDefault
33 				? (BString(" (") << defaultChoice << ") ").String() : "");
34 
35 		if (!fInteractive) {
36 			printf("%s\n", yes.String());
37 			return true;
38 		}
39 
40 		char buffer[32];
41 		if (fgets(buffer, 32, stdin)) {
42 			if (haveDefault &&  (buffer[0] == '\n' || buffer[0] == '\0'))
43 				return defaultChoice == yes;
44 			int length = strlen(buffer);
45 			for (int i = 1; i <= length; ++i) {
46 				if (yes.ICompare(buffer, i) == 0) {
47 					if (no.ICompare(buffer, i) != 0)
48 						return true;
49 				} else if (no.Compare(buffer, i) == 0) {
50 					if (yes.ICompare(buffer, i) != 0)
51 						return false;
52 				} else
53 					break;
54 			}
55 			fprintf(stderr, "*** please enter '%s' or '%s'\n", yes.String(),
56 				no.String());
57 		}
58 	}
59 }
60