xref: /freebsd/contrib/ntp/sntp/unity/auto/colour_prompt.rb (revision e6bfd18d21b225af6a0ed67ceeaf1293b7b9eba5)
1# ==========================================
2#   Unity Project - A Test Framework for C
3#   Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams
4#   [Released under MIT License. Please refer to license.txt for details]
5# ==========================================
6
7if RUBY_PLATFORM =~/(win|w)32$/
8	begin
9		require 'Win32API'
10	rescue LoadError
11		puts "ERROR! \"Win32API\" library not found"
12		puts "\"Win32API\" is required for colour on a windows machine"
13		puts "  try => \"gem install Win32API\" on the command line"
14		puts
15	end
16	# puts
17  # puts 'Windows Environment Detected...'
18	# puts 'Win32API Library Found.'
19	# puts
20end
21
22class ColourCommandLine
23  def initialize
24    if RUBY_PLATFORM =~/(win|w)32$/
25      get_std_handle = Win32API.new("kernel32", "GetStdHandle", ['L'], 'L')
26      @set_console_txt_attrb =
27      Win32API.new("kernel32","SetConsoleTextAttribute",['L','N'], 'I')
28      @hout = get_std_handle.call(-11)
29    end
30  end
31
32  def change_to(new_colour)
33    if RUBY_PLATFORM =~/(win|w)32$/
34      @set_console_txt_attrb.call(@hout,self.win32_colour(new_colour))
35    else
36	  	"\033[30;#{posix_colour(new_colour)};22m"
37	 	end
38  end
39
40  def win32_colour(colour)
41    case colour
42      when :black then 0
43      when :dark_blue then 1
44      when :dark_green then 2
45      when :dark_cyan then 3
46      when :dark_red then 4
47      when :dark_purple then 5
48      when :dark_yellow, :narrative then 6
49      when :default_white, :default, :dark_white then 7
50      when :silver then 8
51      when :blue then 9
52      when :green, :success then 10
53      when :cyan, :output then 11
54      when :red, :failure then 12
55      when :purple then 13
56      when :yellow then 14
57      when :white then 15
58      else
59        0
60    end
61  end
62
63	def posix_colour(colour)
64	  case colour
65      when :black then 30
66      when :red, :failure then 31
67      when :green, :success then 32
68			when :yellow then 33
69      when :blue, :narrative then 34
70      when :purple, :magenta then 35
71      when :cyan, :output then 36
72      when :white, :default_white, :default then 37
73      else
74        30
75    end
76  end
77
78  def out_c(mode, colour, str)
79    case RUBY_PLATFORM
80			when /(win|w)32$/
81			  change_to(colour)
82				 $stdout.puts str if mode == :puts
83				 $stdout.print str if mode == :print
84			  change_to(:default_white)
85			else
86				$stdout.puts("#{change_to(colour)}#{str}\033[0m") if mode == :puts
87				$stdout.print("#{change_to(colour)}#{str}\033[0m") if mode == :print
88		end
89  end
90end # ColourCommandLine
91
92def colour_puts(role,str)  ColourCommandLine.new.out_c(:puts, role, str)  end
93def colour_print(role,str) ColourCommandLine.new.out_c(:print, role, str) end
94
95