|
| 1 | +package com.mycmd.commands; |
| 2 | + |
| 3 | +import com.mycmd.Command; |
| 4 | +import com.mycmd.ShellContext; |
| 5 | + |
| 6 | +public class ColorCommand implements Command { |
| 7 | + @Override |
| 8 | + public void execute(String[] args, ShellContext context) { |
| 9 | + if (args.length == 1) { |
| 10 | + String color = args[0]; |
| 11 | + |
| 12 | + if (color.length() != 2) { |
| 13 | + System.out.println("Usage: color <background><text>"); |
| 14 | + return; |
| 15 | + } |
| 16 | + |
| 17 | + String background = String.valueOf(color.charAt(0)); |
| 18 | + String text = String.valueOf(color.charAt(1)); |
| 19 | + |
| 20 | + if (background.equals(text)) { |
| 21 | + return; |
| 22 | + } |
| 23 | + |
| 24 | + int bgIndex, fgIndex; |
| 25 | + try { |
| 26 | + bgIndex = Integer.parseInt(background,16); |
| 27 | + fgIndex = Integer.parseInt(text,16); |
| 28 | + } catch (NumberFormatException e) { |
| 29 | + System.out.println("Invalid color code. must use two hexadecimal digits."); |
| 30 | + System.out.println("Example: color 0A"); |
| 31 | + return; |
| 32 | + } |
| 33 | + |
| 34 | + String[] ansiForeground = {"30","34","32","36","31","35","33","37","90","94","92","96","91","95","93","97"}; |
| 35 | + String[] ansiBackground = {"40","44","42","46","41","45","43","47","100","104","102","106","101","105","103","107"}; |
| 36 | + |
| 37 | + if (bgIndex >= ansiBackground.length || fgIndex >= ansiForeground.length) { |
| 38 | + System.out.println("Invalid color code. must use two hexadecimal digits."); |
| 39 | + System.out.println("Example: color 0A"); |
| 40 | + return; |
| 41 | + } |
| 42 | + |
| 43 | + String bg = "\033[" + ansiBackground[bgIndex] + "m"; |
| 44 | + String fg = "\033[" + ansiForeground[fgIndex] + "m"; |
| 45 | + |
| 46 | + System.out.println(bg + fg); |
| 47 | + } |
| 48 | + |
| 49 | + else { |
| 50 | + // set default color |
| 51 | + System.out.println("\033[0m"); |
| 52 | + } |
| 53 | + } |
| 54 | +} |
0 commit comments