/*
 * Copyright 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gradle.internal.nativeintegration.console;

import net.rubygrapefruit.platform.terminal.Terminals;
import org.gradle.internal.os.OperatingSystem;

import static net.rubygrapefruit.platform.terminal.Terminals.Output.Stderr;
import static net.rubygrapefruit.platform.terminal.Terminals.Output.Stdout;

public class NativePlatformConsoleDetector implements ConsoleDetector {
    private final Terminals terminals;

    public NativePlatformConsoleDetector(Terminals terminals) {
        this.terminals = terminals;
    }

    @Override
    public ConsoleMetaData getConsole() {
        // Dumb terminal doesn't support ANSI control codes.
        // TODO - remove this when we use Terminal rather than JAnsi to render to console
        String term = System.getenv("TERM");
        if ((term != null && term.equals("dumb")) || (OperatingSystem.current().isUnix() && term == null)) {
            return null;
        }

        boolean stdout = terminals.isTerminal(Stdout);
        boolean stderr = terminals.isTerminal(Stderr);
        if (stdout) {
            return new NativePlatformConsoleMetaData(stdout, stderr, terminals.getTerminal(Stdout));
        } else if (stderr) {
            return new NativePlatformConsoleMetaData(stdout, stderr, terminals.getTerminal(Stderr));
        }
        return null;
    }

    @Override
    public boolean isConsoleInput() {
        return terminals.isTerminalInput();
    }
}

@@ -666,16 +666,68 @@
 nsole;%0A%0A
+import net.rubygrapefruit.platform.NativeException;%0A
 import n
@@ -1700,16 +1700,35 @@
 tderr);%0A
+%0A        try %7B%0A    
         
@@ -1745,32 +1745,36 @@
 ) %7B%0A            
+    
 return new Nativ
@@ -1842,24 +1842,28 @@
 l(Stdout));%0A
+    
         %7D el
@@ -1883,32 +1883,36 @@
 ) %7B%0A            
+    
 return new Nativ
@@ -1992,18 +1992,37 @@
         
-%7D%0A
+    %7D else %7B%0A        
         
@@ -2030,24 +2030,305 @@
 eturn null;%0A
+            %7D%0A        %7D catch (NativeException ex) %7B%0A            // if a native terminal exists but cannot be resolved, use dumb terminal settings%0A            // this can happen if a terminal is in use that does not have its terminfo installed  %0A            return null;%0A        %7D%0A
     %7D%0A%0A    @

Use dumb terminal settings as a backup