Home | History | Annotate | Download | only in gn
      1 // Copyright (c) 2013 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 "tools/gn/standard_out.h"
      6 
      7 #include "build/build_config.h"
      8 
      9 #if defined(OS_WIN)
     10 #include <windows.h>
     11 #else
     12 #include <stdio.h>
     13 #endif
     14 
     15 namespace {
     16 
     17 bool initialized = false;
     18 
     19 #if defined(OS_WIN)
     20 HANDLE hstdout;
     21 WORD default_attributes;
     22 
     23 bool is_console = false;
     24 #endif
     25 
     26 void EnsureInitialized() {
     27   if (initialized)
     28     return;
     29   initialized = true;
     30 
     31 #if defined(OS_WIN)
     32   hstdout = ::GetStdHandle(STD_OUTPUT_HANDLE);
     33   CONSOLE_SCREEN_BUFFER_INFO info;
     34   is_console = !!::GetConsoleScreenBufferInfo(hstdout, &info);
     35   default_attributes = info.wAttributes;
     36 #endif
     37 }
     38 
     39 }  // namespace
     40 
     41 #if defined(OS_WIN)
     42 
     43 void OutputString(const std::string& output, TextDecoration dec) {
     44   EnsureInitialized();
     45   if (is_console) {
     46     switch (dec) {
     47       case DECORATION_NONE:
     48         break;
     49       case DECORATION_BOLD:
     50         ::SetConsoleTextAttribute(hstdout, FOREGROUND_INTENSITY);
     51         break;
     52       case DECORATION_RED:
     53         ::SetConsoleTextAttribute(hstdout,
     54                                   FOREGROUND_RED | FOREGROUND_INTENSITY);
     55         break;
     56       case DECORATION_GREEN:
     57         // Keep green non-bold.
     58         ::SetConsoleTextAttribute(hstdout, FOREGROUND_GREEN);
     59         break;
     60       case DECORATION_BLUE:
     61         ::SetConsoleTextAttribute(hstdout,
     62                                   FOREGROUND_BLUE | FOREGROUND_INTENSITY);
     63         break;
     64       case DECORATION_YELLOW:
     65         ::SetConsoleTextAttribute(hstdout,
     66                                   FOREGROUND_RED | FOREGROUND_GREEN);
     67         break;
     68     }
     69   }
     70 
     71   DWORD written = 0;
     72   ::WriteFile(hstdout, output.c_str(), output.size(), &written, NULL);
     73 
     74   if (is_console)
     75     ::SetConsoleTextAttribute(hstdout, default_attributes);
     76 }
     77 
     78 #else
     79 
     80 void OutputString(const std::string& output, TextDecoration dec) {
     81   printf("%s", output.c_str());
     82 }
     83 
     84 #endif
     85