2026-07-20 09:23:55 -04:00
#!/usr/bin/env -S python3 -u
2013-06-11 22:59:50 -07:00
'''
Copyright 2009, The Android Open Source Project
2013-09-12 10:17:00 +06:30
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
2013-06-11 22:59:50 -07:00
2013-09-12 10:17:00 +06:30
http://www.apache.org/licenses/LICENSE-2.0
2013-06-11 22:59:50 -07:00
2013-09-12 10:17:00 +06:30
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
2013-06-11 22:59:50 -07:00
limitations under the License.
'''
# Script to highlight adb logcat output for console
2014-01-09 15:54:03 -08:00
# Originally written by Jeff Sharkey, http://jsharkey.org/
2013-06-11 22:59:50 -07:00
# Piping detection and popen() added by other Android team members
2014-01-09 15:54:03 -08:00
# Package filtering and output improvements by Jake Wharton, http://jakewharton.com
2013-06-11 22:59:50 -07:00
2013-06-12 08:34:23 -07:00
import argparse
2026-07-20 09:23:55 -04:00
import codecs
import collections
import os
import select
import signal
2014-07-15 12:51:06 -07:00
import sys
2013-06-12 08:34:23 -07:00
import re
2013-06-18 18:32:11 -07:00
import subprocess
2026-07-20 09:23:55 -04:00
import threading
2013-06-18 18:32:11 -07:00
from subprocess import PIPE
2013-06-11 22:59:50 -07:00
2026-07-20 11:44:13 -04:00
__version__ = '2.4.0'
2015-02-17 14:11:25 +01:00
2013-06-24 09:16:07 -07:00
LOG_LEVELS = 'VDIWEF'
2013-06-13 14:08:13 -07:00
LOG_LEVELS_MAP = dict ([( LOG_LEVELS [ i ], i ) for i in range ( len ( LOG_LEVELS ))])
2013-06-12 08:34:23 -07:00
parser = argparse . ArgumentParser ( description = 'Filter logcat by package name' )
2013-10-12 16:04:20 +02:00
parser . add_argument ( 'package' , nargs = '*' , help = 'Application package name(s)' )
2015-05-25 17:50:58 -07:00
parser . add_argument ( '-w' , '--tag-width' , metavar = 'N' , dest = 'tag_width' , type = int , default = 23 , help = 'Width of log tag' )
2014-07-01 20:17:25 +02:00
parser . add_argument ( '-l' , '--min-level' , dest = 'min_level' , type = str , choices = LOG_LEVELS + LOG_LEVELS . lower (), default = 'V' , help = 'Minimum level to be displayed' )
2013-06-12 14:45:48 -07:00
parser . add_argument ( '--color-gc' , dest = 'color_gc' , action = 'store_true' , help = 'Color garbage collection' )
2013-09-12 10:17:00 +06:30
parser . add_argument ( '--always-display-tags' , dest = 'always_tags' , action = 'store_true' , help = 'Always display the tag name' )
2014-08-24 23:03:48 +09:00
parser . add_argument ( '--current' , dest = 'current_app' , action = 'store_true' , help = 'Filter logcat by current running app' )
2013-06-19 08:36:09 -03:00
parser . add_argument ( '-s' , '--serial' , dest = 'device_serial' , help = 'Device serial number (adb -s option)' )
2015-02-17 14:11:25 +01:00
parser . add_argument ( '-d' , '--device' , dest = 'use_device' , action = 'store_true' , help = 'Use first device for log input (adb -d option)' )
parser . add_argument ( '-e' , '--emulator' , dest = 'use_emulator' , action = 'store_true' , help = 'Use first emulator for log input (adb -e option)' )
parser . add_argument ( '-c' , '--clear' , dest = 'clear_logcat' , action = 'store_true' , help = 'Clear the entire log before running' )
2014-08-19 14:02:23 -04:00
parser . add_argument ( '-t' , '--tag' , dest = 'tag' , action = 'append' , help = 'Filter output by specified tag(s)' )
2015-01-16 19:10:09 -02:00
parser . add_argument ( '-i' , '--ignore-tag' , dest = 'ignored_tag' , action = 'append' , help = 'Filter output by ignoring specified tag(s)' )
2015-02-17 14:11:25 +01:00
parser . add_argument ( '-v' , '--version' , action = 'version' , version = ' %(prog)s ' + __version__ , help = 'Print the version number and exit' )
2015-08-12 10:47:16 +08:00
parser . add_argument ( '-a' , '--all' , dest = 'all' , action = 'store_true' , default = False , help = 'Print all log messages' )
2026-07-20 09:23:55 -04:00
parser . add_argument ( '--plain' , dest = 'plain' , action = 'store_true' , help = 'Plain streaming output, without the interactive filter UI' )
2013-06-12 08:34:23 -07:00
args = parser . parse_args ()
2014-07-01 20:17:25 +02:00
min_level = LOG_LEVELS_MAP [ args . min_level . upper ()]
2013-06-12 08:34:23 -07:00
2014-08-24 23:03:48 +09:00
package = args . package
2015-05-27 00:23:55 +09:00
base_adb_command = [ 'adb' ]
if args . device_serial :
base_adb_command . extend ([ '-s' , args . device_serial ])
if args . use_device :
base_adb_command . append ( '-d' )
if args . use_emulator :
base_adb_command . append ( '-e' )
2014-08-24 23:03:48 +09:00
if args . current_app :
2015-05-27 00:23:55 +09:00
system_dump_command = base_adb_command + [ "shell" , "dumpsys" , "activity" , "activities" ]
system_dump = subprocess . Popen ( system_dump_command , stdout = PIPE , stderr = PIPE ) . communicate ()[ 0 ]
2021-02-11 18:25:20 -08:00
running_package_name = re . search ( ".*TaskRecord.*A[= ]([^ ^}]*)" , str ( system_dump )) . group ( 1 )
2014-08-24 23:03:48 +09:00
package . append ( running_package_name )
2015-08-12 10:47:16 +08:00
if len ( package ) == 0 :
args . all = True
2014-03-12 23:35:47 -07:00
# Store the names of packages for which to match all processes.
2022-01-31 10:23:16 -08:00
catchall_package = list ( filter ( lambda package : package . find ( ":" ) == - 1 , package ))
2014-03-12 23:35:47 -07:00
# Store the name of processes to match exactly.
2022-01-31 10:23:16 -08:00
named_processes = list ( filter ( lambda package : package . find ( ":" ) != - 1 , package ))
2014-03-12 23:35:47 -07:00
# Convert default process names from <package>: (cli notation) to <package> (android notation) in the exact names match group.
2026-07-20 09:23:55 -04:00
named_processes = list ( map ( lambda package : package if package . find ( ":" ) != len ( package ) - 1 else package [: - 1 ], named_processes ))
2014-03-12 23:35:47 -07:00
2013-06-12 10:13:27 -07:00
header_size = args . tag_width + 1 + 3 + 1 # space, level, space
2013-06-11 22:59:50 -07:00
2020-07-24 17:14:30 +02:00
stdout_isatty = sys . stdout . isatty ()
2013-06-18 18:32:11 -07:00
width = - 1
try :
# Get the current terminal width
import fcntl , termios , struct
h , width = struct . unpack ( 'hh' , fcntl . ioctl ( 0 , termios . TIOCGWINSZ , struct . pack ( 'hh' , 0 , 0 )))
except :
pass
2013-06-11 22:59:50 -07:00
BLACK , RED , GREEN , YELLOW , BLUE , MAGENTA , CYAN , WHITE = range ( 8 )
2013-06-12 14:45:48 -07:00
RESET = ' \033 [0m'
def termcolor ( fg = None , bg = None ):
2013-06-11 22:59:50 -07:00
codes = []
if fg is not None : codes . append ( '3 %d ' % fg )
if bg is not None : codes . append ( '10 %d ' % bg )
2013-06-12 14:45:48 -07:00
return ' \033 [ %s m' % ';' . join ( codes ) if codes else ''
def colorize ( message , fg = None , bg = None ):
2020-07-24 17:14:30 +02:00
return termcolor ( fg , bg ) + message + RESET if stdout_isatty else message
2013-06-11 22:59:50 -07:00
def indent_wrap ( message ):
2026-07-20 09:23:55 -04:00
wrap_area = width - header_size
# width == -1 means detection failed; a non-positive wrap area (very narrow or
# unsized terminal) would make the loop below never advance, so skip wrapping.
if width == - 1 or wrap_area <= 0 :
2013-06-18 18:32:11 -07:00
return message
2013-07-18 16:38:04 -04:00
message = message . replace ( ' \t ' , ' ' )
2013-06-12 08:18:53 -07:00
messagebuf = ''
2013-06-11 22:59:50 -07:00
current = 0
while current < len ( message ):
next = min ( current + wrap_area , len ( message ))
2013-06-12 08:18:53 -07:00
messagebuf += message [ current : next ]
2013-06-11 22:59:50 -07:00
if next < len ( message ):
2013-06-12 08:18:53 -07:00
messagebuf += ' \n '
2013-06-12 08:34:23 -07:00
messagebuf += ' ' * header_size
2013-06-11 22:59:50 -07:00
current = next
2013-06-12 08:18:53 -07:00
return messagebuf
2013-06-11 22:59:50 -07:00
LAST_USED = [ RED , GREEN , YELLOW , BLUE , MAGENTA , CYAN ]
KNOWN_TAGS = {
'dalvikvm' : WHITE ,
'Process' : WHITE ,
'ActivityManager' : WHITE ,
'ActivityThread' : WHITE ,
'AndroidRuntime' : CYAN ,
'jdwp' : WHITE ,
2013-06-12 14:45:48 -07:00
'StrictMode' : WHITE ,
2014-02-14 00:31:41 -08:00
'DEBUG' : YELLOW ,
2013-06-11 22:59:50 -07:00
}
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 tag not in KNOWN_TAGS :
KNOWN_TAGS [ tag ] = LAST_USED [ 0 ]
color = KNOWN_TAGS [ tag ]
if color in LAST_USED :
LAST_USED . remove ( color )
LAST_USED . append ( color )
return color
RULES = {
2013-06-12 14:45:48 -07:00
# StrictMode policy violation; ~duration=319 ms: android.os.StrictMode$StrictModeDiskWriteViolation: policy=31 violation=1
re . compile ( r '^(StrictMode policy violation)(; ~duration=)(\d+ ms)' )
: r ' %s \1 %s \2 %s \3 %s ' % ( termcolor ( RED ), RESET , termcolor ( YELLOW ), RESET ),
2013-06-11 22:59:50 -07:00
}
2013-06-12 14:45:48 -07:00
# Only enable GC coloring if the user opted-in
if args . color_gc :
# GC_CONCURRENT freed 3617K, 29% free 20525K/28648K, paused 4ms+5ms, total 85ms
2013-06-12 22:26:58 -07:00
key = re . compile ( r '^(GC_(?:CONCURRENT|FOR_M?ALLOC|EXTERNAL_ALLOC|EXPLICIT) )(freed <?\d+.)(, \d+\ % f ree \d+./\d+., )(paused \d+ms(?:\+\d+ms)?)' )
2013-06-12 14:45:48 -07:00
val = r '\1 %s \2 %s \3 %s \4 %s ' % ( termcolor ( GREEN ), RESET , termcolor ( YELLOW ), RESET )
RULES [ key ] = val
2013-06-11 22:59:50 -07:00
TAGTYPES = {
'V' : colorize ( ' V ' , fg = WHITE , bg = BLACK ),
'D' : colorize ( ' D ' , fg = BLACK , bg = BLUE ),
'I' : colorize ( ' I ' , fg = BLACK , bg = GREEN ),
'W' : colorize ( ' W ' , fg = BLACK , bg = YELLOW ),
'E' : colorize ( ' E ' , fg = BLACK , bg = RED ),
2013-06-15 01:48:04 +02:00
'F' : colorize ( ' F ' , fg = BLACK , bg = RED ),
2013-06-11 22:59:50 -07:00
}
2015-08-12 10:47:16 +08:00
PID_LINE = re . compile ( r '^\w+\s+(\w+)\s+\w+\s+\w+\s+\w+\s+\w+\s+\w+\s+\w\s([\w|\.|\/]+)$' )
2014-09-29 21:39:55 -07:00
PID_START = re . compile ( r '^.*: Start proc ([a-zA-Z0-9._:]+) for ([a-z]+ [^:]+): pid=(\d+) uid=(\d+) gids=(.*)$' )
2015-03-14 02:36:24 -04:00
PID_START_5_1 = re . compile ( r '^.*: Start proc (\d+):([a-zA-Z0-9._:]+)/[a-z0-9]+ for (.*)$' )
2014-10-07 14:10:01 -07:00
PID_START_DALVIK = re . compile ( r '^E/dalvikvm\(\s*(\d+)\): >>>>> ([a-zA-Z0-9._:]+) \[ userId:0 \| appId:(\d+) \]$' )
2014-03-27 18:03:12 -07:00
PID_KILL = re . compile ( r '^Killing (\d+):([a-zA-Z0-9._:]+)/[^:]+: (.*)$' )
PID_LEAVE = re . compile ( r '^No longer want ([a-zA-Z0-9._:]+) \(pid (\d+)\): .*$' )
PID_DEATH = re . compile ( r '^Process ([a-zA-Z0-9._:]+) \(pid (\d+)\) has died.?$' )
2013-07-12 15:03:40 +02:00
LOG_LINE = re . compile ( r '^([A-Z])/(.+?)\( *(\d+)\): (.*?)$' )
2013-07-03 16:35:50 -07:00
BUG_LINE = re . compile ( r '.*nativeGetEnabledTags.*' )
2014-02-14 00:31:41 -08:00
BACKTRACE_LINE = re . compile ( r '^#(.*?)pc\s(.*?)$' )
2013-06-11 22:59:50 -07:00
2015-02-17 10:56:38 +01:00
adb_command = base_adb_command [:]
2013-06-19 11:05:43 -07:00
adb_command . append ( 'logcat' )
2015-06-06 11:14:02 +08:00
adb_command . extend ([ '-v' , 'brief' ])
2013-06-19 11:05:43 -07:00
2014-05-14 12:07:34 +02:00
# Clear log before starting logcat
if args . clear_logcat :
adb_clear_command = list ( adb_command )
2014-07-15 12:51:06 -07:00
adb_clear_command . append ( '-c' )
2014-05-14 12:07:34 +02:00
adb_clear = subprocess . Popen ( adb_clear_command )
while adb_clear . poll () is None :
pass
2014-07-15 12:51:06 -07:00
# This is a ducktype of the subprocess.Popen object
class FakeStdinProcess ():
def __init__ ( self ):
2026-07-20 09:23:55 -04:00
self . stdout = sys . stdin . buffer
2014-07-15 12:51:06 -07:00
def poll ( self ):
return None
if sys . stdin . isatty ():
2017-02-17 18:47:35 -05:00
adb = subprocess . Popen ( adb_command , stdin = PIPE , stdout = PIPE )
2014-07-15 12:51:06 -07:00
else :
adb = FakeStdinProcess ()
2013-06-12 09:38:00 -07:00
pids = set ()
2013-06-12 10:17:22 -07:00
last_tag = None
2014-02-14 00:31:41 -08:00
app_pid = None
2013-06-11 22:59:50 -07:00
2013-06-15 17:50:12 +02:00
def match_packages ( token ):
2014-08-24 23:03:48 +09:00
if len ( package ) == 0 :
2013-10-12 16:04:20 +02:00
return True
2014-03-12 23:35:47 -07:00
if token in named_processes :
return True
2013-06-13 14:45:37 -04:00
index = token . find ( ':' )
2014-03-12 23:35:47 -07:00
return ( token in catchall_package ) if index == - 1 else ( token [: index ] in catchall_package )
2013-06-12 18:52:34 -04:00
2013-12-02 00:50:08 -08:00
def parse_death ( tag , message ):
if tag != 'ActivityManager' :
2014-03-12 23:27:39 -07:00
return None , None
2013-12-02 00:50:08 -08:00
kill = PID_KILL . match ( message )
if kill :
pid = kill . group ( 1 )
2014-03-12 23:27:39 -07:00
package_line = kill . group ( 2 )
if match_packages ( package_line ) and pid in pids :
return pid , package_line
2013-12-02 00:50:08 -08:00
leave = PID_LEAVE . match ( message )
if leave :
pid = leave . group ( 2 )
2014-03-12 23:27:39 -07:00
package_line = leave . group ( 1 )
if match_packages ( package_line ) and pid in pids :
return pid , package_line
2013-12-02 00:50:08 -08:00
death = PID_DEATH . match ( message )
if death :
pid = death . group ( 2 )
2014-03-12 23:27:39 -07:00
package_line = death . group ( 1 )
if match_packages ( package_line ) and pid in pids :
return pid , package_line
return None , None
2013-06-12 10:09:30 -07:00
2014-09-29 21:39:55 -07:00
def parse_start_proc ( line ):
2015-03-14 02:36:24 -04:00
start = PID_START_5_1 . match ( line )
if start is not None :
line_pid , line_package , target = start . groups ()
return line_package , target , line_pid , '' , ''
2014-09-29 21:39:55 -07:00
start = PID_START . match ( line )
if start is not None :
line_package , target , line_pid , line_uid , line_gids = start . groups ()
return line_package , target , line_pid , line_uid , line_gids
start = PID_START_DALVIK . match ( line )
if start is not None :
line_pid , line_package , line_uid = start . groups ()
return line_package , '' , line_pid , line_uid , ''
return None
2020-07-24 17:14:30 +02:00
def tag_in_tags_regex ( tag , tags ):
2015-03-14 18:15:28 -07:00
return any ( re . match ( r '^' + t + r '$' , tag ) for t in map ( str . strip , tags ))
2015-02-17 10:56:38 +01:00
ps_command = base_adb_command + [ 'shell' , 'ps' ]
ps_pid = subprocess . Popen ( ps_command , stdin = PIPE , stdout = PIPE , stderr = PIPE )
2015-09-18 16:45:00 +08:00
while True :
2015-02-17 10:56:38 +01:00
try :
line = ps_pid . stdout . readline () . decode ( 'utf-8' , 'replace' ) . strip ()
except KeyboardInterrupt :
break
if len ( line ) == 0 :
break
pid_match = PID_LINE . match ( line )
if pid_match is not None :
pid = pid_match . group ( 1 )
proc = pid_match . group ( 2 )
if proc in catchall_package :
seen_pids = True
pids . add ( pid )
2026-07-20 09:23:55 -04:00
def stream ( emit ):
'''Parse adb output and hand each formatted block to emit(search_text, block).
2013-06-11 22:59:50 -07:00
2026-07-20 09:23:55 -04:00
search_text is the block's plain, markup-free text, used by the interactive
filter; block is the colorized output.
'''
global last_tag , app_pid
2013-06-12 13:30:58 -06:00
2026-07-20 09:23:55 -04:00
while adb . poll () is None :
try :
line = adb . stdout . readline () . decode ( 'utf-8' , 'replace' ) . strip ()
except KeyboardInterrupt :
break
if len ( line ) == 0 :
break
2013-06-11 22:59:50 -07:00
2026-07-20 09:23:55 -04:00
bug_line = BUG_LINE . match ( line )
if bug_line is not None :
continue
2013-12-02 00:50:08 -08:00
2026-07-20 09:23:55 -04:00
log_line = LOG_LINE . match ( line )
if log_line is None :
continue
2014-02-14 00:31:41 -08:00
2026-07-20 09:23:55 -04:00
level , tag , owner , message = log_line . groups ()
tag = tag . strip ()
start = parse_start_proc ( line )
if start :
line_package , target , line_pid , line_uid , line_gids = start
if match_packages ( line_package ):
pids . add ( line_pid )
app_pid = line_pid
linebuf = ' \n '
linebuf += colorize ( ' ' * ( header_size - 1 ), bg = WHITE )
linebuf += indent_wrap ( ' Process %s created for %s \n ' % ( line_package , target ))
linebuf += colorize ( ' ' * ( header_size - 1 ), bg = WHITE )
linebuf += ' PID: %s UID: %s GIDs: %s ' % ( line_pid , line_uid , line_gids )
linebuf += ' \n '
2026-07-20 11:44:13 -04:00
emit ( 'Process %s created for %s PID: %s ' % ( line_package , target , line_pid ), linebuf , is_separator = True )
2026-07-20 09:23:55 -04:00
last_tag = None # Ensure next log gets a tag printed
dead_pid , dead_pname = parse_death ( tag , message )
if dead_pid :
pids . remove ( dead_pid )
2013-12-02 00:50:08 -08:00
linebuf = ' \n '
2026-07-20 09:23:55 -04:00
linebuf += colorize ( ' ' * ( header_size - 1 ), bg = RED )
linebuf += ' Process %s (PID: %s ) ended' % ( dead_pname , dead_pid )
2013-12-02 00:50:08 -08:00
linebuf += ' \n '
2026-07-20 11:44:13 -04:00
emit ( 'Process %s (PID: %s ) ended' % ( dead_pname , dead_pid ), linebuf , is_separator = True )
2013-12-02 00:50:08 -08:00
last_tag = None # Ensure next log gets a tag printed
2026-07-20 09:23:55 -04:00
# Make sure the backtrace is printed after a native crash
if tag == 'DEBUG' :
bt_line = BACKTRACE_LINE . match ( message . lstrip ())
if bt_line is not None :
message = message . lstrip ()
owner = app_pid
2013-12-02 00:50:08 -08:00
2026-07-20 09:23:55 -04:00
if not args . all and owner not in pids :
continue
if level in LOG_LEVELS_MAP and LOG_LEVELS_MAP [ level ] < min_level :
continue
if args . ignored_tag and tag_in_tags_regex ( tag , args . ignored_tag ):
continue
if args . tag and not tag_in_tags_regex ( tag , args . tag ):
continue
2014-02-14 00:31:41 -08:00
2026-07-20 09:23:55 -04:00
# Captured before color markup is added to the message.
search_text = ' %s %s %s ' % ( level , tag , message )
2013-06-19 14:18:52 -07:00
2026-07-20 09:23:55 -04:00
linebuf = ''
2013-06-19 14:18:52 -07:00
2026-07-20 09:23:55 -04:00
if args . tag_width > 0 :
# right-align tag title and allocate color if needed
if tag != last_tag or args . always_tags :
last_tag = tag
color = allocate_color ( tag )
tag = tag [ - args . tag_width :] . rjust ( args . tag_width )
linebuf += colorize ( tag , fg = color )
else :
linebuf += ' ' * args . tag_width
linebuf += ' '
# write out level colored edge
if level in TAGTYPES :
linebuf += TAGTYPES [ level ]
2016-01-30 03:12:27 +03:00
else :
2026-07-20 09:23:55 -04:00
linebuf += ' ' + level + ' '
2016-01-30 03:12:27 +03:00
linebuf += ' '
2013-06-19 14:18:52 -07:00
2026-07-20 09:23:55 -04:00
# format tag message using rules
for matcher in RULES :
replace = RULES [ matcher ]
message = matcher . sub ( replace , message )
2013-06-19 14:18:52 -07:00
2026-07-20 09:23:55 -04:00
linebuf += indent_wrap ( message )
emit ( search_text , linebuf )
2013-06-19 14:18:52 -07:00
2026-07-20 09:23:55 -04:00
class InteractiveUI :
'''Full-screen filter UI: log lines render above a bottom prompt line, and the
typed query live-filters the scrollback. Every whitespace-separated word must
2026-07-20 11:44:13 -04:00
appear in a block's plain text (case-insensitive) for it to be shown, except
process create/death separators, which always stay visible so filtered runs
can still be told apart.'''
2026-07-20 09:23:55 -04:00
MAX_ENTRIES = 10000 # (search_text, block) pairs kept for re-filtering
MAX_VISIBLE = 5000 # rendered lines kept for the current query
def __init__ ( self ):
self . lock = threading . Lock ()
2026-07-20 11:44:13 -04:00
self . entries = collections . deque ( maxlen = self . MAX_ENTRIES ) # (entry_id, search_lower, block, is_separator)
2026-07-20 11:07:20 -04:00
self . visible = [] # (entry_id, line_text)
self . next_entry_id = 0
2026-07-20 09:23:55 -04:00
self . query = ''
self . status = ''
self . resized = False
2026-07-20 11:07:20 -04:00
self . scroll_offset = 0 # lines scrolled up from the tail; 0 == following the live tail
2026-07-20 11:44:13 -04:00
self . hover_row = None # 0-based screen row the pointer is over, or None
self . selected_index = None # index into self.visible pinned by the last click, or None
2026-07-20 09:23:55 -04:00
self . rows , self . cols = self . _term_size ()
def _term_size ( self ):
try :
size = os . get_terminal_size ( sys . stdout . fileno ())
rows , cols = size . lines , size . columns
except OSError :
rows , cols = 24 , 80
if rows < 5 or cols < 20 :
rows , cols = 24 , 80
return rows , cols
def _matches ( self , search_lower ):
return all ( token in search_lower for token in self . query . lower () . split ())
2026-07-20 11:44:13 -04:00
def _included ( self , search_lower , is_separator ):
# Process create/death separators ignore the filter so a run boundary is
# never hidden by an unrelated search.
return is_separator or self . _matches ( search_lower )
2026-07-20 11:07:20 -04:00
def _append_visible ( self , entry_id , block ):
new_lines = [( entry_id , line ) for line in block . split ( ' \n ' )]
self . visible . extend ( new_lines )
if self . scroll_offset > 0 :
# Keep whatever the user is currently looking at in place instead of
# letting newly-arrived lines push it down and out of view.
self . scroll_offset += len ( new_lines )
overflow = len ( self . visible ) - self . MAX_VISIBLE
if overflow > 0 :
del self . visible [: overflow ]
self . scroll_offset = max ( 0 , self . scroll_offset - overflow )
2026-07-20 11:44:13 -04:00
if self . selected_index is not None :
self . selected_index -= overflow
if self . selected_index < 0 :
self . selected_index = None
2026-07-20 09:23:55 -04:00
2026-07-20 11:44:13 -04:00
def emit ( self , search_text , block , is_separator = False ):
2026-07-20 09:23:55 -04:00
with self . lock :
2026-07-20 11:07:20 -04:00
entry_id = self . next_entry_id
self . next_entry_id += 1
2026-07-20 09:23:55 -04:00
search_lower = search_text . lower ()
2026-07-20 11:44:13 -04:00
self . entries . append (( entry_id , search_lower , block , is_separator ))
if self . _included ( search_lower , is_separator ):
2026-07-20 11:07:20 -04:00
self . _append_visible ( entry_id , block )
2026-07-20 09:23:55 -04:00
self . _render ()
def set_query ( self , query ):
with self . lock :
self . query = query
self . visible = []
2026-07-20 11:07:20 -04:00
self . scroll_offset = 0
2026-07-20 11:44:13 -04:00
self . selected_index = None # a new search replaces whatever was pinned
for entry_id , search_lower , block , is_separator in self . entries :
if self . _included ( search_lower , is_separator ):
2026-07-20 11:07:20 -04:00
self . _append_visible ( entry_id , block )
2026-07-20 09:23:55 -04:00
self . _render ()
def refresh ( self ):
global width
with self . lock :
self . rows , self . cols = self . _term_size ()
width = self . cols # future indent_wrap calls track the new size
self . _render ()
2026-07-20 11:44:13 -04:00
def _window_bounds ( self ):
'''Returns (start, end, pad): the self.visible slice currently on screen and
how many blank padding rows precede it (when there isn't enough content yet
to fill the log area).'''
2026-07-20 09:23:55 -04:00
log_rows = max ( 1 , self . rows - 2 )
2026-07-20 11:07:20 -04:00
max_offset = max ( 0 , len ( self . visible ) - log_rows )
if self . scroll_offset > max_offset :
self . scroll_offset = max_offset
end = len ( self . visible ) - self . scroll_offset
start = max ( 0 , end - log_rows )
2026-07-20 11:44:13 -04:00
pad = log_rows - ( end - start )
return start , end , pad
def _render ( self ):
log_rows = max ( 1 , self . rows - 2 )
start , end , pad = self . _window_bounds ()
2026-07-20 11:07:20 -04:00
window = self . visible [ start : end ]
2026-07-20 09:23:55 -04:00
out = [ ' \x1b [H' ]
# Pad above so the log content hugs the prompt, like a terminal.
2026-07-20 11:44:13 -04:00
for _ in range ( pad ):
2026-07-20 09:23:55 -04:00
out . append ( ' \x1b [K \n ' )
2026-07-20 11:44:13 -04:00
for i , ( _ , line ) in enumerate ( window ):
# Only hint clickability when a filter is active; with no filter a
# click is a no-op, so there's nothing to invite the user to click.
hovered = self . query and self . hover_row == pad + i
selected = self . selected_index == start + i
if hovered or selected :
out . append ( ' \x1b [7m' + line . replace ( RESET , RESET + ' \x1b [7m' ) + RESET + ' \x1b [K \n ' )
else :
out . append ( line + ' \x1b [K \n ' )
2026-07-20 09:23:55 -04:00
if self . query :
state = ' %d matching lines of %d blocks' % ( len ( self . visible ), len ( self . entries ))
else :
state = ' %d blocks' % len ( self . entries )
2026-07-20 11:07:20 -04:00
if self . scroll_offset > 0 :
state += ' \xb7 scrolled (End to jump to latest)'
2026-07-20 09:23:55 -04:00
if self . status :
state += ' \xb7 ' + self . status
2026-07-20 11:44:13 -04:00
hint = ' \xb7 click a line to unfilter' if self . query else ''
separator = ' %s \xb7 type to filter \xb7 ctrl-u clear %s \xb7 esc/ctrl-c quit' % ( state , hint )
2026-07-20 09:23:55 -04:00
out . append ( ' \x1b [2m' + separator [: max ( 0 , self . cols - 1 )] + ' \x1b [0m \x1b [K \n ' )
out . append ( ' \x1b [36m❯ \x1b [0m ' + self . query + ' \x1b [K' )
sys . stdout . write ( '' . join ( out ))
sys . stdout . flush ()
2026-07-20 11:07:20 -04:00
MOUSE_RE = re . compile ( r '^\[<(\d+);(\d+);(\d+)([Mm])$' )
def _scroll ( self , delta ):
with self . lock :
log_rows = max ( 1 , self . rows - 2 )
max_offset = max ( 0 , len ( self . visible ) - log_rows )
self . scroll_offset = max ( 0 , min ( max_offset , self . scroll_offset + delta ))
self . _render ()
def _handle_click ( self , row ):
with self . lock :
2026-07-20 11:44:13 -04:00
if not self . query : # nothing to unfilter, so clicking is a no-op
2026-07-20 11:07:20 -04:00
return
2026-07-20 11:44:13 -04:00
log_rows = max ( 1 , self . rows - 2 )
start , _end , pad = self . _window_bounds ()
if row < 1 or row > log_rows or row <= pad :
return
idx = start + ( row - 1 - pad )
2026-07-20 11:07:20 -04:00
if idx < 0 or idx >= len ( self . visible ):
return
entry_id = self . visible [ idx ][ 0 ]
self . _jump_to_entry ( entry_id )
2026-07-20 11:44:13 -04:00
def _handle_hover ( self , row ):
with self . lock :
log_rows = max ( 1 , self . rows - 2 )
_start , _end , pad = self . _window_bounds ()
new_hover = ( row - 1 ) if ( 1 <= row <= log_rows and row > pad ) else None
if new_hover == self . hover_row :
return
self . hover_row = new_hover
self . _render ()
2026-07-20 11:07:20 -04:00
def _jump_to_entry ( self , entry_id ):
'''Clears the filter, rebuilds the full unfiltered scrollback, and scrolls
2026-07-20 11:44:13 -04:00
so the clicked entry is in view with a bit of context above it. The entry's
line stays pinned/highlighted until another search starts.'''
2026-07-20 11:07:20 -04:00
with self . lock :
self . query = ''
self . visible = []
self . scroll_offset = 0
target_index = None
2026-07-20 11:44:13 -04:00
for eid , _search_lower , block , _is_separator in self . entries :
2026-07-20 11:07:20 -04:00
for line in block . split ( ' \n ' ):
if target_index is None and eid == entry_id :
target_index = len ( self . visible )
self . visible . append (( eid , line ))
overflow = len ( self . visible ) - self . MAX_VISIBLE
if overflow > 0 :
del self . visible [: overflow ]
if target_index is not None :
target_index -= overflow
if target_index is not None and target_index >= 0 :
2026-07-20 11:44:13 -04:00
self . selected_index = target_index
2026-07-20 11:07:20 -04:00
log_rows = max ( 1 , self . rows - 2 )
max_offset = max ( 0 , len ( self . visible ) - log_rows )
desired_end = target_index + max ( 1 , log_rows // 3 )
self . scroll_offset = max ( 0 , min ( max_offset , len ( self . visible ) - desired_end ))
2026-07-20 11:44:13 -04:00
else :
self . selected_index = None
2026-07-20 11:07:20 -04:00
self . _render ()
def _handle_escape ( self , seq ):
m = self . MOUSE_RE . match ( seq )
if m :
button , _col , row , kind = m . groups ()
if kind != 'M' : # ignore button-release reports
return
button = int ( button )
if button == 0 : # left click
self . _handle_click ( int ( row ))
2026-07-20 11:44:13 -04:00
elif button == 35 : # pointer moved, no button held
self . _handle_hover ( int ( row ))
2026-07-20 11:07:20 -04:00
elif button == 64 : # wheel up
self . _scroll ( 3 )
elif button == 65 : # wheel down
self . _scroll ( - 3 )
return
log_rows = max ( 1 , self . rows - 2 )
if seq in ( '[A' , 'OA' ): # up
self . _scroll ( 1 )
elif seq in ( '[B' , 'OB' ): # down
self . _scroll ( - 1 )
elif seq == '[5~' : # page up
self . _scroll ( log_rows )
elif seq == '[6~' : # page down
self . _scroll ( - log_rows )
elif seq in ( '[H' , '[1~' ): # home
self . _scroll ( 10 ** 9 )
elif seq in ( '[F' , '[4~' ): # end
self . _scroll ( - ( 10 ** 9 ))
def _read_escape ( self , pending , fd , decoder ):
'''Consumes the sequence following an ESC already pulled from `pending`.
Returns (seq, rest_of_pending). seq is None for a standalone Escape
keypress (nothing followed it within the grace window), '' when ESC was
followed by something unrelated, or the sequence body (e.g. '[A')
otherwise.'''
if not pending :
# Give a fast terminal-generated sequence (arrow keys, mouse reports)
# a brief window to arrive before treating this as a lone Escape.
if select . select ([ fd ], [], [], 0.01 )[ 0 ]:
data = os . read ( fd , 64 )
if data :
pending = decoder . decode ( data )
if not pending :
return None , pending
introducer = pending [ 0 ]
if introducer not in ( '[' , 'O' ):
return '' , pending
seq = introducer
pending = pending [ 1 :]
while not ( seq [ - 1 ] . isalpha () or seq [ - 1 ] == '~' ):
if not pending :
if select . select ([ fd ], [], [], 0.01 )[ 0 ]:
data = os . read ( fd , 64 )
if data :
pending += decoder . decode ( data )
continue
2026-07-20 09:23:55 -04:00
break
2026-07-20 11:07:20 -04:00
seq += pending [ 0 ]
pending = pending [ 1 :]
return seq , pending
2026-07-20 09:23:55 -04:00
def run ( self , reader_thread ):
fd = sys . stdin . fileno ()
old_attrs = termios . tcgetattr ( fd )
decoder = codecs . getincrementaldecoder ( 'utf-8' )( 'replace' )
signal . signal ( signal . SIGWINCH , lambda * _ : setattr ( self , 'resized' , True ))
2026-07-20 11:44:13 -04:00
# Alt screen, no autowrap, mouse click/wheel/motion reporting (SGR encoding).
sys . stdout . write ( ' \x1b [?1049h \x1b [?7l \x1b [2J \x1b [H \x1b [?1000h \x1b [?1003h \x1b [?1006h' )
2026-07-20 09:23:55 -04:00
sys . stdout . flush ()
tty . setcbreak ( fd )
reader_thread . start ()
2026-07-20 11:07:20 -04:00
pending = '' # decoded characters carried over between reads
2026-07-20 09:23:55 -04:00
try :
with self . lock :
self . _render ()
while True :
if self . resized :
self . resized = False
self . refresh ()
if not reader_thread . is_alive () and not self . status :
self . status = 'adb ended, scrollback still filterable'
with self . lock :
self . _render ()
2026-07-20 11:07:20 -04:00
if not pending :
if not select . select ([ fd ], [], [], 0.2 )[ 0 ]:
continue
data = os . read ( fd , 64 )
if not data :
2026-07-20 09:23:55 -04:00
break
2026-07-20 11:07:20 -04:00
pending = decoder . decode ( data )
if not pending :
continue
ch , pending = pending [ 0 ], pending [ 1 :]
if ch in ( ' \x7f ' , ' \x08 ' ): # backspace
if self . query :
self . set_query ( self . query [: - 1 ])
elif ch == ' \x15 ' : # ctrl-u
if self . query :
self . set_query ( '' )
elif ch == ' \x04 ' : # ctrl-d
return
elif ch == ' \x0c ' : # ctrl-l
self . refresh ()
elif ch == ' \x1b ' :
seq , pending = self . _read_escape ( pending , fd , decoder )
if seq is None : # standalone Escape keypress
return
if seq :
self . _handle_escape ( seq )
elif ch in ( ' \r ' , ' \n ' , ' \t ' ):
pass
elif ch >= ' ' :
self . set_query ( self . query + ch )
2026-07-20 09:23:55 -04:00
except KeyboardInterrupt :
pass
finally :
termios . tcsetattr ( fd , termios . TCSADRAIN , old_attrs )
2026-07-20 11:44:13 -04:00
sys . stdout . write ( ' \x1b [?1006l \x1b [?1003l \x1b [?1000l \x1b [?7h \x1b [?1049l' )
2026-07-20 09:23:55 -04:00
sys . stdout . flush ()
interactive = sys . stdin . isatty () and stdout_isatty and not args . plain
if interactive :
try :
import termios
import tty
except ImportError :
interactive = False # not a POSIX terminal; stream like before
if interactive :
ui = InteractiveUI ()
stream_thread = threading . Thread ( target = stream , args = ( ui . emit ,), daemon = True )
ui . run ( stream_thread )
else :
if hasattr ( signal , 'SIGPIPE' ):
# Die quietly like other unix filters when the downstream reader closes,
# e.g. `pidcat --plain <pkg> | head`.
signal . signal ( signal . SIGPIPE , signal . SIG_DFL )
2026-07-20 11:44:13 -04:00
stream ( lambda search_text , block , is_separator = False : print ( block ))