1 // Copyright 2014 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "media/cast/test/utility/input_builder.h" 6 7 #include <stdlib.h> 8 #include <cstdio> 9 10 #include "base/command_line.h" 11 #include "base/logging.h" 12 #include "base/strings/string_number_conversions.h" 13 14 namespace media { 15 namespace cast { 16 namespace test { 17 18 static const char kEnablePromptsSwitch[] = "enable-prompts"; 19 20 InputBuilder::InputBuilder(const std::string& title, 21 const std::string& default_value, 22 int low_range, 23 int high_range) 24 : title_(title), 25 default_value_(default_value), 26 low_range_(low_range), 27 high_range_(high_range) {} 28 29 InputBuilder::~InputBuilder() {} 30 31 std::string InputBuilder::GetStringInput() const { 32 if (!CommandLine::ForCurrentProcess()->HasSwitch(kEnablePromptsSwitch)) 33 return default_value_; 34 35 printf("\n%s\n", title_.c_str()); 36 if (!default_value_.empty()) 37 printf("Hit enter for default (%s):\n", default_value_.c_str()); 38 39 printf("# "); 40 fflush(stdout); 41 char raw_input[128]; 42 if (!fgets(raw_input, 128, stdin)) { 43 NOTREACHED(); 44 return std::string(); 45 } 46 47 std::string input = raw_input; 48 input = input.substr(0, input.size() - 1); // Strip last \n. 49 if (input.empty() && !default_value_.empty()) 50 return default_value_; 51 52 if (!ValidateInput(input)) { 53 printf("Invalid input. Please try again.\n"); 54 return GetStringInput(); 55 } 56 return input; 57 } 58 59 int InputBuilder::GetIntInput() const { 60 std::string string_input = GetStringInput(); 61 int int_value; 62 CHECK(base::StringToInt(string_input, &int_value)); 63 return int_value; 64 } 65 66 bool InputBuilder::ValidateInput(const std::string input) const { 67 // Check for a valid range. 68 if (low_range_ == INT_MIN && high_range_ == INT_MAX) 69 return true; 70 int value; 71 if (!base::StringToInt(input, &value)) 72 return false; 73 return value >= low_range_ && value <= high_range_; 74 } 75 76 } // namespace test 77 } // namespace cast 78 } // namespace media 79