grc: Fix formatting

Signed-off-by: Bailey Campbell <baileycampbell1990@gmail.com>
This commit is contained in:
Bailey Campbell 2023-10-03 19:57:47 -04:00 committed by Jeff Long
parent 1385878aa3
commit 4e84c0bf8d
3 changed files with 148 additions and 190 deletions

View File

@ -25,29 +25,22 @@ def have_dark_theme():
"""
Check if a theme is dark based on its name.
"""
return theme_name and (
theme_name in Constants.GTK_DARK_THEMES or "dark" in theme_name.lower()
)
return theme_name and (theme_name in Constants.GTK_DARK_THEMES or "dark" in theme_name.lower())
# GoGoGo
config = configparser.ConfigParser()
config.read(os.path.expanduser(Constants.GTK_SETTINGS_INI_PATH))
prefer_dark = config.get(
"Settings", Constants.GTK_INI_PREFER_DARK_KEY, fallback=None
)
theme_name = config.get("Settings", Constants.GTK_INI_THEME_NAME_KEY, fallback=None)
if prefer_dark in ("1", "yes", "true", "on") or is_dark_theme(theme_name):
'Settings', Constants.GTK_INI_PREFER_DARK_KEY, fallback=None)
theme_name = config.get(
'Settings', Constants.GTK_INI_THEME_NAME_KEY, fallback=None)
if prefer_dark in ('1', 'yes', 'true', 'on') or is_dark_theme(theme_name):
return True
try:
theme = (
subprocess.check_output(
["gsettings", "get", "org.gnome.desktop.interface", "gtk-theme"],
stderr=subprocess.DEVNULL,
)
.decode("utf-8")
.strip()
.replace("'", "")
)
theme = subprocess.check_output(
["gsettings", "get", "org.gnome.desktop.interface", "gtk-theme"],
stderr=subprocess.DEVNULL
).decode('utf-8').strip().replace("'", "")
except:
return False
return is_dark_theme(theme)
@ -60,12 +53,11 @@ def add_style_provider():
style_provider = Gtk.CssProvider()
dark_theme = have_dark_theme()
style_provider.load_from_data(
DARK_THEME_STYLES if dark_theme else LIGHT_THEME_STYLES
)
DARK_THEME_STYLES if dark_theme else LIGHT_THEME_STYLES)
Gtk.StyleContext.add_provider_for_screen(
Gdk.Screen.get_default(),
style_provider,
Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION,
Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
)
@ -77,9 +69,7 @@ class InputParam(Gtk.HBox):
expand = False
def __init__(
self, param, changed_callback=None, editing_callback=None, transient_for=None
):
def __init__(self, param, changed_callback=None, editing_callback=None, transient_for=None):
Gtk.HBox.__init__(self)
self.param = param
@ -103,7 +93,7 @@ class InputParam(Gtk.HBox):
self.tp = None
self._have_pending_changes = False
self.connect("show", self._update_gui)
self.connect('show', self._update_gui)
def set_tooltip_text(self, text):
pass
@ -116,14 +106,13 @@ class InputParam(Gtk.HBox):
Set the markup, color, tooltip, show/hide.
"""
self.label.set_markup(
self.param.format_label_markup(self._have_pending_changes)
)
self.param.format_label_markup(self._have_pending_changes))
if self.dtype_label is not None:
self.dtype_label.set_markup(self.param.format_dtype_markup())
self.set_tooltip_text(self.param.format_tooltip_text())
if self.param.hide == "all":
if self.param.hide == 'all':
self.hide()
else:
self.show_all()
@ -154,10 +143,7 @@ class InputParam(Gtk.HBox):
self._update_gui()
def _handle_key_press(self, widget, event):
if (
event.keyval == Gdk.KEY_Return
and event.get_state() & Gdk.ModifierType.CONTROL_MASK
):
if event.keyval == Gdk.KEY_Return and event.get_state() & Gdk.ModifierType.CONTROL_MASK:
self._apply_change(widget, event)
return True
return False
@ -174,9 +160,9 @@ class EntryParam(InputParam):
InputParam.__init__(self, *args, **kwargs)
self._input = Gtk.Entry()
self._input.set_text(self.param.get_value())
self._input.connect("changed", self._mark_changed)
self._input.connect("focus-out-event", self._apply_change)
self._input.connect("key-press-event", self._handle_key_press)
self._input.connect('changed', self._mark_changed)
self._input.connect('focus-out-event', self._apply_change)
self._input.connect('key-press-event', self._handle_key_press)
self.pack_start(self._input, True, True, 0)
def get_text(self):
@ -195,12 +181,12 @@ class MultiLineEntryParam(InputParam):
InputParam.__init__(self, *args, **kwargs)
self._buffer = Gtk.TextBuffer()
self._buffer.set_text(self.param.get_value())
self._buffer.connect("changed", self._mark_changed)
self._buffer.connect('changed', self._mark_changed)
self._view = Gtk.TextView()
self._view.set_buffer(self._buffer)
self._view.connect("focus-out-event", self._apply_change)
self._view.connect("key-press-event", self._handle_key_press)
self._view.connect('focus-out-event', self._apply_change)
self._view.connect('key-press-event', self._handle_key_press)
self._sw = Gtk.ScrolledWindow()
self._sw.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
@ -211,9 +197,8 @@ class MultiLineEntryParam(InputParam):
def get_text(self):
buf = self._buffer
text = buf.get_text(
buf.get_start_iter(), buf.get_end_iter(), include_hidden_chars=False
)
text = buf.get_text(buf.get_start_iter(), buf.get_end_iter(),
include_hidden_chars=False)
return text.strip()
def set_tooltip_text(self, text):
@ -223,17 +208,16 @@ class MultiLineEntryParam(InputParam):
class PythonEditorParam(InputParam):
def __init__(self, *args, **kwargs):
InputParam.__init__(self, *args, **kwargs)
open_button = self._open_button = Gtk.Button(label="Open in Editor")
open_button.connect("clicked", self.open_editor)
open_button = self._open_button = Gtk.Button(label='Open in Editor')
open_button.connect('clicked', self.open_editor)
self.pack_start(open_button, True, True, True)
chooser_button = self._chooser_button = Gtk.Button(label="Choose Editor")
chooser_button.connect("clicked", self.open_chooser)
chooser_button = self._chooser_button = Gtk.Button(label='Choose Editor')
chooser_button.connect('clicked', self.open_chooser)
self.pack_start(chooser_button, True, True, True)
def open_editor(self, widget=None):
self.param.parent_flowgraph.install_external_editor(
self.param, parent=self._transient_for
)
self.param, parent=self._transient_for)
def open_chooser(self, widget=None):
self.param.parent_flowgraph.remove_external_editor(param=self.param)
@ -260,8 +244,8 @@ class EnumParam(InputParam):
self.param_values = list(self.param.options)
self._input.set_active(self.param_values.index(self.param.get_value()))
self._input.connect("changed", self._editing_callback)
self._input.connect("changed", self._apply_change)
self._input.connect('changed', self._editing_callback)
self._input.connect('changed', self._apply_change)
self.pack_start(self._input, False, False, 0)
def get_text(self):
@ -288,10 +272,10 @@ class EnumEntryParam(InputParam):
self._input.set_active(-1)
self._input.get_child().set_text(value)
self._input.connect("changed", self._apply_change)
self._input.get_child().connect("changed", self._mark_changed)
self._input.get_child().connect("focus-out-event", self._apply_change)
self._input.get_child().connect("key-press-event", self._handle_key_press)
self._input.connect('changed', self._apply_change)
self._input.get_child().connect('changed', self._mark_changed)
self._input.get_child().connect('focus-out-event', self._apply_change)
self._input.get_child().connect('key-press-event', self._handle_key_press)
self.pack_start(self._input, False, False, 0)
@property
@ -316,8 +300,8 @@ class FileParam(EntryParam):
def __init__(self, *args, **kwargs):
EntryParam.__init__(self, *args, **kwargs)
self._open_button = Gtk.Button(label="...")
self._open_button.connect("clicked", self._handle_clicked)
self._open_button = Gtk.Button(label='...')
self._open_button.connect('clicked', self._handle_clicked)
self.pack_start(self._open_button, False, False, 0)
def _handle_clicked(self, widget=None):
@ -326,44 +310,39 @@ class FileParam(EntryParam):
Replace the text in the entry with the new filename from the file dialog.
"""
# get the paths
file_path = self.param.is_valid() and self.param.get_evaluated() or ""
(dirname, basename) = (
os.path.isfile(file_path) and os.path.split(file_path) or (file_path, "")
)
file_path = self.param.is_valid() and self.param.get_evaluated() or ''
(dirname, basename) = os.path.isfile(
file_path) and os.path.split(file_path) or (file_path, '')
# check for qss theme default directory
if self.param.key == "qt_qss_theme":
if self.param.key == 'qt_qss_theme':
dirname = os.path.dirname(dirname) # trim filename
if not os.path.exists(dirname):
config = self.param.parent_platform.config
dirname = os.path.join(config.install_prefix, "/share/gnuradio/themes")
dirname = os.path.join(
config.install_prefix, '/share/gnuradio/themes')
if not os.path.exists(dirname):
dirname = os.getcwd() # fix bad paths
# build the dialog
if self.param.dtype == "file_open":
if self.param.dtype == 'file_open':
file_dialog = Gtk.FileChooserDialog(
title="Open a Data File...",
action=Gtk.FileChooserAction.OPEN,
title='Open a Data File...', action=Gtk.FileChooserAction.OPEN,
transient_for=self._transient_for,
)
file_dialog.add_buttons(
"gtk-cancel", Gtk.ResponseType.CANCEL, "gtk-open", Gtk.ResponseType.OK
)
elif self.param.dtype == "file_save":
'gtk-cancel', Gtk.ResponseType.CANCEL, 'gtk-open', Gtk.ResponseType.OK)
elif self.param.dtype == 'file_save':
file_dialog = Gtk.FileChooserDialog(
title="Save a Data File...",
action=Gtk.FileChooserAction.SAVE,
title='Save a Data File...', action=Gtk.FileChooserAction.SAVE,
transient_for=self._transient_for,
)
file_dialog.add_buttons(
"gtk-cancel", Gtk.ResponseType.CANCEL, "gtk-save", Gtk.ResponseType.OK
)
'gtk-cancel', Gtk.ResponseType.CANCEL, 'gtk-save', Gtk.ResponseType.OK)
file_dialog.set_do_overwrite_confirmation(True)
file_dialog.set_current_name(basename) # show the current filename
else:
raise ValueError(
"Can't open file chooser dialog for type " + repr(self.param.dtype)
)
"Can't open file chooser dialog for type " + repr(self.param.dtype))
file_dialog.set_current_folder(dirname) # current directory
file_dialog.set_select_multiple(False)
file_dialog.set_local_only(True)
@ -383,29 +362,24 @@ class DirectoryParam(FileParam):
Open the directory selector, when the button is clicked.
On success, update the entry.
"""
dirname = self.param.get_evaluated() if self.param.is_valid() else ""
dirname = self.param.get_evaluated() if self.param.is_valid() else ''
# Check if directory exists, if not fall back to workdir
if not os.path.isdir(dirname):
dirname = os.getcwd()
if (
self.param.dtype == "dir_select"
): # Setup directory selection dialog, and fail for unexpected dtype
if self.param.dtype == "dir_select": # Setup directory selection dialog, and fail for unexpected dtype
dir_dialog = Gtk.FileChooserDialog(
title="Select a Directory...",
action=Gtk.FileChooserAction.SELECT_FOLDER,
transient_for=self._transient_for,
title='Select a Directory...', action=Gtk.FileChooserAction.SELECT_FOLDER,
transient_for=self._transient_for
)
else:
raise ValueError(
"Can't open directory chooser dialog for type " + repr(self.param.dtype)
)
"Can't open directory chooser dialog for type " + repr(self.param.dtype))
# Set dialog properties
dir_dialog.add_buttons(
"gtk-cancel", Gtk.ResponseType.CANCEL, "gtk-open", Gtk.ResponseType.OK
)
'gtk-cancel', Gtk.ResponseType.CANCEL, 'gtk-open', Gtk.ResponseType.OK)
dir_dialog.set_current_folder(dirname)
dir_dialog.set_local_only(True)
dir_dialog.set_select_multiple(False)

View File

@ -27,23 +27,20 @@ class PropsDialog(Gtk.Dialog):
Gtk.Dialog.__init__(
self,
title="Properties: " + block.label,
title='Properties: ' + block.label,
transient_for=parent,
modal=True,
destroy_with_parent=True,
)
self.add_buttons(
Gtk.STOCK_OK,
Gtk.ResponseType.ACCEPT,
Gtk.STOCK_CANCEL,
Gtk.ResponseType.REJECT,
Gtk.STOCK_APPLY,
Gtk.ResponseType.APPLY,
Gtk.STOCK_OK, Gtk.ResponseType.ACCEPT,
Gtk.STOCK_CANCEL, Gtk.ResponseType.REJECT,
Gtk.STOCK_APPLY, Gtk.ResponseType.APPLY,
)
self.set_response_sensitive(Gtk.ResponseType.APPLY, False)
self.set_size_request(
*Utils.scale((Constants.MIN_DIALOG_WIDTH, Constants.MIN_DIALOG_HEIGHT))
)
self.set_size_request(*Utils.scale(
(Constants.MIN_DIALOG_WIDTH, Constants.MIN_DIALOG_HEIGHT)
))
self._block = block
self._hash = 0
@ -65,9 +62,10 @@ class PropsDialog(Gtk.Dialog):
# Docs for the block
self._docs_text_display = doc_view = SimpleTextDisplay()
doc_view.get_buffer().create_tag("b", weight=Pango.Weight.BOLD)
doc_view.get_buffer().create_tag('b', weight=Pango.Weight.BOLD)
self._docs_box = Gtk.ScrolledWindow()
self._docs_box.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
self._docs_box.set_policy(
Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
self._docs_vbox = Gtk.VBox(homogeneous=False, spacing=0)
self._docs_box.add(self._docs_vbox)
self._docs_link = Gtk.Label(use_markup=True)
@ -79,12 +77,13 @@ class PropsDialog(Gtk.Dialog):
if Actions.TOGGLE_SHOW_CODE_PREVIEW_TAB.get_active():
self._code_text_display = code_view = SimpleTextDisplay()
code_view.set_wrap_mode(Gtk.WrapMode.NONE)
code_view.get_buffer().create_tag("b", weight=Pango.Weight.BOLD)
code_view.get_buffer().create_tag('b', weight=Pango.Weight.BOLD)
code_view.set_monospace(True)
# todo: set font size in non-deprecated way
# code_view.override_font(Pango.FontDescription('monospace %d' % Constants.FONT_SIZE))
code_box = Gtk.ScrolledWindow()
code_box.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
code_box.set_policy(Gtk.PolicyType.AUTOMATIC,
Gtk.PolicyType.AUTOMATIC)
code_box.add(self._code_text_display)
notebook.append_page(code_box, Gtk.Label(label="Generated Code"))
else:
@ -93,15 +92,16 @@ class PropsDialog(Gtk.Dialog):
# Error Messages for the block
self._error_messages_text_display = SimpleTextDisplay()
self._error_box = Gtk.ScrolledWindow()
self._error_box.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
self._error_box.set_policy(
Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
self._error_box.add(self._error_messages_text_display)
vpaned.pack2(self._error_box)
vpaned.set_position(int(0.65 * Constants.MIN_DIALOG_HEIGHT))
# Connect events
self.connect("key-press-event", self._handle_key_press)
self.connect("show", self.update_gui)
self.connect("response", self._handle_response)
self.connect('key-press-event', self._handle_key_press)
self.connect('show', self.update_gui)
self.connect('response', self._handle_response)
self.show_all() # show all (performs initial gui update)
def _build_param_tab_boxes(self):
@ -120,7 +120,8 @@ class PropsDialog(Gtk.Dialog):
label = Gtk.Label()
vbox = Gtk.VBox()
scroll_box = Gtk.ScrolledWindow()
scroll_box.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
scroll_box.set_policy(Gtk.PolicyType.AUTOMATIC,
Gtk.PolicyType.AUTOMATIC)
scroll_box.add(vbox)
self.notebook.append_page(scroll_box, label)
self._params_boxes.append((category, label, vbox))
@ -137,17 +138,10 @@ class PropsDialog(Gtk.Dialog):
true if changed
"""
old_hash = self._hash
new_hash = self._hash = hash(
tuple(
(
hash(param),
param.name,
param.dtype,
param.hide == "all",
)
for param in self._block.params.values()
)
)
new_hash = self._hash = hash(tuple(
(hash(param), param.name, param.dtype, param.hide == 'all',)
for param in self._block.params.values()
))
return new_hash != old_hash
def _handle_changed(self, *args):
@ -184,34 +178,28 @@ class PropsDialog(Gtk.Dialog):
force_show_id = Actions.TOGGLE_SHOW_BLOCK_IDS.get_active()
for param in self._block.params.values():
if force_show_id and param.dtype == "id":
param.hide = "none"
if force_show_id and param.dtype == 'id':
param.hide = 'none'
# todo: why do we even rebuild instead of really hiding params?
if param.category != category or param.hide == "all":
if param.category != category or param.hide == 'all':
continue
box_all_valid = box_all_valid and param.is_valid()
input_widget = param.get_input(
self._handle_changed,
self._activate_apply,
transient_for=self.get_transient_for(),
)
input_widget = param.get_input(self._handle_changed, self._activate_apply,
transient_for=self.get_transient_for())
input_widget.show_all()
vbox.pack_start(input_widget, input_widget.expand, True, 1)
label.set_markup(
"<span {color}>{name}</span>".format(
color='foreground="red"' if not box_all_valid else "",
name=Utils.encode(category),
)
)
label.set_markup('<span {color}>{name}</span>'.format(
color='foreground="red"' if not box_all_valid else '', name=Utils.encode(category)
))
vbox.show() # show params box with new params
if self._block.is_valid():
self._error_box.hide()
else:
self._error_box.show()
messages = "\n\n".join(self._block.get_error_messages())
messages = '\n\n'.join(self._block.get_error_messages())
self._error_messages_text_display.set_text(messages)
self._update_docs_page()
@ -231,32 +219,33 @@ class PropsDialog(Gtk.Dialog):
href = f'<a href="{prefix+suffix}">Visit Wiki Page</a>'
self._docs_link.set_markup(href)
else:
self._docs_link.set_markup("Out of Tree Block")
self._docs_link.set_markup('Out of Tree Block')
docstrings = self._block.documentation.copy()
if not docstrings:
return
# show documentation string from block yaml
from_yaml = docstrings.pop("", "")
from_yaml = docstrings.pop('', '')
for line in from_yaml.splitlines():
if line.lstrip() == line and line.endswith(":"):
buf.insert_with_tags_by_name(pos, line + "\n", "b")
if line.lstrip() == line and line.endswith(':'):
buf.insert_with_tags_by_name(pos, line + '\n', 'b')
else:
buf.insert(pos, line + "\n")
buf.insert(pos, line + '\n')
if from_yaml:
buf.insert(pos, "\n")
buf.insert(pos, '\n')
# if given the current parameters an exact match can be made
block_constructor = self._block.templates.render("make").rsplit(".", 2)[-1]
block_class = block_constructor.partition("(")[0].strip()
block_constructor = self._block.templates.render(
'make').rsplit('.', 2)[-1]
block_class = block_constructor.partition('(')[0].strip()
if block_class in docstrings:
docstrings = {block_class: docstrings[block_class]}
# show docstring(s) extracted from python sources
for cls_name, docstring in docstrings.items():
buf.insert_with_tags_by_name(pos, cls_name + "\n", "b")
buf.insert(pos, docstring + "\n\n")
buf.insert_with_tags_by_name(pos, cls_name + '\n', 'b')
buf.insert(pos, docstring + '\n\n')
pos.backward_chars(2)
buf.delete(pos, buf.get_end_iter())
@ -268,32 +257,32 @@ class PropsDialog(Gtk.Dialog):
block = self._block
key = block.key
if key == "epy_block":
src = block.params["_source_code"].get_value()
elif key == "epy_module":
src = block.params["source_code"].get_value()
if key == 'epy_block':
src = block.params['_source_code'].get_value()
elif key == 'epy_module':
src = block.params['source_code'].get_value()
else:
src = ""
src = ''
def insert(header, text):
if not text:
return
buf.insert_with_tags_by_name(buf.get_end_iter(), header, "b")
buf.insert_with_tags_by_name(buf.get_end_iter(), header, 'b')
buf.insert(buf.get_end_iter(), text)
buf.delete(buf.get_start_iter(), buf.get_end_iter())
insert("# Imports\n", block.templates.render("imports").strip("\n"))
insert('# Imports\n', block.templates.render('imports').strip('\n'))
if block.is_variable:
insert("\n\n# Variables\n", block.templates.render("var_make"))
insert("\n\n# Blocks\n", block.templates.render("make"))
insert('\n\n# Variables\n', block.templates.render('var_make'))
insert('\n\n# Blocks\n', block.templates.render('make'))
if src:
insert("\n\n# External Code ({}.py)\n".format(block.name), src)
insert('\n\n# External Code ({}.py)\n'.format(block.name), src)
def _handle_key_press(self, widget, event):
close_dialog = (
event.keyval == Gdk.KEY_Return
and event.get_state() & Gdk.ModifierType.CONTROL_MASK == 0
and not isinstance(widget.get_focus(), Gtk.TextView)
event.keyval == Gdk.KEY_Return and
event.get_state() & Gdk.ModifierType.CONTROL_MASK == 0 and
not isinstance(widget.get_focus(), Gtk.TextView)
)
if close_dialog:
self.response(Gtk.ResponseType.ACCEPT)

View File

@ -28,22 +28,22 @@ class Param(CoreParam):
gtk input class
"""
dtype = self.dtype
if dtype in ("file_open", "file_save"):
if dtype in ('file_open', 'file_save'):
input_widget_cls = ParamWidgets.FileParam
elif dtype == "dir_select":
elif dtype == 'dir_select':
input_widget_cls = ParamWidgets.DirectoryParam
elif dtype == "enum":
elif dtype == 'enum':
input_widget_cls = ParamWidgets.EnumParam
elif self.options:
input_widget_cls = ParamWidgets.EnumEntryParam
elif dtype == "_multiline":
elif dtype == '_multiline':
input_widget_cls = ParamWidgets.MultiLineEntryParam
elif dtype == "_multiline_python_external":
elif dtype == '_multiline_python_external':
input_widget_cls = ParamWidgets.PythonEditorParam
else:
@ -54,20 +54,15 @@ class Param(CoreParam):
def format_label_markup(self, have_pending_changes=False):
block = self.parent
# fixme: using non-public attribute here
has_callback = hasattr(block, "templates") and any(
self.key in callback for callback in block.templates.get("callbacks", "")
)
has_callback = \
hasattr(block, 'templates') and \
any(self.key in callback for callback in block.templates.get('callbacks', ''))
return (
'<span {underline} {foreground} font_desc="Sans 9">{label}</span>'.format(
underline='underline="low"' if has_callback else "",
foreground='foreground="blue"'
if have_pending_changes
else 'foreground="red"'
if not self.is_valid()
else "",
label=Utils.encode(self.name),
)
return '<span {underline} {foreground} font_desc="Sans 9">{label}</span>'.format(
underline='underline="low"' if has_callback else '',
foreground='foreground="blue"' if have_pending_changes else
'foreground="red"' if not self.is_valid() else '',
label=Utils.encode(self.name)
)
def format_dtype_markup(self):
@ -75,24 +70,24 @@ class Param(CoreParam):
def format_tooltip_text(self):
errors = self.get_error_messages()
tooltip_lines = ["Key: " + self.key, "Type: " + self.dtype]
tooltip_lines = ['Key: ' + self.key, 'Type: ' + self.dtype]
if self.is_valid():
value = self.get_evaluated()
if hasattr(value, "__len__"):
tooltip_lines.append("Length: {}".format(len(value)))
tooltip_lines.append('Length: {}'.format(len(value)))
value = str(value)
# ensure that value is a UTF-8 string
# Old PMTs could produce non-UTF-8 strings
value = value.encode("utf-8", "backslashreplace").decode("utf-8")
value = value.encode('utf-8', 'backslashreplace').decode('utf-8')
if len(value) > 100:
value = "{}...{}".format(value[:50], value[-50:])
tooltip_lines.append("Value: " + value)
value = '{}...{}'.format(value[:50], value[-50:])
tooltip_lines.append('Value: ' + value)
elif len(errors) == 1:
tooltip_lines.append("Error: " + errors[0])
tooltip_lines.append('Error: ' + errors[0])
elif len(errors) > 1:
tooltip_lines.append("Error:")
tooltip_lines.extend(" * " + msg for msg in errors)
return "\n".join(tooltip_lines)
tooltip_lines.append('Error:')
tooltip_lines.extend(' * ' + msg for msg in errors)
return '\n'.join(tooltip_lines)
##################################################
# Truncate helper method
@ -102,11 +97,12 @@ class Param(CoreParam):
max_len = max(27 - len(self.name), 3)
if len(string) > max_len:
if style < 0: # Front truncate
string = "..." + string[3 - max_len :]
string = '...' + string[3 - max_len:]
elif style == 0: # Center truncate
string = string[: max_len // 2 - 3] + "..." + string[-max_len // 2 :]
string = string[:max_len // 2 - 3] + \
'...' + string[-max_len // 2:]
elif style > 0: # Rear truncate
string = string[: max_len - 3] + "..."
string = string[:max_len - 3] + '...'
return string
def pretty_print(self):
@ -145,8 +141,8 @@ class Param(CoreParam):
truncate = 1
else:
# Small vectors use eval
dt_str = ", ".join(map(Utils.num_to_str, e))
elif t in ("file_open", "file_save"):
dt_str = ', '.join(map(Utils.num_to_str, e))
elif t in ('file_open', 'file_save'):
dt_str = self.get_value()
truncate = -1
else:
@ -154,7 +150,7 @@ class Param(CoreParam):
dt_str = str(e)
# ensure that value is a UTF-8 string
# Old PMTs could produce non-UTF-8 strings
dt_str = dt_str.encode("utf-8", "backslashreplace").decode("utf-8")
dt_str = dt_str.encode('utf-8', 'backslashreplace').decode('utf-8')
# Done
return self.truncate(dt_str, truncate)
@ -176,11 +172,13 @@ class Param(CoreParam):
# Include the value defined by the user (after evaluation)
if not is_evaluated or show_value or not show_expr:
display_value += Utils.encode(self.pretty_print().replace("\n", " "))
display_value += Utils.encode(
self.pretty_print().replace('\n', ' '))
# Include the expression that was evaluated to get the value
if is_evaluated and show_expr:
expr_string = "<i>" + Utils.encode(self.truncate(self.value)) + "</i>"
expr_string = "<i>" + \
Utils.encode(self.truncate(self.value)) + "</i>"
if display_value: # We are already displaying the value
display_value = expr_string + "=" + display_value
@ -188,8 +186,5 @@ class Param(CoreParam):
display_value = expr_string
return '<span {foreground} font_desc="{font}"><b>{label}:</b> {value}</span>'.format(
foreground='foreground="red"' if not self.is_valid() else "",
font=Constants.PARAM_FONT,
label=Utils.encode(self.name),
value=display_value,
)
foreground='foreground="red"' if not self.is_valid() else '', font=Constants.PARAM_FONT,
label=Utils.encode(self.name), value=display_value)