INSTRUCTION
stringlengths 1
46.3k
| RESPONSE
stringlengths 75
80.2k
|
---|---|
Return kwargs dict for text | def get_kwargs(self):
"""Return kwargs dict for text"""
kwargs = {}
if self.font_face:
kwargs["fontname"] = repr(self.font_face)
if self.font_size:
kwargs["fontsize"] = repr(self.font_size)
if self.font_style in self.style_wx2mpl:
kwargs["fontstyle"] = repr(self.style_wx2mpl[self.font_style])
if self.font_weight in self.weight_wx2mpl:
kwargs["fontweight"] = repr(self.weight_wx2mpl[self.font_weight])
kwargs["color"] = color2code(self.colorselect.GetValue())
code = ", ".join(repr(key) + ": " + kwargs[key] for key in kwargs)
code = "{" + code + "}"
return code |
Sets widget from kwargs string
Parameters
----------
code: String
\tCode representation of kwargs value | def set_kwargs(self, code):
"""Sets widget from kwargs string
Parameters
----------
code: String
\tCode representation of kwargs value
"""
kwargs = {}
kwarglist = list(parse_dict_strings(code[1:-1]))
for kwarg, val in zip(kwarglist[::2], kwarglist[1::2]):
kwargs[unquote_string(kwarg)] = val
for key in kwargs:
if key == "color":
color = code2color(kwargs[key])
self.colorselect.SetOwnForegroundColour(color)
elif key == "fontname":
self.font_face = unquote_string(kwargs[key])
if self.chosen_font is None:
self.chosen_font = get_default_font()
self.chosen_font.SetFaceName(self.font_face)
elif key == "fontsize":
if kwargs[key]:
self.font_size = int(kwargs[key])
else:
self.font_size = get_default_font().GetPointSize()
if self.chosen_font is None:
self.chosen_font = get_default_font()
self.chosen_font.SetPointSize(self.font_size)
elif key == "fontstyle":
self.font_style = \
self.style_mpl2wx[unquote_string(kwargs[key])]
if self.chosen_font is None:
self.chosen_font = get_default_font()
self.chosen_font.SetStyle(self.font_style)
elif key == "fontweight":
self.font_weight = \
self.weight_mpl2wx[unquote_string(kwargs[key])]
if self.chosen_font is None:
self.chosen_font = get_default_font()
self.chosen_font.SetWeight(self.font_weight) |
Check event handler | def OnFont(self, event):
"""Check event handler"""
font_data = wx.FontData()
# Disable color chooser on Windows
font_data.EnableEffects(False)
if self.chosen_font:
font_data.SetInitialFont(self.chosen_font)
dlg = wx.FontDialog(self, font_data)
if dlg.ShowModal() == wx.ID_OK:
font_data = dlg.GetFontData()
font = self.chosen_font = font_data.GetChosenFont()
self.font_face = font.GetFaceName()
self.font_size = font.GetPointSize()
self.font_style = font.GetStyle()
self.font_weight = font.GetWeight()
dlg.Destroy()
post_command_event(self, self.DrawChartMsg) |
Binds events to handlers | def __bindings(self):
"""Binds events to handlers"""
self.direction_choicectrl.Bind(wx.EVT_CHOICE, self.OnDirectionChoice)
self.sec_checkboxctrl.Bind(wx.EVT_CHECKBOX, self.OnSecondaryCheckbox)
self.pad_intctrl.Bind(EVT_INT, self.OnPadIntCtrl)
self.labelsize_intctrl.Bind(EVT_INT, self.OnLabelSizeIntCtrl) |
Return kwargs dict for text | def get_kwargs(self):
"""Return kwargs dict for text"""
kwargs = {}
for attr in self.attrs:
val = self.attrs[attr]
if val is not None:
kwargs[attr] = repr(val)
code = ", ".join(repr(key) + ": " + kwargs[key] for key in kwargs)
code = "{" + code + "}"
return code |
Direction choice event handler | def OnDirectionChoice(self, event):
"""Direction choice event handler"""
label = self.direction_choicectrl.GetItems()[event.GetSelection()]
param = self.choice_label2param[label]
self.attrs["direction"] = param
post_command_event(self, self.DrawChartMsg) |
Top Checkbox event handler | def OnSecondaryCheckbox(self, event):
"""Top Checkbox event handler"""
self.attrs["top"] = event.IsChecked()
self.attrs["right"] = event.IsChecked()
post_command_event(self, self.DrawChartMsg) |
Pad IntCtrl event handler | def OnPadIntCtrl(self, event):
"""Pad IntCtrl event handler"""
self.attrs["pad"] = event.GetValue()
post_command_event(self, self.DrawChartMsg) |
Label size IntCtrl event handler | def OnLabelSizeIntCtrl(self, event):
"""Label size IntCtrl event handler"""
self.attrs["labelsize"] = event.GetValue()
post_command_event(self, self.DrawChartMsg) |
Returns code representation of value of widget | def get_code(self):
"""Returns code representation of value of widget"""
selection = self.GetSelection()
if selection == wx.NOT_FOUND:
selection = 0
# Return code string
return self.styles[selection][1] |
Sets widget from code string
Parameters
----------
code: String
\tCode representation of widget value | def set_code(self, code):
"""Sets widget from code string
Parameters
----------
code: String
\tCode representation of widget value
"""
for i, (_, style_code) in enumerate(self.styles):
if code == style_code:
self.SetSelection(i) |
Updates self.data from series data
Parameters
----------
* series_data: dict
\tKey value pairs for self.data, which correspond to chart attributes | def update(self, series_data):
"""Updates self.data from series data
Parameters
----------
* series_data: dict
\tKey value pairs for self.data, which correspond to chart attributes
"""
for key in series_data:
try:
data_list = list(self.data[key])
data_list[2] = str(series_data[key])
self.data[key] = tuple(data_list)
except KeyError:
pass |
Returns current plot_panel | def get_plot_panel(self):
"""Returns current plot_panel"""
plot_type_no = self.chart_type_book.GetSelection()
return self.chart_type_book.GetPage(plot_type_no) |
Sets plot type | def set_plot_type(self, plot_type):
"""Sets plot type"""
ptypes = [pt["type"] for pt in self.plot_types]
self.plot_panel = ptypes.index(plot_type) |
Binds events to handlers | def __bindings(self):
"""Binds events to handlers"""
self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnSeriesChanged)
self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CLOSING, self.OnSeriesDeleted) |
Updates widget content from series_list
Parameters
----------
series_list: List of dict
\tList of dicts with data from all series | def update(self, series_list):
"""Updates widget content from series_list
Parameters
----------
series_list: List of dict
\tList of dicts with data from all series
"""
if not series_list:
self.series_notebook.AddPage(wx.Panel(self, -1), _("+"))
return
self.updating = True
# Delete all tabs in the notebook
self.series_notebook.DeleteAllPages()
# Add as many tabs as there are series in code
for page, attrdict in enumerate(series_list):
series_panel = SeriesPanel(self.grid, attrdict)
name = "Series"
self.series_notebook.InsertPage(page, series_panel, name)
self.series_notebook.AddPage(wx.Panel(self, -1), _("+"))
self.updating = False |
FlatNotebook change event handler | def OnSeriesChanged(self, event):
"""FlatNotebook change event handler"""
selection = event.GetSelection()
if not self.updating and \
selection == self.series_notebook.GetPageCount() - 1:
# Add new series
new_panel = SeriesPanel(self, {"type": "plot"})
self.series_notebook.InsertPage(selection, new_panel, _("Series"))
event.Skip() |
Updates figure on data change
Parameters
----------
* figure: matplotlib.figure.Figure
\tMatplotlib figure object that is displayed in self | def update(self, figure):
"""Updates figure on data change
Parameters
----------
* figure: matplotlib.figure.Figure
\tMatplotlib figure object that is displayed in self
"""
if hasattr(self, "figure_canvas"):
self.figure_canvas.Destroy()
self.figure_canvas = self._get_figure_canvas(figure)
self.figure_canvas.SetSize(self.GetSize())
figure.subplots_adjust()
self.main_sizer.Add(self.figure_canvas, 1,
wx.EXPAND | wx.FIXED_MINSIZE, 0)
self.Layout()
self.figure_canvas.draw() |
Returns figure from executing code in grid
Returns an empty matplotlib figure if code does not eval to a
matplotlib figure instance.
Parameters
----------
code: Unicode
\tUnicode string which contains Python code that should yield a figure | def get_figure(self, code):
"""Returns figure from executing code in grid
Returns an empty matplotlib figure if code does not eval to a
matplotlib figure instance.
Parameters
----------
code: Unicode
\tUnicode string which contains Python code that should yield a figure
"""
# Caching for fast response if there are no changes
if code == self.figure_code_old and self.figure_cache:
return self.figure_cache
self.figure_code_old = code
# key is the current cursor cell of the grid
key = self.grid.actions.cursor
cell_result = self.grid.code_array._eval_cell(key, code)
# If cell_result is matplotlib figure
if isinstance(cell_result, matplotlib.pyplot.Figure):
# Return it
self.figure_cache = cell_result
return cell_result
else:
# Otherwise return empty figure
self.figure_cache = charts.ChartFigure()
return self.figure_cache |
Update widgets from code | def set_code(self, code):
"""Update widgets from code"""
# Get attributes from code
attributes = []
strip = lambda s: s.strip('u').strip("'").strip('"')
for attr_dict in parse_dict_strings(unicode(code).strip()[19:-1]):
attrs = list(strip(s) for s in parse_dict_strings(attr_dict[1:-1]))
attributes.append(dict(zip(attrs[::2], attrs[1::2])))
if not attributes:
return
# Set widgets from attributes
# ---------------------------
# Figure attributes
figure_attributes = attributes[0]
for key, widget in self.figure_attributes_panel:
try:
obj = figure_attributes[key]
kwargs_key = key + "_kwargs"
if kwargs_key in figure_attributes:
widget.set_kwargs(figure_attributes[kwargs_key])
except KeyError:
obj = ""
widget.code = charts.object2code(key, obj)
# Series attributes
self.all_series_panel.update(attributes[1:]) |
Returns code that generates figure from widgets | def get_code(self):
"""Returns code that generates figure from widgets"""
def dict2str(attr_dict):
"""Returns string with dict content with values as code
Code means that string identifiers are removed
"""
result = u"{"
for key in attr_dict:
code = attr_dict[key]
if key in self.string_keys:
code = repr(code)
elif code and key in self.tuple_keys and \
not (code[0] in ["[", "("] and code[-1] in ["]", ")"]):
code = "(" + code + ")"
elif key in ["xscale", "yscale"]:
if code:
code = '"log"'
else:
code = '"linear"'
elif key in ["legend"]:
if code:
code = '1'
else:
code = '0'
elif key in ["xtick_params"]:
code = '"x"'
elif key in ["ytick_params"]:
code = '"y"'
if not code:
if key in self.empty_none_keys:
code = "None"
else:
code = 'u""'
result += repr(key) + ": " + code + ", "
result = result[:-2] + u"}"
return result
# cls_name inludes full class name incl. charts
cls_name = "charts." + charts.ChartFigure.__name__
attr_dicts = []
# Figure attributes
attr_dict = {}
# figure_attributes is a dict key2code
for key, widget in self.figure_attributes_panel:
if key == "type":
attr_dict[key] = widget
else:
attr_dict[key] = widget.code
try:
attr_dict[key+"_kwargs"] = widget.get_kwargs()
except AttributeError:
pass
attr_dicts.append(attr_dict)
# Series_attributes is a list of dicts key2code
for series_panel in self.all_series_panel:
attr_dict = {}
for key, widget in series_panel:
if key == "type":
attr_dict[key] = widget
else:
attr_dict[key] = widget.code
attr_dicts.append(attr_dict)
code = cls_name + "("
for attr_dict in attr_dicts:
code += dict2str(attr_dict) + ", "
code = code[:-2] + ")"
return code |
Redraw event handler for the figure panel | def OnUpdateFigurePanel(self, event):
"""Redraw event handler for the figure panel"""
if self.updating:
return
self.updating = True
self.figure_panel.update(self.get_figure(self.code))
self.updating = False |
Returns tuple of selection parameters of self
(self.block_tl, self.block_br, self.rows, self.cols, self.cells) | def parameters(self):
"""Returns tuple of selection parameters of self
(self.block_tl, self.block_br, self.rows, self.cols, self.cells)
"""
return self.block_tl, self.block_br, self.rows, self.cols, self.cells |
Inserts number of rows/cols/tabs into selection at point on axis
Parameters
----------
point: Integer
\tAt this point the rows/cols are inserted or deleted
number: Integer
\tNumber of rows/cols to be inserted, negative number deletes
axis: Integer in 0, 1
\tDefines whether rows or cols are affected | def insert(self, point, number, axis):
"""Inserts number of rows/cols/tabs into selection at point on axis
Parameters
----------
point: Integer
\tAt this point the rows/cols are inserted or deleted
number: Integer
\tNumber of rows/cols to be inserted, negative number deletes
axis: Integer in 0, 1
\tDefines whether rows or cols are affected
"""
def build_tuple_list(source_list, point, number, axis):
"""Returns adjusted tuple list for single cells"""
target_list = []
for tl in source_list:
tl_list = list(tl)
if tl[axis] > point:
tl_list[axis] += number
target_list.append(tuple(tl_list))
return target_list
self.block_tl = build_tuple_list(self.block_tl, point, number, axis)
self.block_br = build_tuple_list(self.block_br, point, number, axis)
if axis == 0:
self.rows = \
[row + number if row > point else row for row in self.rows]
elif axis == 1:
self.cols = \
[col + number if col > point else col for col in self.cols]
else:
raise ValueError("Axis not in [0, 1]")
self.cells = build_tuple_list(self.cells, point, number, axis) |
Returns ((top, left), (bottom, right)) of bounding box
A bounding box is the smallest rectangle that contains all selections.
Non-specified boundaries are None. | def get_bbox(self):
"""Returns ((top, left), (bottom, right)) of bounding box
A bounding box is the smallest rectangle that contains all selections.
Non-specified boundaries are None.
"""
bb_top, bb_left, bb_bottom, bb_right = [None] * 4
# Block selections
for top_left, bottom_right in zip(self.block_tl, self.block_br):
top, left = top_left
bottom, right = bottom_right
if bb_top is None or bb_top > top:
bb_top = top
if bb_left is None or bb_left > left:
bb_left = left
if bb_bottom is None or bb_bottom < bottom:
bb_bottom = bottom
if bb_right is None or bb_right > right:
bb_right = right
# Row and column selections
for row in self.rows:
if bb_top is None or bb_top > row:
bb_top = row
if bb_bottom is None or bb_bottom < row:
bb_bottom = row
for col in self.cols:
if bb_left is None or bb_left > col:
bb_left = col
if bb_right is None or bb_right < col:
bb_right = col
# Cell selections
for cell in self.cells:
cell_row, cell_col = cell
if bb_top is None or bb_top > cell_row:
bb_top = cell_row
if bb_left is None or bb_left > cell_col:
bb_left = cell_col
if bb_bottom is None or bb_bottom < cell_row:
bb_bottom = cell_row
if bb_right is None or bb_right < cell_col:
bb_right = cell_col
if all(val is None for val in [bb_top, bb_left, bb_bottom, bb_right]):
return None
return ((bb_top, bb_left), (bb_bottom, bb_right)) |
Returns ((top, left), (bottom, right)) of bounding box
A bounding box is the smallest rectangle that contains all selections.
Non-specified boundaries are filled i from size.
Parameters
----------
shape: 3-Tuple of Integer
\tGrid shape | def get_grid_bbox(self, shape):
"""Returns ((top, left), (bottom, right)) of bounding box
A bounding box is the smallest rectangle that contains all selections.
Non-specified boundaries are filled i from size.
Parameters
----------
shape: 3-Tuple of Integer
\tGrid shape
"""
(bb_top, bb_left), (bb_bottom, bb_right) = self.get_bbox()
if bb_top is None:
bb_top = 0
if bb_left is None:
bb_left = 0
if bb_bottom is None:
bb_bottom = shape[0]
if bb_right is None:
bb_right = shape[1]
return ((bb_top, bb_left), (bb_bottom, bb_right)) |
Returns a string, with which the selection can be accessed
Parameters
----------
shape: 3-tuple of Integer
\tShape of grid, for which the generated keys are valid
table: Integer
\tThird component of all returned keys. Must be in dimensions | def get_access_string(self, shape, table):
"""Returns a string, with which the selection can be accessed
Parameters
----------
shape: 3-tuple of Integer
\tShape of grid, for which the generated keys are valid
table: Integer
\tThird component of all returned keys. Must be in dimensions
"""
rows, columns, tables = shape
# Negative dimensions cannot be
assert all(dim > 0 for dim in shape)
# Current table has to be in dimensions
assert 0 <= table < tables
string_list = []
# Block selections
templ = "[(r, c, {}) for r in xrange({}, {}) for c in xrange({}, {})]"
for (top, left), (bottom, right) in izip(self.block_tl, self.block_br):
string_list += [templ.format(table, top, bottom + 1,
left, right + 1)]
# Fully selected rows
template = "[({}, c, {}) for c in xrange({})]"
for row in self.rows:
string_list += [template.format(row, table, columns)]
# Fully selected columns
template = "[(r, {}, {}) for r in xrange({})]"
for column in self.cols:
string_list += [template.format(column, table, rows)]
# Single cells
for row, column in self.cells:
string_list += [repr([(row, column, table)])]
key_string = " + ".join(string_list)
if len(string_list) == 0:
return ""
elif len(self.cells) == 1 and len(string_list) == 1:
return "S[{}]".format(string_list[0][1:-1])
else:
template = "[S[key] for key in {} if S[key] is not None]"
return template.format(key_string) |
Returns a new selection that is shifted by rows and cols.
Negative values for rows and cols may result in a selection
that addresses negative cells.
Parameters
----------
rows: Integer
\tNumber of rows that the new selection is shifted down
cols: Integer
\tNumber of columns that the new selection is shifted right | def shifted(self, rows, cols):
"""Returns a new selection that is shifted by rows and cols.
Negative values for rows and cols may result in a selection
that addresses negative cells.
Parameters
----------
rows: Integer
\tNumber of rows that the new selection is shifted down
cols: Integer
\tNumber of columns that the new selection is shifted right
"""
shifted_block_tl = \
[(row + rows, col + cols) for row, col in self.block_tl]
shifted_block_br = \
[(row + rows, col + cols) for row, col in self.block_br]
shifted_rows = [row + rows for row in self.rows]
shifted_cols = [col + cols for col in self.cols]
shifted_cells = [(row + rows, col + cols) for row, col in self.cells]
return Selection(shifted_block_tl, shifted_block_br, shifted_rows,
shifted_cols, shifted_cells) |
Selects cells of grid with selection content | def grid_select(self, grid, clear_selection=True):
"""Selects cells of grid with selection content"""
if clear_selection:
grid.ClearSelection()
for (tl, br) in zip(self.block_tl, self.block_br):
grid.SelectBlock(tl[0], tl[1], br[0], br[1], addToSelected=True)
for row in self.rows:
grid.SelectRow(row, addToSelected=True)
for col in self.cols:
grid.SelectCol(col, addToSelected=True)
for cell in self.cells:
grid.SelectBlock(cell[0], cell[1], cell[0], cell[1],
addToSelected=True) |
Modify traceback to only include the user code's execution frame
Always call in this fashion:
e = sys.exc_info()
user_tb = get_user_codeframe(e[2]) or e[2]
so that you can get the original frame back if you need to
(this is necessary because copying traceback objects is tricky and
this is a good workaround) | def get_user_codeframe(tb):
"""Modify traceback to only include the user code's execution frame
Always call in this fashion:
e = sys.exc_info()
user_tb = get_user_codeframe(e[2]) or e[2]
so that you can get the original frame back if you need to
(this is necessary because copying traceback objects is tricky and
this is a good workaround)
"""
while tb is not None:
f = tb.tb_frame
co = f.f_code
filename = co.co_filename
if filename[0] == '<':
# This is a meta-descriptor
# (probably either "<unknown>" or "<string>")
# and is likely the user's code we're executing
return tb
else:
tb = tb.tb_next
# We could not find the user's frame.
return False |
Returns code for widget from dict object | def object2code(key, code):
"""Returns code for widget from dict object"""
if key in ["xscale", "yscale"]:
if code == "log":
code = True
else:
code = False
else:
code = unicode(code)
return code |
Returns wx.Bitmap from matplotlib chart
Parameters
----------
fig: Object
\tMatplotlib figure
width: Integer
\tImage width in pixels
height: Integer
\tImage height in pixels
dpi = Float
\tDC resolution | def fig2bmp(figure, width, height, dpi, zoom):
"""Returns wx.Bitmap from matplotlib chart
Parameters
----------
fig: Object
\tMatplotlib figure
width: Integer
\tImage width in pixels
height: Integer
\tImage height in pixels
dpi = Float
\tDC resolution
"""
dpi *= float(zoom)
figure.set_figwidth(width / dpi)
figure.set_figheight(height / dpi)
figure.subplots_adjust()
with warnings.catch_warnings():
warnings.simplefilter("ignore")
try:
# The padding is too small for small sizes. This fixes it.
figure.tight_layout(pad=1.0/zoom)
except ValueError:
pass
figure.set_canvas(FigureCanvas(figure))
png_stream = StringIO()
figure.savefig(png_stream, format='png', dpi=(dpi))
png_stream.seek(0)
img = wx.ImageFromStream(png_stream, type=wx.BITMAP_TYPE_PNG)
return wx.BitmapFromImage(img) |
Returns svg from matplotlib chart | def fig2x(figure, format):
"""Returns svg from matplotlib chart"""
# Save svg to file like object svg_io
io = StringIO()
figure.savefig(io, format=format)
# Rewind the file like object
io.seek(0)
data = io.getvalue()
io.close()
return data |
Sets up axes for drawing chart | def _setup_axes(self, axes_data):
"""Sets up axes for drawing chart"""
self.__axes.clear()
key_setter = [
("title", self.__axes.set_title),
("xlabel", self.__axes.set_xlabel),
("ylabel", self.__axes.set_ylabel),
("xscale", self.__axes.set_xscale),
("yscale", self.__axes.set_yscale),
("xticks", self.__axes.set_xticks),
("xtick_labels", self.__axes.set_xticklabels),
("xtick_params", self.__axes.tick_params),
("yticks", self.__axes.set_yticks),
("ytick_labels", self.__axes.set_yticklabels),
("ytick_params", self.__axes.tick_params),
("xlim", self.__axes.set_xlim),
("ylim", self.__axes.set_ylim),
("xgrid", self.__axes.xaxis.grid),
("ygrid", self.__axes.yaxis.grid),
("xdate_format", self._xdate_setter),
]
key2setter = OrderedDict(key_setter)
for key in key2setter:
if key in axes_data and axes_data[key]:
try:
kwargs_key = key + "_kwargs"
kwargs = axes_data[kwargs_key]
except KeyError:
kwargs = {}
if key == "title":
# Shift title up
kwargs["y"] = 1.08
key2setter[key](axes_data[key], **kwargs) |
Makes x axis a date axis with auto format
Parameters
----------
xdate_format: String
\tSets date formatting | def _xdate_setter(self, xdate_format='%Y-%m-%d'):
"""Makes x axis a date axis with auto format
Parameters
----------
xdate_format: String
\tSets date formatting
"""
if xdate_format:
# We have to validate xdate_format. If wrong then bail out.
try:
self.autofmt_xdate()
datetime.date(2000, 1, 1).strftime(xdate_format)
except ValueError:
self.autofmt_xdate()
return
self.__axes.xaxis_date()
formatter = dates.DateFormatter(xdate_format)
self.__axes.xaxis.set_major_formatter(formatter) |
Plots chart from self.attributes | def draw_chart(self):
"""Plots chart from self.attributes"""
if not hasattr(self, "attributes"):
return
# The first element is always axes data
self._setup_axes(self.attributes[0])
for attribute in self.attributes[1:]:
series = copy(attribute)
# Extract chart type
chart_type_string = series.pop("type")
x_str, y_str = self.plot_type_xy_mapping[chart_type_string]
# Check xdata length
if x_str in series and \
len(series[x_str]) != len(series[y_str]):
# Wrong length --> ignore xdata
series[x_str] = range(len(series[y_str]))
else:
# Solve the problem that the series data may contain utf-8 data
series_list = list(series[x_str])
series_unicode_list = []
for ele in series_list:
if isinstance(ele, types.StringType):
try:
series_unicode_list.append(ele.decode('utf-8'))
except Exception:
series_unicode_list.append(ele)
else:
series_unicode_list.append(ele)
series[x_str] = tuple(series_unicode_list)
fixed_attrs = []
if chart_type_string in self.plot_type_fixed_attrs:
for attr in self.plot_type_fixed_attrs[chart_type_string]:
# Remove attr if it is a fixed (non-kwd) attr
# If a fixed attr is missing, insert a dummy
try:
fixed_attrs.append(tuple(series.pop(attr)))
except KeyError:
fixed_attrs.append(())
# Remove contour chart label info from series
cl_attrs = {}
for contour_label_attr in self.contour_label_attrs:
if contour_label_attr in series:
cl_attrs[self.contour_label_attrs[contour_label_attr]] = \
series.pop(contour_label_attr)
# Remove contourf attributes from series
cf_attrs = {}
for contourf_attr in self.contourf_attrs:
if contourf_attr in series:
cf_attrs[self.contourf_attrs[contourf_attr]] = \
series.pop(contourf_attr)
if not fixed_attrs or all(fixed_attrs):
# Draw series to axes
# Do we have a Sankey plot --> build it
if chart_type_string == "Sankey":
Sankey(self.__axes, **series).finish()
else:
chart_method = getattr(self.__axes, chart_type_string)
plot = chart_method(*fixed_attrs, **series)
# Do we have a filled contour?
try:
if cf_attrs.pop("contour_fill"):
cf_attrs.update(series)
if "linewidths" in cf_attrs:
cf_attrs.pop("linewidths")
if "linestyles" in cf_attrs:
cf_attrs.pop("linestyles")
if not cf_attrs["hatches"]:
cf_attrs.pop("hatches")
self.__axes.contourf(plot, **cf_attrs)
except KeyError:
pass
# Do we have a contour chart label?
try:
if cl_attrs.pop("contour_labels"):
self.__axes.clabel(plot, **cl_attrs)
except KeyError:
pass
# The legend has to be set up after all series are drawn
self._setup_legend(self.attributes[0]) |
Return the source string of a cell | def GetSource(self, row, col, table=None):
"""Return the source string of a cell"""
if table is None:
table = self.grid.current_table
value = self.code_array((row, col, table))
if value is None:
return u""
else:
return value |
Return the result value of a cell, line split if too much data | def GetValue(self, row, col, table=None):
"""Return the result value of a cell, line split if too much data"""
if table is None:
table = self.grid.current_table
try:
cell_code = self.code_array((row, col, table))
except IndexError:
cell_code = None
# Put EOLs into result if it is too long
maxlength = int(config["max_textctrl_length"])
if cell_code is not None and len(cell_code) > maxlength:
chunk = 80
cell_code = "\n".join(cell_code[i:i + chunk]
for i in xrange(0, len(cell_code), chunk))
return cell_code |
Set the value of a cell, merge line breaks | def SetValue(self, row, col, value, refresh=True):
"""Set the value of a cell, merge line breaks"""
# Join code that has been split because of long line issue
value = "".join(value.split("\n"))
key = row, col, self.grid.current_table
old_code = self.grid.code_array(key)
if old_code is None:
old_code = ""
if value != old_code:
self.grid.actions.set_code(key, value) |
Update all displayed values | def UpdateValues(self):
"""Update all displayed values"""
# This sends an event to the grid table
# to update all of the values
msg = wx.grid.GridTableMessage(self,
wx.grid.GRIDTABLE_REQUEST_VIEW_GET_VALUES)
self.grid.ProcessTableMessage(msg) |
(Grid) -> Reset the grid view. Call this to
update the grid if rows and columns have been added or deleted | def ResetView(self):
"""
(Grid) -> Reset the grid view. Call this to
update the grid if rows and columns have been added or deleted
"""
grid = self.grid
current_rows = self.grid.GetNumberRows()
current_cols = self.grid.GetNumberCols()
grid.BeginBatch()
for current, new, delmsg, addmsg in [
(current_rows, self.GetNumberRows(),
wx.grid.GRIDTABLE_NOTIFY_ROWS_DELETED,
wx.grid.GRIDTABLE_NOTIFY_ROWS_APPENDED),
(current_cols, self.GetNumberCols(),
wx.grid.GRIDTABLE_NOTIFY_COLS_DELETED,
wx.grid.GRIDTABLE_NOTIFY_COLS_APPENDED)]:
if new < current:
msg = wx.grid.GridTableMessage(self, delmsg, new,
current - new)
grid.ProcessTableMessage(msg)
elif new > current:
msg = wx.grid.GridTableMessage(self, addmsg, new - current)
grid.ProcessTableMessage(msg)
self.UpdateValues()
grid.EndBatch()
# Reset cell sizes to standard cell size
grid.SetDefaultRowSize(grid.GetDefaultRowSize(),
resizeExistingRows=True)
grid.SetDefaultColSize(grid.GetDefaultColSize(),
resizeExistingCols=True)
# Adjust rows
row_heights = grid.code_array.row_heights
for key in row_heights:
if key[1] == grid.current_table and \
key[0] < self.code_array.shape[0]:
row = key[0]
if row_heights[key] is None:
# Default row size
grid.SetRowSize(row, grid.GetDefaultRowSize())
else:
grid.SetRowSize(row, row_heights[key])
# Adjust columns
col_widths = grid.code_array.col_widths
for key in col_widths:
if key[1] == grid.current_table and \
key[0] < self.code_array.shape[1]:
col = key[0]
if col_widths[key] is None:
# Default row size
grid.SetColSize(col, grid.GetDefaultColSize())
else:
grid.SetColSize(col, col_widths[key])
# update the scrollbars and the displayed part
# of the grid
grid.Freeze()
grid.AdjustScrollbars()
grid.Refresh()
grid.Thaw() |
Posts command event to main window
Command events propagate.
Parameters
----------
* msg_cls: class
\tMessage class from new_command_event()
* kwargs: dict
\tMessage arguments | def post_command_event(target, msg_cls, **kwargs):
"""Posts command event to main window
Command events propagate.
Parameters
----------
* msg_cls: class
\tMessage class from new_command_event()
* kwargs: dict
\tMessage arguments
"""
msg = msg_cls(id=-1, **kwargs)
wx.PostEvent(target, msg) |
Converts data string to iterable.
Parameters:
-----------
datastring: string, defaults to None
\tThe data string to be converted.
\tself.get_clipboard() is called if set to None
sep: string
\tSeparator for columns in datastring | def _convert_clipboard(self, datastring=None, sep='\t'):
"""Converts data string to iterable.
Parameters:
-----------
datastring: string, defaults to None
\tThe data string to be converted.
\tself.get_clipboard() is called if set to None
sep: string
\tSeparator for columns in datastring
"""
if datastring is None:
datastring = self.get_clipboard()
data_it = ((ele for ele in line.split(sep))
for line in datastring.splitlines())
return data_it |
Returns the clipboard content
If a bitmap is contained then it is returned.
Otherwise, the clipboard text is returned. | def get_clipboard(self):
"""Returns the clipboard content
If a bitmap is contained then it is returned.
Otherwise, the clipboard text is returned.
"""
bmpdata = wx.BitmapDataObject()
textdata = wx.TextDataObject()
if self.clipboard.Open():
is_bmp_present = self.clipboard.GetData(bmpdata)
self.clipboard.GetData(textdata)
self.clipboard.Close()
else:
wx.MessageBox(_("Can't open the clipboard"), _("Error"))
if is_bmp_present:
return bmpdata.GetBitmap()
else:
return textdata.GetText() |
Writes data to the clipboard
Parameters
----------
data: Object
\tData object for clipboard
datatype: String in ["text", "bitmap"]
\tIdentifies datatype to be copied to the clipboard | def set_clipboard(self, data, datatype="text"):
"""Writes data to the clipboard
Parameters
----------
data: Object
\tData object for clipboard
datatype: String in ["text", "bitmap"]
\tIdentifies datatype to be copied to the clipboard
"""
error_log = []
if datatype == "text":
clip_data = wx.TextDataObject(text=data)
elif datatype == "bitmap":
clip_data = wx.BitmapDataObject(bitmap=data)
else:
msg = _("Datatype {type} unknown").format(type=datatype)
raise ValueError(msg)
if self.clipboard.Open():
self.clipboard.SetData(clip_data)
self.clipboard.Close()
else:
wx.MessageBox(_("Can't open the clipboard"), _("Error"))
return error_log |
Draws a rect | def draw_rect(grid, attr, dc, rect):
"""Draws a rect"""
dc.SetBrush(wx.Brush(wx.Colour(15, 255, 127), wx.SOLID))
dc.SetPen(wx.Pen(wx.BLUE, 1, wx.SOLID))
dc.DrawRectangleRect(rect) |
Draws bitmap | def draw_bmp(bmp_filepath):
"""Draws bitmap"""
def draw(grid, attr, dc, rect):
bmp = wx.EmptyBitmap(100, 100)
try:
dummy = open(bmp_filepath)
dummy.close()
bmp.LoadFile(bmp_filepath, wx.BITMAP_TYPE_ANY)
dc.DrawBitmap(bmp, 0, 0)
except:
return
return draw |
Displays progress and returns True if abort
Parameters
----------
cycle: Integer
\tThe current operation cycle
statustext: String
\tLeft text in statusbar to be displayed
total_elements: Integer:
\tThe number of elements that have to be processed
freq: Integer, defaults to None
\tNo. operations between two abort possibilities, 1000 if None | def _is_aborted(self, cycle, statustext, total_elements=None, freq=None):
"""Displays progress and returns True if abort
Parameters
----------
cycle: Integer
\tThe current operation cycle
statustext: String
\tLeft text in statusbar to be displayed
total_elements: Integer:
\tThe number of elements that have to be processed
freq: Integer, defaults to None
\tNo. operations between two abort possibilities, 1000 if None
"""
if total_elements is None:
statustext += _("{nele} elements processed. Press <Esc> to abort.")
else:
statustext += _("{nele} of {totalele} elements processed. "
"Press <Esc> to abort.")
if freq is None:
show_msg = False
freq = 1000
else:
show_msg = True
# Show progress in statusbar each freq (1000) cells
if cycle % freq == 0:
if show_msg:
text = statustext.format(nele=cycle, totalele=total_elements)
try:
post_command_event(self.main_window, self.StatusBarMsg,
text=text)
except TypeError:
# The main window does not exist any more
pass
# Now wait for the statusbar update to be written on screen
if is_gtk():
try:
wx.Yield()
except:
pass
# Abort if we have to
if self.need_abort:
# We have to abort`
return True
# Continue
return False |
Returns True if a valid signature is present for filename | def validate_signature(self, filename):
"""Returns True if a valid signature is present for filename"""
if not GPG_PRESENT:
return False
sigfilename = filename + '.sig'
try:
with open(sigfilename):
pass
except IOError:
# Signature file does not exist
return False
# Check if the sig is valid for the sigfile
# TODO: Check for whitespace in filepaths
return verify(sigfilename, filename) |
Leaves safe mode | def leave_safe_mode(self):
"""Leaves safe mode"""
self.code_array.safe_mode = False
# Clear result cache
self.code_array.result_cache.clear()
# Execute macros
self.main_window.actions.execute_macros()
post_command_event(self.main_window, self.SafeModeExitMsg) |
Sets safe mode if signature missing of invalid | def approve(self, filepath):
"""Sets safe mode if signature missing of invalid"""
try:
signature_valid = self.validate_signature(filepath)
except ValueError:
# GPG is not installed
signature_valid = False
if signature_valid:
self.leave_safe_mode()
post_command_event(self.main_window, self.SafeModeExitMsg)
statustext = _("Valid signature found. File is trusted.")
post_command_event(self.main_window, self.StatusBarMsg,
text=statustext)
else:
self.enter_safe_mode()
post_command_event(self.main_window, self.SafeModeEntryMsg)
statustext = \
_("File is not properly signed. Safe mode "
"activated. Select File -> Approve to leave safe mode.")
post_command_event(self.main_window, self.StatusBarMsg,
text=statustext) |
Clears globals and reloads modules | def clear_globals_reload_modules(self):
"""Clears globals and reloads modules"""
self.code_array.clear_globals()
self.code_array.reload_modules()
# Clear result cache
self.code_array.result_cache.clear() |
Returns infile version string. | def _get_file_version(self, infile):
"""Returns infile version string."""
# Determine file version
for line1 in infile:
if line1.strip() != "[Pyspread save file version]":
raise ValueError(_("File format unsupported."))
break
for line2 in infile:
return line2.strip() |
Empties grid and sets shape to shape
Clears all attributes, row heights, column withs and frozen states.
Empties undo/redo list and caches. Empties globals.
Properties
----------
shape: 3-tuple of Integer, defaults to None
\tTarget shape of grid after clearing all content.
\tShape unchanged if None | def clear(self, shape=None):
"""Empties grid and sets shape to shape
Clears all attributes, row heights, column withs and frozen states.
Empties undo/redo list and caches. Empties globals.
Properties
----------
shape: 3-tuple of Integer, defaults to None
\tTarget shape of grid after clearing all content.
\tShape unchanged if None
"""
# Without setting this explicitly, the cursor is set too late
self.grid.actions.cursor = 0, 0, 0
self.grid.current_table = 0
post_command_event(self.main_window.grid, self.GotoCellMsg,
key=(0, 0, 0))
# Clear cells
self.code_array.dict_grid.clear()
# Clear attributes
del self.code_array.dict_grid.cell_attributes[:]
if shape is not None:
# Set shape
self.code_array.shape = shape
# Clear row heights and column widths
self.code_array.row_heights.clear()
self.code_array.col_widths.clear()
# Clear macros
self.code_array.macros = ""
# Clear caches
self.code_array.result_cache.clear()
# Clear globals
self.code_array.clear_globals()
self.code_array.reload_modules() |
Opens a file that is specified in event.attr
Parameters
----------
event.attr: Dict
\tkey filepath contains file path of file to be loaded
\tkey filetype contains file type of file to be loaded
\tFiletypes can be pys, pysu, xls | def open(self, event):
"""Opens a file that is specified in event.attr
Parameters
----------
event.attr: Dict
\tkey filepath contains file path of file to be loaded
\tkey filetype contains file type of file to be loaded
\tFiletypes can be pys, pysu, xls
"""
filepath = event.attr["filepath"]
try:
filetype = event.attr["filetype"]
except KeyError:
try:
file_ext = filepath.strip().split(".")[-1]
except:
file_ext = None
if file_ext in ["pys", "pysu", "xls", "xlsx", "ods"]:
filetype = file_ext
else:
filetype = "pys"
type2opener = {
"pys": (Bz2AOpen, [filepath, "r"], {"main_window":
self.main_window}),
"pysu": (AOpen, [filepath, "r"], {"main_window": self.main_window})
}
if xlrd is not None:
type2opener["xls"] = \
(xlrd.open_workbook, [filepath], {"formatting_info": True})
type2opener["xlsx"] = \
(xlrd.open_workbook, [filepath], {"formatting_info": False})
if odf is not None and Ods is not None:
type2opener["ods"] = (open, [filepath, "rb"], {})
# Specify the interface that shall be used
opener, op_args, op_kwargs = type2opener[filetype]
Interface = self.type2interface[filetype]
# Set state for file open
self.opening = True
try:
with opener(*op_args, **op_kwargs) as infile:
# Make loading safe
self.approve(filepath)
if xlrd is None:
interface_errors = (ValueError, )
else:
interface_errors = (ValueError, xlrd.biffh.XLRDError)
try:
wx.BeginBusyCursor()
self.grid.Disable()
self.clear()
interface = Interface(self.grid.code_array, infile)
interface.to_code_array()
self.grid.main_window.macro_panel.codetext_ctrl.SetText(
self.grid.code_array.macros)
except interface_errors, err:
post_command_event(self.main_window, self.StatusBarMsg,
text=str(err))
finally:
self.grid.GetTable().ResetView()
post_command_event(self.main_window, self.ResizeGridMsg,
shape=self.grid.code_array.shape)
self.grid.Enable()
wx.EndBusyCursor()
# Execute macros
self.main_window.actions.execute_macros()
self.grid.GetTable().ResetView()
self.grid.ForceRefresh()
# File sucessfully opened. Approve again to show status.
self.approve(filepath)
# Change current directory to file directory
filedir = os.path.dirname(filepath)
os.chdir(filedir)
except IOError, err:
txt = _("Error opening file {filepath}:").format(filepath=filepath)
txt += " " + str(err)
post_command_event(self.main_window, self.StatusBarMsg, text=txt)
return False
except EOFError:
# Normally on empty grids
pass
finally:
# Unset state for file open
self.opening = False |
Signs file if possible | def sign_file(self, filepath):
"""Signs file if possible"""
if not GPG_PRESENT:
return
signed_data = sign(filepath)
signature = signed_data.data
if signature is None or not signature:
statustext = _('Error signing file. ') + signed_data.stderr
try:
post_command_event(self.main_window, self.StatusBarMsg,
text=statustext)
except TypeError:
# The main window does not exist any more
pass
return
with open(filepath + '.sig', 'wb') as signfile:
signfile.write(signature)
# Statustext differs if a save has occurred
if self.code_array.safe_mode:
statustext = _('File saved and signed')
else:
statustext = _('File signed')
try:
post_command_event(self.main_window, self.StatusBarMsg,
text=statustext)
except TypeError:
# The main window does not exist any more
pass |
Sets application save states | def _set_save_states(self):
"""Sets application save states"""
wx.BeginBusyCursor()
self.saving = True
self.grid.Disable() |
Releases application save states | def _release_save_states(self):
"""Releases application save states"""
self.saving = False
self.grid.Enable()
wx.EndBusyCursor()
# Mark content as unchanged
try:
post_command_event(self.main_window, self.ContentChangedMsg)
except TypeError:
# The main window does not exist any more
pass |
Moves tmpfile over file after saving is finished
Parameters
----------
filepath: String
\tTarget file path for xls file
tmpfilepath: String
\tTemporary file file path for xls file | def _move_tmp_file(self, tmpfilepath, filepath):
"""Moves tmpfile over file after saving is finished
Parameters
----------
filepath: String
\tTarget file path for xls file
tmpfilepath: String
\tTemporary file file path for xls file
"""
try:
shutil.move(tmpfilepath, filepath)
except OSError, err:
# No tmp file present
post_command_event(self.main_window, self.StatusBarMsg, text=err) |
Saves file as xls workbook
Parameters
----------
filepath: String
\tTarget file path for xls file | def _save_xls(self, filepath):
"""Saves file as xls workbook
Parameters
----------
filepath: String
\tTarget file path for xls file
"""
Interface = self.type2interface["xls"]
workbook = xlwt.Workbook()
interface = Interface(self.grid.code_array, workbook)
interface.from_code_array()
try:
workbook.save(filepath)
except IOError, err:
try:
post_command_event(self.main_window, self.StatusBarMsg,
text=err)
except TypeError:
# The main window does not exist any more
pass |
Saves file as pys file and returns True if save success
Parameters
----------
filepath: String
\tTarget file path for xls file | def _save_pys(self, filepath):
"""Saves file as pys file and returns True if save success
Parameters
----------
filepath: String
\tTarget file path for xls file
"""
try:
with Bz2AOpen(filepath, "wb",
main_window=self.main_window) as outfile:
interface = Pys(self.grid.code_array, outfile)
interface.from_code_array()
except (IOError, ValueError), err:
try:
post_command_event(self.main_window, self.StatusBarMsg,
text=err)
return
except TypeError:
# The main window does not exist any more
pass
return not outfile.aborted |
Sign so that the new file may be retrieved without safe mode | def _save_sign(self, filepath):
"""Sign so that the new file may be retrieved without safe mode"""
if self.code_array.safe_mode:
msg = _("File saved but not signed because it is unapproved.")
try:
post_command_event(self.main_window, self.StatusBarMsg,
text=msg)
except TypeError:
# The main window does not exist any more
pass
else:
try:
self.sign_file(filepath)
except ValueError, err:
msg = "Signing file failed. " + unicode(err)
post_command_event(self.main_window, self.StatusBarMsg,
text=msg) |
Saves a file that is specified in event.attr
Parameters
----------
event.attr: Dict
\tkey filepath contains file path of file to be saved | def save(self, event):
"""Saves a file that is specified in event.attr
Parameters
----------
event.attr: Dict
\tkey filepath contains file path of file to be saved
"""
filepath = event.attr["filepath"]
try:
filetype = event.attr["filetype"]
except KeyError:
filetype = "pys"
# If saving is already in progress abort
if self.saving:
return
# Use tmpfile to make sure that old save file does not get lost
# on abort save
__, tmpfilepath = tempfile.mkstemp()
if filetype == "xls":
self._set_save_states()
self._save_xls(tmpfilepath)
self._move_tmp_file(tmpfilepath, filepath)
self._release_save_states()
elif filetype == "pys" or filetype == "all":
self._set_save_states()
if self._save_pys(tmpfilepath):
# Writing was successful
self._move_tmp_file(tmpfilepath, filepath)
self._save_sign(filepath)
self._release_save_states()
elif filetype == "pysu":
self._set_save_states()
if self._save_pysu(tmpfilepath):
# Writing was successful
self._move_tmp_file(tmpfilepath, filepath)
self._save_sign(filepath)
self._release_save_states()
else:
os.remove(tmpfilepath)
msg = "Filetype {filetype} unknown.".format(filetype=filetype)
raise ValueError(msg)
try:
os.remove(tmpfilepath)
except OSError:
pass |
Sets row height and marks grid as changed | def set_row_height(self, row, height):
"""Sets row height and marks grid as changed"""
# Mark content as changed
post_command_event(self.main_window, self.ContentChangedMsg)
tab = self.grid.current_table
self.code_array.set_row_height(row, tab, height)
self.grid.SetRowSize(row, height) |
Adds no_rows rows before row, appends if row > maxrows
and marks grid as changed | def insert_rows(self, row, no_rows=1):
"""Adds no_rows rows before row, appends if row > maxrows
and marks grid as changed
"""
# Mark content as changed
post_command_event(self.main_window, self.ContentChangedMsg)
tab = self.grid.current_table
self.code_array.insert(row, no_rows, axis=0, tab=tab) |
Deletes no_rows rows and marks grid as changed | def delete_rows(self, row, no_rows=1):
"""Deletes no_rows rows and marks grid as changed"""
# Mark content as changed
post_command_event(self.main_window, self.ContentChangedMsg)
tab = self.grid.current_table
try:
self.code_array.delete(row, no_rows, axis=0, tab=tab)
except ValueError, err:
post_command_event(self.main_window, self.StatusBarMsg,
text=err.message) |
Sets column width and marks grid as changed | def set_col_width(self, col, width):
"""Sets column width and marks grid as changed"""
# Mark content as changed
post_command_event(self.main_window, self.ContentChangedMsg)
tab = self.grid.current_table
self.code_array.set_col_width(col, tab, width)
self.grid.SetColSize(col, width) |
Adds no_cols columns before col, appends if col > maxcols
and marks grid as changed | def insert_cols(self, col, no_cols=1):
"""Adds no_cols columns before col, appends if col > maxcols
and marks grid as changed
"""
# Mark content as changed
post_command_event(self.main_window, self.ContentChangedMsg)
tab = self.grid.current_table
self.code_array.insert(col, no_cols, axis=1, tab=tab) |
Deletes no_cols column and marks grid as changed | def delete_cols(self, col, no_cols=1):
"""Deletes no_cols column and marks grid as changed"""
# Mark content as changed
post_command_event(self.main_window, self.ContentChangedMsg)
tab = self.grid.current_table
try:
self.code_array.delete(col, no_cols, axis=1, tab=tab)
except ValueError, err:
post_command_event(self.main_window, self.StatusBarMsg,
text=err.message) |
Adds no_tabs tabs before table, appends if tab > maxtabs
and marks grid as changed | def insert_tabs(self, tab, no_tabs=1):
"""Adds no_tabs tabs before table, appends if tab > maxtabs
and marks grid as changed
"""
# Mark content as changed
post_command_event(self.main_window, self.ContentChangedMsg)
self.code_array.insert(tab, no_tabs, axis=2)
# Update TableChoiceIntCtrl
shape = self.grid.code_array.shape
post_command_event(self.main_window, self.ResizeGridMsg, shape=shape) |
Deletes no_tabs tabs and marks grid as changed | def delete_tabs(self, tab, no_tabs=1):
"""Deletes no_tabs tabs and marks grid as changed"""
# Mark content as changed
post_command_event(self.main_window, self.ContentChangedMsg)
try:
self.code_array.delete(tab, no_tabs, axis=2)
# Update TableChoiceIntCtrl
shape = self.grid.code_array.shape
post_command_event(self.main_window, self.ResizeGridMsg,
shape=shape)
except ValueError, err:
post_command_event(self.main_window, self.StatusBarMsg,
text=err.message) |
Sets abort if pasting and if escape is pressed | def on_key(self, event):
"""Sets abort if pasting and if escape is pressed"""
# If paste is running and Esc is pressed then we need to abort
if event.GetKeyCode() == wx.WXK_ESCAPE and \
self.pasting or self.grid.actions.saving:
self.need_abort = True
event.Skip() |
Returns full key even if table is omitted | def _get_full_key(self, key):
"""Returns full key even if table is omitted"""
length = len(key)
if length == 3:
return key
elif length == 2:
row, col = key
tab = self.grid.current_table
return row, col, tab
else:
msg = _("Key length {length} not in (2, 3)").format(length=length)
raise ValueError(msg) |
Aborts import | def _abort_paste(self):
"""Aborts import"""
statustext = _("Paste aborted.")
post_command_event(self.main_window, self.StatusBarMsg,
text=statustext)
self.pasting = False
self.need_abort = False |
Displays overflow message after import in statusbar | def _show_final_overflow_message(self, row_overflow, col_overflow):
"""Displays overflow message after import in statusbar"""
if row_overflow and col_overflow:
overflow_cause = _("rows and columns")
elif row_overflow:
overflow_cause = _("rows")
elif col_overflow:
overflow_cause = _("columns")
else:
raise AssertionError(_("Import cell overflow missing"))
statustext = \
_("The imported data did not fit into the grid {cause}. "
"It has been truncated. Use a larger grid for full import.").\
format(cause=overflow_cause)
post_command_event(self.main_window, self.StatusBarMsg,
text=statustext) |
Show actually pasted number of cells | def _show_final_paste_message(self, tl_key, no_pasted_cells):
"""Show actually pasted number of cells"""
plural = "" if no_pasted_cells == 1 else _("s")
statustext = _("{ncells} cell{plural} pasted at cell {topleft}").\
format(ncells=no_pasted_cells, plural=plural, topleft=tl_key)
post_command_event(self.main_window, self.StatusBarMsg,
text=statustext) |
Pastes data into grid from top left cell tl_key
Parameters
----------
ul_key: Tuple
\key of top left cell of paste area
data: iterable of iterables where inner iterable returns string
\tThe outer iterable represents rows
freq: Integer, defaults to None
\tStatus message frequency | def paste_to_current_cell(self, tl_key, data, freq=None):
"""Pastes data into grid from top left cell tl_key
Parameters
----------
ul_key: Tuple
\key of top left cell of paste area
data: iterable of iterables where inner iterable returns string
\tThe outer iterable represents rows
freq: Integer, defaults to None
\tStatus message frequency
"""
self.pasting = True
grid_rows, grid_cols, __ = self.grid.code_array.shape
self.need_abort = False
tl_row, tl_col, tl_tab = self._get_full_key(tl_key)
row_overflow = False
col_overflow = False
no_pasted_cells = 0
for src_row, row_data in enumerate(data):
target_row = tl_row + src_row
if self.grid.actions._is_aborted(src_row, _("Pasting cells... "),
freq=freq):
self._abort_paste()
return False
# Check if rows fit into grid
if target_row >= grid_rows:
row_overflow = True
break
for src_col, cell_data in enumerate(row_data):
target_col = tl_col + src_col
if target_col >= grid_cols:
col_overflow = True
break
if cell_data is not None:
# Is only None if pasting into selection
key = target_row, target_col, tl_tab
try:
CellActions.set_code(self, key, cell_data)
no_pasted_cells += 1
except KeyError:
pass
if row_overflow or col_overflow:
self._show_final_overflow_message(row_overflow, col_overflow)
else:
self._show_final_paste_message(tl_key, no_pasted_cells)
self.pasting = False |
Generator that yields data for selection paste | def selection_paste_data_gen(self, selection, data, freq=None):
"""Generator that yields data for selection paste"""
(bb_top, bb_left), (bb_bottom, bb_right) = \
selection.get_grid_bbox(self.grid.code_array.shape)
bbox_height = bb_bottom - bb_top + 1
bbox_width = bb_right - bb_left + 1
for row, row_data in enumerate(itertools.cycle(data)):
# Break if row is not in selection bbox
if row >= bbox_height:
break
# Duplicate row data if selection is wider than row data
row_data = list(row_data)
duplicated_row_data = row_data * (bbox_width // len(row_data) + 1)
duplicated_row_data = duplicated_row_data[:bbox_width]
for col in xrange(len(duplicated_row_data)):
if (bb_top, bb_left + col) not in selection:
duplicated_row_data[col] = None
yield duplicated_row_data |
Pastes data into grid selection | def paste_to_selection(self, selection, data, freq=None):
"""Pastes data into grid selection"""
(bb_top, bb_left), (bb_bottom, bb_right) = \
selection.get_grid_bbox(self.grid.code_array.shape)
adjusted_data = self.selection_paste_data_gen(selection, data)
self.paste_to_current_cell((bb_top, bb_left), adjusted_data, freq=freq) |
Pastes data into grid, marks grid changed
If no selection is present, data is pasted starting with current cell
If a selection is present, data is pasted fully if the selection is
smaller. If the selection is larger then data is duplicated.
Parameters
----------
ul_key: Tuple
\key of top left cell of paste area
data: iterable of iterables where inner iterable returns string
\tThe outer iterable represents rows
freq: Integer, defaults to None
\tStatus message frequency | def paste(self, tl_key, data, freq=None):
"""Pastes data into grid, marks grid changed
If no selection is present, data is pasted starting with current cell
If a selection is present, data is pasted fully if the selection is
smaller. If the selection is larger then data is duplicated.
Parameters
----------
ul_key: Tuple
\key of top left cell of paste area
data: iterable of iterables where inner iterable returns string
\tThe outer iterable represents rows
freq: Integer, defaults to None
\tStatus message frequency
"""
# Get selection bounding box
selection = self.get_selection()
# Mark content as changed
post_command_event(self.main_window, self.ContentChangedMsg)
if selection:
# There is a selection. Paste into it
self.paste_to_selection(selection, data, freq=freq)
else:
# There is no selection. Paste from top left cell.
self.paste_to_current_cell(tl_key, data, freq=freq) |
Grid shape change event handler, marks content as changed | def change_grid_shape(self, shape):
"""Grid shape change event handler, marks content as changed"""
# Mark content as changed
post_command_event(self.main_window, self.ContentChangedMsg)
self.code_array.shape = shape
# Update TableChoiceIntCtrl
post_command_event(self.main_window, self.ResizeGridMsg, shape=shape)
# Change grid table dimensions
self.grid.GetTable().ResetView()
# Clear caches
self.code_array.result_cache.clear() |
Replaces cells in current selection so that they are sorted | def replace_cells(self, key, sorted_row_idxs):
"""Replaces cells in current selection so that they are sorted"""
row, col, tab = key
new_keys = {}
del_keys = []
selection = self.grid.actions.get_selection()
for __row, __col, __tab in self.grid.code_array:
if __tab == tab and \
(not selection or (__row, __col) in selection):
new_row = sorted_row_idxs.index(__row)
if __row != new_row:
new_keys[(new_row, __col, __tab)] = \
self.grid.code_array((__row, __col, __tab))
del_keys.append((__row, __col, __tab))
for key in del_keys:
self.grid.code_array.pop(key)
for key in new_keys:
CellActions.set_code(self, key, new_keys[key]) |
Sorts selection (or grid if none) corresponding to column of key | def sort_ascending(self, key):
"""Sorts selection (or grid if none) corresponding to column of key"""
row, col, tab = key
scells = self.grid.code_array[:, col, tab]
def sorter(i):
sorted_ele = scells[i]
return sorted_ele is None, sorted_ele
sorted_row_idxs = sorted(xrange(len(scells)), key=sorter)
self.replace_cells(key, sorted_row_idxs)
self.grid.ForceRefresh() |
Sorts inversely selection (or grid if none)
corresponding to column of key | def sort_descending(self, key):
"""Sorts inversely selection (or grid if none)
corresponding to column of key
"""
row, col, tab = key
scells = self.grid.code_array[:, col, tab]
sorted_row_idxs = sorted(xrange(len(scells)), key=scells.__getitem__)
sorted_row_idxs.reverse()
self.replace_cells(key, sorted_row_idxs)
self.grid.ForceRefresh() |
Creates a new spreadsheet. Expects code_array in event. | def new(self, event):
"""Creates a new spreadsheet. Expects code_array in event."""
# Grid table handles interaction to code_array
self.grid.actions.clear(event.shape)
_grid_table = GridTable(self.grid, self.grid.code_array)
self.grid.SetTable(_grid_table, True)
# Update toolbars
self.grid.update_entry_line()
self.grid.update_attribute_toolbar() |
Zooms grid rows | def _zoom_rows(self, zoom):
"""Zooms grid rows"""
self.grid.SetDefaultRowSize(self.grid.std_row_size * zoom,
resizeExistingRows=True)
self.grid.SetRowLabelSize(self.grid.row_label_size * zoom)
for row, tab in self.code_array.row_heights:
if tab == self.grid.current_table and \
row < self.grid.code_array.shape[0]:
base_row_width = self.code_array.row_heights[(row, tab)]
if base_row_width is None:
base_row_width = self.grid.GetDefaultRowSize()
zoomed_row_size = base_row_width * zoom
self.grid.SetRowSize(row, zoomed_row_size) |
Zooms grid columns | def _zoom_cols(self, zoom):
"""Zooms grid columns"""
self.grid.SetDefaultColSize(self.grid.std_col_size * zoom,
resizeExistingCols=True)
self.grid.SetColLabelSize(self.grid.col_label_size * zoom)
for col, tab in self.code_array.col_widths:
if tab == self.grid.current_table and \
col < self.grid.code_array.shape[1]:
base_col_width = self.code_array.col_widths[(col, tab)]
if base_col_width is None:
base_col_width = self.grid.GetDefaultColSize()
zoomed_col_size = base_col_width * zoom
self.grid.SetColSize(col, zoomed_col_size) |
Adjust grid label font to zoom factor | def _zoom_labels(self, zoom):
"""Adjust grid label font to zoom factor"""
labelfont = self.grid.GetLabelFont()
default_fontsize = get_default_font().GetPointSize()
labelfont.SetPointSize(max(1, int(round(default_fontsize * zoom))))
self.grid.SetLabelFont(labelfont) |
Zooms to zoom factor | def zoom(self, zoom=None):
"""Zooms to zoom factor"""
status = True
if zoom is None:
zoom = self.grid.grid_renderer.zoom
status = False
# Zoom factor for grid content
self.grid.grid_renderer.zoom = zoom
# Zoom grid labels
self._zoom_labels(zoom)
# Zoom rows and columns
self._zoom_rows(zoom)
self._zoom_cols(zoom)
if self.main_window.IsFullScreen():
# Do not display labels in fullscreen mode
self.main_window.handlers.row_label_size = \
self.grid.GetRowLabelSize()
self.main_window.handlers.col_label_size = \
self.grid.GetColLabelSize()
self.grid.HideRowLabels()
self.grid.HideColLabels()
self.grid.ForceRefresh()
if status:
statustext = _(u"Zoomed to {0:.2f}.").format(zoom)
post_command_event(self.main_window, self.StatusBarMsg,
text=statustext) |
Zooms in by zoom factor | def zoom_in(self):
"""Zooms in by zoom factor"""
zoom = self.grid.grid_renderer.zoom
target_zoom = zoom * (1 + config["zoom_factor"])
if target_zoom < config["maximum_zoom"]:
self.zoom(target_zoom) |
Zooms out by zoom factor | def zoom_out(self):
"""Zooms out by zoom factor"""
zoom = self.grid.grid_renderer.zoom
target_zoom = zoom * (1 - config["zoom_factor"])
if target_zoom > config["minimum_zoom"]:
self.zoom(target_zoom) |
Returns the total height of all grid rows | def _get_rows_height(self):
"""Returns the total height of all grid rows"""
tab = self.grid.current_table
no_rows = self.grid.code_array.shape[0]
default_row_height = self.grid.code_array.cell_attributes.\
default_cell_attributes["row-height"]
non_standard_row_heights = []
__row_heights = self.grid.code_array.row_heights
for __row, __tab in __row_heights:
if __tab == tab:
non_standard_row_heights.append(__row_heights[(__row, __tab)])
rows_height = sum(non_standard_row_heights)
rows_height += \
(no_rows - len(non_standard_row_heights)) * default_row_height
return rows_height |
Returns the total width of all grid cols | def _get_cols_width(self):
"""Returns the total width of all grid cols"""
tab = self.grid.current_table
no_cols = self.grid.code_array.shape[1]
default_col_width = self.grid.code_array.cell_attributes.\
default_cell_attributes["column-width"]
non_standard_col_widths = []
__col_widths = self.grid.code_array.col_widths
for __col, __tab in __col_widths:
if __tab == tab:
non_standard_col_widths.append(__col_widths[(__col, __tab)])
cols_width = sum(non_standard_col_widths)
cols_width += \
(no_cols - len(non_standard_col_widths)) * default_col_width
return cols_width |
Displays cell code of cell key in status bar | def on_mouse_over(self, key):
"""Displays cell code of cell key in status bar"""
def split_lines(string, line_length=80):
"""Returns string that is split into lines of length line_length"""
result = u""
line = 0
while len(string) > line_length * line:
line_start = line * line_length
result += string[line_start:line_start+line_length]
result += '\n'
line += 1
return result[:-1]
row, col, tab = key
# If the cell is a button cell or a frozen cell then do nothing
cell_attributes = self.grid.code_array.cell_attributes
if cell_attributes[key]["button_cell"] or \
cell_attributes[key]["frozen"]:
return
if (row, col) != self.prev_rowcol and row >= 0 and col >= 0:
self.prev_rowcol[:] = [row, col]
max_result_length = int(config["max_result_length"])
table = self.grid.GetTable()
hinttext = table.GetSource(row, col, tab)[:max_result_length]
if hinttext is None:
hinttext = ''
post_command_event(self.main_window, self.StatusBarMsg,
text=hinttext)
cell_res = self.grid.code_array[row, col, tab]
if cell_res is None:
self.grid.SetToolTip(None)
return
try:
cell_res_str = unicode(cell_res)
except UnicodeEncodeError:
cell_res_str = unicode(cell_res, encoding='utf-8')
if len(cell_res_str) > max_result_length:
cell_res_str = cell_res_str[:max_result_length] + ' [...]'
self.grid.SetToolTipString(split_lines(cell_res_str)) |
Zooms the rid to fit the window.
Only has an effect if the resulting zoom level is between
minimum and maximum zoom level. | def zoom_fit(self):
"""Zooms the rid to fit the window.
Only has an effect if the resulting zoom level is between
minimum and maximum zoom level.
"""
zoom = self.grid.grid_renderer.zoom
grid_width, grid_height = self.grid.GetSize()
rows_height = self._get_rows_height() + \
(float(self.grid.GetColLabelSize()) / zoom)
cols_width = self._get_cols_width() + \
(float(self.grid.GetRowLabelSize()) / zoom)
# Check target zoom for rows
zoom_height = float(grid_height) / rows_height
# Check target zoom for columns
zoom_width = float(grid_width) / cols_width
# Use the minimum target zoom from rows and column target zooms
target_zoom = min(zoom_height, zoom_width)
# Zoom only if between min and max
if config["minimum_zoom"] < target_zoom < config["maximum_zoom"]:
self.zoom(target_zoom) |
Returns visible area
Format is a tuple of the top left tuple and the lower right tuple | def get_visible_area(self):
"""Returns visible area
Format is a tuple of the top left tuple and the lower right tuple
"""
grid = self.grid
top = grid.YToRow(grid.GetViewStart()[1] * grid.ScrollLineX)
left = grid.XToCol(grid.GetViewStart()[0] * grid.ScrollLineY)
# Now start at top left for determining the bottom right visible cell
bottom, right = top, left
while grid.IsVisible(bottom, left, wholeCellVisible=False):
bottom += 1
while grid.IsVisible(top, right, wholeCellVisible=False):
right += 1
# The derived lower right cell is *NOT* visible
bottom -= 1
right -= 1
return (top, left), (bottom, right) |
Switches grid to table
Parameters
----------
event.newtable: Integer
\tTable that the grid is switched to | def switch_to_table(self, event):
"""Switches grid to table
Parameters
----------
event.newtable: Integer
\tTable that the grid is switched to
"""
newtable = event.newtable
no_tabs = self.grid.code_array.shape[2] - 1
if 0 <= newtable <= no_tabs:
self.grid.current_table = newtable
self.grid.SetToolTip(None)
# Delete renderer cache
self.grid.grid_renderer.cell_cache.clear()
# Delete video cells
video_cells = self.grid.grid_renderer.video_cells
for key in video_cells:
video_panel = video_cells[key]
video_panel.player.stop()
video_panel.player.release()
video_panel.Destroy()
video_cells.clear()
# Hide cell editor
cell_editor = self.grid.GetCellEditor(self.grid.GetGridCursorRow(),
self.grid.GetGridCursorCol())
try:
cell_editor.Reset()
except AttributeError:
# No cell editor open
pass
self.grid.HideCellEditControl()
# Change value of entry_line and table choice
post_command_event(self.main_window, self.TableChangedMsg,
table=newtable)
# Reset row heights and column widths by zooming
self.zoom() |
Returns current grid cursor cell (row, col, tab) | def get_cursor(self):
"""Returns current grid cursor cell (row, col, tab)"""
return self.grid.GetGridCursorRow(), self.grid.GetGridCursorCol(), \
self.grid.current_table |
Changes the grid cursor cell.
Parameters
----------
value: 2-tuple or 3-tuple of String
\trow, col, tab or row, col for target cursor position | def set_cursor(self, value):
"""Changes the grid cursor cell.
Parameters
----------
value: 2-tuple or 3-tuple of String
\trow, col, tab or row, col for target cursor position
"""
shape = self.grid.code_array.shape
if len(value) == 3:
self.grid._last_selected_cell = row, col, tab = value
if row < 0 or col < 0 or tab < 0 or \
row >= shape[0] or col >= shape[1] or tab >= shape[2]:
raise ValueError("Cell {value} outside of {shape}".format(
value=value, shape=shape))
if tab != self.cursor[2]:
post_command_event(self.main_window,
self.GridActionTableSwitchMsg, newtable=tab)
if is_gtk():
try:
wx.Yield()
except:
pass
else:
row, col = value
if row < 0 or col < 0 or row >= shape[0] or col >= shape[1]:
raise ValueError("Cell {value} outside of {shape}".format(
value=value, shape=shape))
self.grid._last_selected_cell = row, col, self.grid.current_table
if not (row is None and col is None):
if not self.grid.IsVisible(row, col, wholeCellVisible=True):
self.grid.MakeCellVisible(row, col)
self.grid.SetGridCursor(row, col) |
Returns selected cells in grid as Selection object | def get_selection(self):
"""Returns selected cells in grid as Selection object"""
# GetSelectedCells: individual cells selected by ctrl-clicking
# GetSelectedRows: rows selected by clicking on the labels
# GetSelectedCols: cols selected by clicking on the labels
# GetSelectionBlockTopLeft
# GetSelectionBlockBottomRight: For blocks selected by dragging
# across the grid cells.
block_top_left = self.grid.GetSelectionBlockTopLeft()
block_bottom_right = self.grid.GetSelectionBlockBottomRight()
rows = self.grid.GetSelectedRows()
cols = self.grid.GetSelectedCols()
cells = self.grid.GetSelectedCells()
return Selection(block_top_left, block_bottom_right, rows, cols, cells) |