#!/usr/bin/python

'''
    Copyright 2009, The Android Open Source Project

    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.

 - original from http://jsharkey.org/blog/2009/04/22/modifying-the-android-logcat-stream-for-full-color-debugging/
 - added 'adb logcat -v threadtime' parse, ll-component detect, format&color mods -tdh
 - usage example:
  ./logcat-colorize -v threadtime LL:V QAtools:I PackageManager:V ActivityManager:V IntentResolver:V *:S ControlsAndInsight:V
  adb -d logcat -v threadtime | grep V3C | ./logcat-colorize -vtt
'''

# script to highlight adb logcat output for console
# written by jeff sharkey, http://jsharkey.org/
# piping detection and popen() added by other android team members

import os, sys, re, StringIO
import fcntl, termios, struct

# unpack the current terminal width/height
try:
    data = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, '1234')
    HEIGHT, WIDTH = struct.unpack('hh',data)
except IOError:
    HEIGHT, WIDTH = 24, 160

BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)

def format(fg=None, bg=None, bright=False, bold=False, dim=False, reset=False):
    # manually derived from http://en.wikipedia.org/wiki/ANSI_escape_code#Codes
    codes = []
    if reset: codes.append("0")
    else:
        if not fg is None: codes.append("3%d" % (fg))
        if not bg is None:
            if not bright: codes.append("4%d" % (bg))
            else: codes.append("10%d" % (bg))
        if bold: codes.append("1")
        elif dim: codes.append("2")
        else: codes.append("22")
    return "\033[%sm" % (";".join(codes))


def indent_wrap(message, indent=0, width=80):
    wrap_area = width - indent
    messagebuf = StringIO.StringIO()
    current = 0
    while current < len(message):
        next = min(current + wrap_area, len(message))
        messagebuf.write(message[current:next])
        if next < len(message):
            messagebuf.write("\n%s" % (" " * indent))
        current = next
    return messagebuf.getvalue()


# don't use RED; errors only
# don't use WHITE; can't see
LAST_USED = [GREEN,YELLOW,BLUE,MAGENTA,CYAN]
KNOWN_TAGS = {
    "dalvikvm": BLUE,
    "Process": BLUE,
    "ActivityManager": CYAN,
    "ActivityThread": CYAN,
    "V3Client": YELLOW,
}

def allocate_color(tag):
    # this will allocate a unique format for the given tag
    # since we dont have very many colors, we always keep track of the LRU
    if not tag in KNOWN_TAGS:
        KNOWN_TAGS[tag] = LAST_USED[0]
    color = KNOWN_TAGS[tag]
    LAST_USED.remove(color)
    LAST_USED.append(color)
    return color


RULES = {
    #re.compile(r"([\w\.@]+)=([\w\.@]+)"): r"%s\1%s=%s\2%s" % (format(fg=BLACK), format(fg=YELLOW), format(fg=BLACK), format(reset=True)),
}

TAGTYPE_WIDTH = 3
TAG_WIDTH = 20 
PROCESS_WIDTH = 6  # 6 or 8 or -1
HEADER_SIZE = TAGTYPE_WIDTH + 1 + TAG_WIDTH + 1 + PROCESS_WIDTH + 1

TAGTYPES = {
    "V": "%s%s%s " % (format(fg=BLACK), "V".center(TAGTYPE_WIDTH), format(reset=True)),
    "D": "%s%s%s " % (format(fg=BLUE), "D".center(TAGTYPE_WIDTH), format(reset=True)),
    "I": "%s%s%s " % (format(fg=MAGENTA), "I".center(TAGTYPE_WIDTH), format(reset=True)),
    "W": "%s%s%s " % (format(fg=YELLOW), "W".center(TAGTYPE_WIDTH), format(reset=True)),
    "E": "%s%s%s " % (format(fg=RED), "E".center(TAGTYPE_WIDTH), format(reset=True)),
}
TAGCOLORS = {
    "V": "%s" % (format(fg=BLACK)),
    "D": "%s" % (format(fg=BLUE)),
    "I": "%s" % (format(fg=MAGENTA)),
    "W": "%s" % (format(fg=YELLOW)),
    "E": "%s" % (format(fg=RED)),
}

  # D/DeviceStorageMonitorService( 1376): OoO SMS Memory available. SMS_AVAILABLE_THRESHOLD == 524288
retag = re.compile("^([A-Z])/([^\(]+)\(([^\)]+)\): (.*)$")

  # ll.v.u.Response.handleResponse:34  | HTTP resp hdr: Date: Wed, 07 Dec 2011 02:24:20 GMT
llmsg = re.compile("(^[^|]*) \| (.*)$")

# to pick up logcat args (not adb args), or add "-vtt" to force
adb_args = ' '.join(sys.argv[1:])
usingThreadtime = False
if len(sys.argv) > 1 and sys.argv[1] == "-vtt":
    usingThreadtime = True

# if someone is piping in to us, use stdin as input.  if not, invoke adb logcat
if os.isatty(sys.stdin.fileno()):
    if adb_args.find("threadtime") != -1:
        usingThreadtime = True
    print "running: adb logcat %s" % adb_args
    input = os.popen("adb logcat %s" % adb_args)
else:
    input = sys.stdin

if usingThreadtime:
    # 12-06 08:29:56.657  1376  1394 I DeviceStorageMonitorService: Posting Message again
    retag = re.compile("^([0-9]{1,2}-[0-9]{1,2} [0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3})\s+[0-9]+\s+([0-9]+)\s+([A-Z])([^:]+): (.*)$")
    DATE_WIDTH = 19
    HEADER_SIZE += DATE_WIDTH

while True:
    try:
        line = input.readline()
    except KeyboardInterrupt:
        break

    match = retag.match(line)
    if not match is None:
        if usingThreadtime:
	    date, owner, tagtype, tag, message = match.groups()
        else:
            tagtype, tag, owner, message = match.groups()
        linebuf = StringIO.StringIO()

        # date
        if usingThreadtime:
            linebuf.write("%s " % date)

        # center process info
        if PROCESS_WIDTH > 0:
            owner = owner.strip().center(PROCESS_WIDTH)
            linebuf.write("%s%s%s " % (format(fg=BLACK, bg=BLACK, bright=True), owner, format(reset=True)))

        # right-align tag title and allocate color if needed
        tag = tag.strip()
        color = allocate_color(tag)
        tag = tag[-TAG_WIDTH:].rjust(TAG_WIDTH)
        linebuf.write("%s%s %s" % (format(fg=color, dim=False), tag, format(reset=True)))

        # write out tagtype colored edge
        if not tagtype in TAGTYPES: break
        linebuf.write(TAGTYPES[tagtype])

        # insert line wrapping as needed
        message = indent_wrap(message, HEADER_SIZE, WIDTH)

        # format tag message using rules
        for matcher in RULES:
            replace = RULES[matcher]
            message = matcher.sub(replace, message)

        llmatch = llmsg.match(message)
        if llmatch:
            component, remaining = llmatch.groups()
            linebuf.write("%s%s | %s%s%s" % (format(fg=BLACK, dim=False), component, TAGCOLORS[tagtype], remaining, format(reset=True)))
        else:
            linebuf.write("%s%s%s" % (TAGCOLORS[tagtype], message, format(reset=True)))

        line = linebuf.getvalue()

    print line
    if len(line) == 0: break

