|
|
#-*- coding: utf-8 -*-
|
|
|
|
|
|
# Copyright 2014 Calculate Ltd. http://www.calculate-linux.org
|
|
|
#
|
|
|
# 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.
|
|
|
|
|
|
from output import BaseOutput
|
|
|
from palette import (TextState, BaseColorMapping, ConsoleCodesInfo,
|
|
|
LightColorMapping, ConsoleColor256)
|
|
|
from calculate.lib.utils.tools import SavableIterator
|
|
|
from itertools import ifilter
|
|
|
import re
|
|
|
|
|
|
class ConsoleCodesConverter(object):
|
|
|
"""Преобразователь текста из цветного консольного вывода через объект
|
|
|
форматирования.
|
|
|
|
|
|
Объект форматирования должен реализовывать BaseOutput
|
|
|
|
|
|
>>> cct = ConsoleCodesConverter(BaseOutput())
|
|
|
>>> outtext = "\033[32;1mHello\033[0;39m"
|
|
|
>>> cct.transform(outtext)
|
|
|
'Hello'
|
|
|
>>> cct = ConsoleCodesConverter(SpanCssOutput())
|
|
|
>>> outtext = "\033[32;1mHello\033[0;39m"
|
|
|
>>> cct.transform(outtext)
|
|
|
'<span style="colortext:Green;font-weight:bold;">Hello</span>'
|
|
|
"""
|
|
|
|
|
|
class CodeElement:
|
|
|
"""Элемент кода в ESC последовательности"""
|
|
|
def __init__(self,condition=lambda code:False,action=lambda :None):
|
|
|
self.action = action
|
|
|
self.condition = condition
|
|
|
|
|
|
def tryParse(self,code):
|
|
|
"""Обрабатывает ли экземпляр код"""
|
|
|
return self.condition(code)
|
|
|
|
|
|
def parse(self,code,codes):
|
|
|
"""Обработать код, вызвать действие"""
|
|
|
self.action()
|
|
|
|
|
|
def _next_code(self,other):
|
|
|
"""
|
|
|
Получить следующий код
|
|
|
"""
|
|
|
try:
|
|
|
return int(other.next())
|
|
|
except StopIteration:
|
|
|
return None
|
|
|
|
|
|
class ColorElement:
|
|
|
"""Элемент кода для указания стандартного цвета
|
|
|
|
|
|
Проверка кода в интервале, запуск действия с передачей цвета
|
|
|
"""
|
|
|
# соответствие консольных цветов внутренним цветам
|
|
|
mapColors = BaseColorMapping.mapConsole_TS
|
|
|
|
|
|
def __init__(self,action=lambda x:None, begin=None, end=None):
|
|
|
self.action = action
|
|
|
self.begin = begin
|
|
|
self.end = end
|
|
|
|
|
|
def tryParse(self,code):
|
|
|
cci = ConsoleCodesInfo
|
|
|
return code >=self.begin and code <= self.end
|
|
|
|
|
|
def parse(self,code,codes):
|
|
|
cci = ConsoleCodesInfo
|
|
|
return self.action(self.mapColors.get(code-self.begin,
|
|
|
TextState.Colors.DEFAULT))
|
|
|
|
|
|
def __init__(self,output=None,escSymb="\033"):
|
|
|
self.output = output or BaseOutput()
|
|
|
self.escSymb = escSymb
|
|
|
self.escBlock = r"{esc}\[(\d+(?:;\d+)*)m".format(esc=escSymb)
|
|
|
self.reEscBlock = re.compile(self.escBlock)
|
|
|
self.reParse = re.compile(
|
|
|
"(?:{0})?(.*?)(?=$|{0})".format(self.escBlock),
|
|
|
re.DOTALL)
|
|
|
resetBoldHalfbright = lambda : (
|
|
|
(self.output.resetBold() or "") +
|
|
|
(self.output.resetHalfbright() or ""))
|
|
|
cci = ConsoleCodesInfo
|
|
|
element = self.CodeElement
|
|
|
|
|
|
# набор правил обработки кодов
|
|
|
reset = element(lambda code:code==cci.RESET, self.output.reset)
|
|
|
bold = element(lambda code:code==cci.BOLD, self.output.setBold)
|
|
|
halfbright = element(lambda code:code==cci.HALFBRIGHT,
|
|
|
self.output.setHalfbright)
|
|
|
underline = element(lambda code:code==cci.UNDERLINE,
|
|
|
self.output.setUnderline)
|
|
|
nounderline = element(lambda code:code==cci.NOUNDERLINE,
|
|
|
self.output.resetUnderline)
|
|
|
invert = element(lambda code:code==cci.INVERT,
|
|
|
self.output.setInvert)
|
|
|
noinvert = element(lambda code:code==cci.NOINVERT,
|
|
|
self.output.resetInvert)
|
|
|
normal = element(lambda code:code==cci.NORMAL,
|
|
|
resetBoldHalfbright)
|
|
|
reset_foreground = element(lambda code:code==cci.FOREGROUND_DEFAULT,
|
|
|
self.output.resetForeground)
|
|
|
reset_background = element(lambda code:code==cci.BACKGROUND_DEFAULT,
|
|
|
self.output.resetBackground)
|
|
|
foreground = self.ColorElement(begin=cci.FOREGROUND,
|
|
|
end=cci.FOREGROUND_END,action=self.output.setForeground)
|
|
|
background = self.ColorElement(begin=cci.BACKGROUND,
|
|
|
end=cci.BACKGROUND_END,action=self.output.setBackground)
|
|
|
self.grams = [reset,bold,halfbright,underline,nounderline,normal,
|
|
|
invert,noinvert,foreground,background]
|
|
|
|
|
|
def outputText(self,s):
|
|
|
return self.output.outputText(s)
|
|
|
|
|
|
def transform(self,s):
|
|
|
"""
|
|
|
Запустить преобразование текста
|
|
|
"""
|
|
|
def generator():
|
|
|
for ctrl,txt,_s in self.reParse.findall(s):
|
|
|
if ctrl:
|
|
|
codes = SavableIterator(ctrl.split(';'))
|
|
|
for code in codes:
|
|
|
code = int(code)
|
|
|
res = ""
|
|
|
for gram in ifilter(lambda x:x.tryParse(code),
|
|
|
self.grams):
|
|
|
res = gram.parse(code,codes)
|
|
|
break
|
|
|
if res:
|
|
|
yield res
|
|
|
if txt:
|
|
|
yield self.outputText(txt)
|
|
|
yield self.output.endText()
|
|
|
return "".join(list(filter(None,generator())))
|
|
|
|
|
|
def detect(self,s):
|
|
|
"""
|
|
|
Определить есть ли в тексте управляющие последовательности
|
|
|
"""
|
|
|
return bool(self.reEscBlock.search(s))
|
|
|
|
|
|
class ConsoleCodes256Converter(ConsoleCodesConverter):
|
|
|
"""Расширяет возможность обработки 256 цветного терминала"""
|
|
|
|
|
|
class Color256Element(ConsoleCodesConverter.CodeElement):
|
|
|
def __init__(self, action=lambda x: None, begin=None):
|
|
|
self.action = action
|
|
|
self.begin = begin
|
|
|
|
|
|
def tryParse(self, code):
|
|
|
return code == self.begin
|
|
|
|
|
|
def parse(self, code, codes):
|
|
|
"""
|
|
|
Тон: 38;5;0-255
|
|
|
Фон: 48;5;0-255
|
|
|
"""
|
|
|
colorMap = LightColorMapping(BaseColorMapping).mapConsole_TS
|
|
|
|
|
|
codes.save()
|
|
|
if self._next_code(codes) == ConsoleCodesInfo.COLOR256:
|
|
|
code = self._next_code(codes)
|
|
|
if code is not None:
|
|
|
if code in colorMap:
|
|
|
self.action(colorMap[code])
|
|
|
else:
|
|
|
self.action(ConsoleColor256.consoleToRgb(code))
|
|
|
else:
|
|
|
# если после 38 не 5 - не обрабатываем этот код
|
|
|
codes.restore()
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
ConsoleCodesConverter.__init__(self, *args, **kwargs)
|
|
|
cci = ConsoleCodesInfo
|
|
|
# обработчики кодов для вывода в 256
|
|
|
foreground256 = self.Color256Element(begin=cci.FOREGROUND256,
|
|
|
action=self.output.setForeground)
|
|
|
background256 = self.Color256Element(begin=cci.BACKGROUND256,
|
|
|
action=self.output.setBackground)
|
|
|
self.grams.insert(0,foreground256)
|
|
|
self.grams.insert(0,background256)
|