From 13c71757f29d178053f59e6d906e4c899193cd4f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 2 Feb 2013 11:19:23 -0800 Subject: [PATCH] cross-platform and error-tolerant width check (#82) --- beets/config_default.yaml | 1 + beets/ui/__init__.py | 23 +++++++++++++++++++++++ beets/ui/commands.py | 9 ++------- 3 files changed, 26 insertions(+), 7 deletions(-) diff --git a/beets/config_default.yaml b/beets/config_default.yaml index b822d2707..94ba90338 100644 --- a/beets/config_default.yaml +++ b/beets/config_default.yaml @@ -35,6 +35,7 @@ timeout: 5.0 per_disc_numbering: no verbose: no terminal_encoding: utf8 +terminal_width: 80 list_format_item: $artist - $album - $title list_format_album: $albumartist - $album diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index dedf51a8b..6ba97654a 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -27,6 +27,7 @@ import logging import sqlite3 import errno import re +import struct from beets import library from beets import plugins @@ -477,6 +478,28 @@ def print_obj(obj, lib, fmt=None): else: print_(obj.evaluate_template(template, lib=lib)) +def term_width(): + """Get the width (columns) of the terminal.""" + fallback = config['terminal_width'].get(int) + + # The fcntl and termios modules are not available on non-Unix + # platforms, so we fall back to a constant. + try: + import fcntl + import termios + except ImportError: + return fallback + + try: + buf = fcntl.ioctl(0, termios.TIOCGWINSZ, ' '*4) + except IOError: + return fallback + try: + height, width = struct.unpack('hh', buf) + except struct.error: + return fallback + return width + # Subcommand parsing infrastructure. diff --git a/beets/ui/commands.py b/beets/ui/commands.py index e47702c96..c0018a757 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -22,9 +22,6 @@ import os import time import itertools import re -import fcntl -import struct -import termios import beets from beets import ui @@ -185,10 +182,8 @@ def show_change(cur_artist, cur_album, match): pairs = match.mapping.items() pairs.sort(key=lambda (_, track_info): track_info.index) - # Calculate max column width. - buf = fcntl.ioctl(0, termios.TIOCGWINSZ, ' '*4) - height, width = struct.unpack('hh', buf) - col_width = (width - len(''.join([' * ', ' -> ']))) / 2 + # The width of one column in track difference display. + col_width = (ui.term_width() - len(''.join([' * ', ' -> ']))) // 2 # Get each change as a colorized LHS and RHS value, and the length of the # uncolored LHS value.