Counter omits color codes only if connected to a TTY
authorDmitriy Morozov <morozov@cs.duke.edu>
Sat, 15 Sep 2007 14:31:36 -0400
changeset 34 19fb71f2405e
parent 33 3318eb317618
child 35 a09d42924ece
Counter omits color codes only if connected to a TTY
include/utilities/counter.h
include/utilities/counter.hpp
--- a/include/utilities/counter.h	Sat Sep 15 04:42:15 2007 -0400
+++ b/include/utilities/counter.h	Sat Sep 15 14:31:36 2007 -0400
@@ -26,6 +26,7 @@
 #include <string>
 #include <iostream>
 #include <limits>
+#include <unistd.h>
 
 class Counter
 {
@@ -42,9 +43,7 @@
 
 	public:
 								Counter(const std::string& full_name = "",
-										CounterType freq = std::numeric_limits<CounterType>::max()):
-										count(0), frequency(freq), trigger(this), full_name_(full_name)
-								{}
+										CounterType freq = std::numeric_limits<CounterType>::max());
 								~Counter();
 
 		Counter*				get_child(const std::string& path, std::string::size_type pos);
@@ -53,7 +52,18 @@
 	private:	
 		SubCounterMap			subcounters_;
 		std::string				full_name_;
+		
+		static const char*		start_color;
+		static const char*		finish_color;
+		static const char		green_color[];
+		static const char 		normal_color[];
+		static const char 		empty_string[];
 };
+const char Counter::green_color[] 		= "\033[32m";
+const char Counter::normal_color[] 		= "\033[0m";
+const char Counter::empty_string[] 		= "";
+const char* Counter::start_color 		= 0;
+const char* Counter::finish_color 		= 0;
 
 static		Counter				rootCounter;
 
--- a/include/utilities/counter.hpp	Sat Sep 15 04:42:15 2007 -0400
+++ b/include/utilities/counter.hpp	Sat Sep 15 14:31:36 2007 -0400
@@ -1,6 +1,21 @@
 #include <ctime>
 #include <cstdio>
 
+Counter::
+Counter(const std::string& full_name,
+		CounterType freq):
+		count(0), frequency(freq), trigger(this), full_name_(full_name)
+{ 
+	if (isatty(STDOUT_FILENO)) 
+	{
+		start_color = green_color; 
+		finish_color = normal_color;
+	} 
+	else
+	{	start_color = finish_color = empty_string;	}
+}
+
+
 Counter*
 Counter::
 get_child(const std::string& path, std::string::size_type pos)
@@ -40,11 +55,11 @@
 	struct tm* timeinfo = localtime(&rawtime);
 
 	printf("%s(%02i:%02i:%02i)%s ",
-		   "\033[32m",			// green color
+		    start_color,	
 			timeinfo->tm_hour,
 			timeinfo->tm_min,
 			timeinfo->tm_sec,
-			"\033[0m");			// normal color
+			finish_color);
 	std::cout << "Counter [" << full_name_ << "]: " << count << std::endl;
 	for (SubCountMap::const_iterator cur = subcount.begin(); cur != subcount.end(); ++cur)
 		std::cout << "    " << cur->first << ": " << cur->second << std::endl;