rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
events = self.__fetch_events(event_codes, time_range[0], time_range[1])
events = self._fetch_events(event_codes, time_range[0], time_range[1])
def get_events(self, **kwargs): event_codes = [] time_range = [] # shortcut to argument-free version if "codes" not in kwargs and "time_range" not in kwargs: return self.__fetch_all_events() codec = self.codec if codec is None: raise NoValidCodecException reverse_codec = self.reverse_codec if reverse_codec is None: raise NoValidCodecException if "codes" in kwargs: event_codes = kwargs["codes"] for i in range(0, len(event_codes)): code = event_codes[i] if(type(code) == str): if(code in reverse_codec): event_codes[i] = reverse_codec[code] else: event_codes = codec.keys() # all events if "time_range" in kwargs: time_range = kwargs["time_range"] else: time_range = [self.minimum_time, self.maximum_time] # TODO: convert possible string-based event codes events = self.__fetch_events(event_codes, time_range[0], time_range[1]) return events
e = self.__fetch_events([0])
e = self._fetch_events([0])
def get_codec(self): if not self.loaded: raise FileNotLoadedException e = self.__fetch_events([0]) if(len(e) == 0): return None raw_codec = e[0].value codec = {} for key in raw_codec.keys(): codec[key] = raw_codec[key]["tagname"] return codec
self.data.append([word, has_intersections, display])
self.data.append((word, has_intersections, display))
def display(self, strings, show_intersections): # unset and set model for speed store = self.tree.get_model() self.tree.set_model(None) self.data = [] colors = {True: '<span color="black">', False: '<span color="gray">'} for word, has_intersections in strings: display = "".join([colors[has_intersections], word, "</span>"]) self.data.append([word, has_intersections, display]) self._display_data(store, show_intersections) self.tree.set_model(store) self.tree.queue_draw()
self.puzzle.view.refresh_visual_size(self.drawing_area)
self.puzzle.view.grid = self.puzzle.grid self.puzzle.view.properties.grid = self.puzzle.grid width = self.puzzle.view.properties.visual_width() height = self.puzzle.view.properties.visual_height() self.drawing_area.set_size_request(width, height)
def refresh_visual_size(self): self.puzzle.view.refresh_visual_size(self.drawing_area)
if not grid.is_available(x, y + 1) or not grid.is_available(x, y):
if ltype == "top": bdx, bdy = 0, 1 elif ltype == "left": bdx, bdy = 1, 0 if not grid.is_available(x + bdx, y + bdy) or not grid.is_available(x, y):
def render(context, grid, props): lines = grid.get_lines(x, y) for p, q, ltype, side in lines: sx = props.grid_to_screen_x(p, False) sy = props.grid_to_screen_y(q, False) lwidth = props.line["width"] bwidth = props.border["width"] cellsize = props.cell["size"] bar = grid.is_valid(x, y) and grid.has_bar(x, y, ltype) border = "border" in side if side == "normal": context.set_line_width(lwidth) elif border: context.set_line_width(bwidth) if side == "normal": start = -0.5 * lwidth elif side == "outerborder": start = -0.5 * bwidth elif side == "innerborder": start = 0.5 * bwidth if not grid.is_available(x, y + 1) or not grid.is_available(x, y): start -= lwidth if ltype == "left": render_line(context, props, sx + start, sy, 0, cellsize, bar, border) elif ltype == "top": rx = sx ry = sy + start rdx = cellsize def get_delta(x, y, side_no_extend, side_extend): """ Determine the delta in pixels. The delta is at least the normal line width. """ if ((x, y, "left", side_no_extend) in lines or (x, y - 1, "left", side_no_extend) in lines): return False, props.line["width"] if ((x, y, "left", "normal") in lines or (x, y - 1, "left", "normal") in lines): return False, props.line["width"] if ((x, y, "left", side_extend) in lines or (x, y - 1, "left", side_extend) in lines): return True, 0 return False, 0 is_lb, dxl = get_delta(x, y, "innerborder", "outerborder") is_rb, dxr = get_delta(x + 1, y, "outerborder", "innerborder") # adjust horizontal lines to fill empty spaces in corners rx -= dxl rdx += dxl rdx += dxr render_line(context, props, rx, ry, rdx, 0, bar, border) if is_lb: rx -= bwidth render_line(context, props, rx, ry, bwidth, 0, False, True) if is_rb: rx += (cellsize + dxl) render_line(context, props, rx, ry, bwidth, 0, False, True)
return int(dim)
return dim
def parse_grid_size(attr, name): try: dim = int(element.get(attr)) if dim < 3: msg = name + u" attribute of grid must be at least 3." raise PalabraParserError(msg) return int(dim) except TypeError, ValueError: msg = name + u" attribute of grid not or incorrectly specified." raise PalabraParserError(msg)
if not grid.is_available(x, y):
if not grid.is_available(x, y + 1):
def render(context, grid, props): context.set_line_width(props.line["width"]) lines = grid.lines_of_cell(x, y) for p, q, ltype, side in lines: sx = props.grid_to_screen_x(p, False) sy = props.grid_to_screen_y(q, False) bar = grid.is_valid(x, y) and grid.has_bar(x, y, ltype) border = "border" in side if ltype == "top": rx = sx if side == "normal": context.set_line_width(props.line["width"]) ry = sy - 0.5 * props.line["width"] rdx = props.cell["size"] elif border: context.set_line_width(props.border["width"]) if side == "outerborder": ry = sy - 0.5 * props.border["width"] elif side == "innerborder": ry = sy + 0.5 * props.border["width"] if not grid.is_available(x, y): ry -= props.line["width"] rdx = props.cell["size"] # adjust horizontal lines to fill empty spaces in corners dxl, dxr = get_adjustments(lines, props, x, y) rx -= dxl rdx += dxl rdx += dxr render_line(context, props, rx, ry, rdx, 0, bar, border) elif ltype == "left": if side == "normal": context.set_line_width(props.line["width"]) rx = sx - 0.5 * props.line["width"] rdy = props.cell["size"] elif border: context.set_line_width(props.border["width"]) if side == "outerborder": rx = sx - 0.5 * props.border["width"] elif side == "innerborder": rx = sx + 0.5 * props.border["width"] if not grid.is_available(x, y): rx -= props.line["width"] rdy = props.cell["size"] render_line(context, props, rx, sy, 0, rdy, bar, border)
if not grid.is_available(x, y):
if not grid.is_available(x + 1, y):
def render(context, grid, props): context.set_line_width(props.line["width"]) lines = grid.lines_of_cell(x, y) for p, q, ltype, side in lines: sx = props.grid_to_screen_x(p, False) sy = props.grid_to_screen_y(q, False) bar = grid.is_valid(x, y) and grid.has_bar(x, y, ltype) border = "border" in side if ltype == "top": rx = sx if side == "normal": context.set_line_width(props.line["width"]) ry = sy - 0.5 * props.line["width"] rdx = props.cell["size"] elif border: context.set_line_width(props.border["width"]) if side == "outerborder": ry = sy - 0.5 * props.border["width"] elif side == "innerborder": ry = sy + 0.5 * props.border["width"] if not grid.is_available(x, y): ry -= props.line["width"] rdx = props.cell["size"] # adjust horizontal lines to fill empty spaces in corners dxl, dxr = get_adjustments(lines, props, x, y) rx -= dxl rdx += dxl rdx += dxr render_line(context, props, rx, ry, rdx, 0, bar, border) elif ltype == "left": if side == "normal": context.set_line_width(props.line["width"]) rx = sx - 0.5 * props.line["width"] rdy = props.cell["size"] elif border: context.set_line_width(props.border["width"]) if side == "outerborder": rx = sx - 0.5 * props.border["width"] elif side == "innerborder": rx = sx + 0.5 * props.border["width"] if not grid.is_available(x, y): rx -= props.line["width"] rdy = props.cell["size"] render_line(context, props, rx, sy, 0, rdy, bar, border)
modify_chars.__setattr__('type', constants.TRANSFORM_CONTENT)
modify_chars.__setattr__('type', constants.TRANSFORM_STRUCTURE)
def modify_chars(puzzle, chars): modify_chars.__setattr__('type', constants.TRANSFORM_CONTENT) """Modify the characters at the given locations.""" for x, y, c in chars: puzzle.grid.set_char(x, y, c)
for i, (j, grid) in enumerate(contents.items()):
for i, (j, grid) in enumerate(contents.items(), start=1):
def write_pattern_file(filename, metadata, contents): root = etree.Element("palabra") root.set("version", constants.VERSION) container = etree.SubElement(root, "container") container.set("content", "grid") _write_metadata(container, metadata) for i, (j, grid) in enumerate(contents.items()): _write_grid(container, grid, str(i)) contents = etree.tostring(root, xml_declaration=True, encoding="UTF-8") f = open(filename, "w") f.write(contents) f.close()
self.palabra_window.editor.refresh_words(True)
try: self.palabra_window.editor.refresh_words(True) except AttributeError: pass
def remove_word_list(self): store, it = self.tree.get_selection().get_selected() name = self.store.get_value(it, 0) nextprefs = [p for p in preferences.prefs["word_files"] if p["name"]["value"] != name] preferences.prefs["word_files"] = nextprefs self.palabra_window.wordlists = create_wordlists(preferences.prefs["word_files"]) self.palabra_window.editor.refresh_words(True) self._load_wordlists()
if self.grid.word_length(x, y, d) == 2:def render_all_lines_of_cell(self, context, x, y): self.render_lines_of_cell(context, x, y) for p, q in [(x + 1, y), (x, y + 1), (x + 1, y + 1)]: if self.grid.is_valid(p, q): self.render_lines_of_cell(context, p, q)
if self.grid.word_length(x, y, d) == 2:
if self.grid.word_length(x, y, d) == 2:def render_all_lines_of_cell(self, context, x, y):
self.store.clear() for d in ["across", "down"]: for row in puzzle.grid.gather_words(d): self.store.append(process_row(d, row))
def locked(): self.store.clear() for d in ["across", "down"]: for row in puzzle.grid.gather_words(d): self.store.append(process_row(d, row)) selection = self.tree.get_selection() self.perform_while_locked(selection, locked)
def process_row(direction, row): n = row[0] x = row[1] y = row[2] word = row[3] clue = row[4] explanation = row[5] display = self.create_display_string(n, direction, word, clue) return (n, x, y, direction, word, clue, explanation, display)
avg_score = float(score) / status["char_count"]
try: avg_score = float(score) / status["char_count"] except ZeroDivisionError: avg_score = 0
def create_statistic(table, title, value, x, y): label = gtk.Label(title) label.set_alignment(0, 0) table.attach(label, x, x + 1, y, y + 1) label = gtk.Label(value) label.set_alignment(1, 0) table.attach(label, x + 1, x + 2, y, y + 1)
except PalabraParserError, e:
except ParserError, e:
def show_error(title, message): mdialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL , gtk.MESSAGE_INFO, gtk.BUTTONS_NONE, message) mdialog.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) mdialog.set_title(title) mdialog.run() mdialog.destroy()
self.copy_pattern_button.connect("clicked", self.on_copy_pattern)
self.copy_pattern_button.connect("clicked", self.on_copy_patterns)
def __init__(self, palabra_window): gtk.Dialog.__init__(self, u"Pattern file manager" , palabra_window, gtk.DIALOG_MODAL) self.palabra_window = palabra_window self.set_size_request(640, 512) self.preview = GridPreview() self.preview.set_size_request(200, 256) self.patterns = {} # display_string filename id_of_grid self.store = gtk.TreeStore(str, str, str) self.reset_pattern_list() self.tree = gtk.TreeView(self.store) self.tree.set_headers_visible(False) self.tree.get_selection().set_mode(gtk.SELECTION_MULTIPLE) self.tree.get_selection().connect("changed", self.on_selection_changed) cell = gtk.CellRendererText() column = gtk.TreeViewColumn() column.pack_start(cell, True) column.set_attributes(cell, text=0) self.tree.append_column(column) right_vbox = gtk.VBox(False, 6) label = gtk.Label() label.set_markup(u"<b>Options for pattern files</b>") align = gtk.Alignment(0, 0.5) align.add(label) right_vbox.pack_start(align, False, False, 0) add_button = gtk.Button(stock=gtk.STOCK_ADD) add_button.connect("clicked", lambda button: self.add_file()) align = add_button.get_children()[0] hbox = align.get_children()[0] image, label = hbox.get_children() label.set_text(u"Add pattern file"); right_vbox.pack_start(add_button, False, False, 0) self.remove_button = gtk.Button(stock=gtk.STOCK_REMOVE) self.remove_button.connect("clicked", lambda button: self.remove_file()) self.remove_button.set_sensitive(False) align = self.remove_button.get_children()[0] hbox = align.get_children()[0] image, label = hbox.get_children() label.set_text(u"Remove pattern file(s)"); right_vbox.pack_start(self.remove_button, False, False, 0)
self.move_pattern_button.connect("clicked", self.on_move_pattern)
self.move_pattern_button.connect("clicked", self.on_move_patterns)
def __init__(self, palabra_window): gtk.Dialog.__init__(self, u"Pattern file manager" , palabra_window, gtk.DIALOG_MODAL) self.palabra_window = palabra_window self.set_size_request(640, 512) self.preview = GridPreview() self.preview.set_size_request(200, 256) self.patterns = {} # display_string filename id_of_grid self.store = gtk.TreeStore(str, str, str) self.reset_pattern_list() self.tree = gtk.TreeView(self.store) self.tree.set_headers_visible(False) self.tree.get_selection().set_mode(gtk.SELECTION_MULTIPLE) self.tree.get_selection().connect("changed", self.on_selection_changed) cell = gtk.CellRendererText() column = gtk.TreeViewColumn() column.pack_start(cell, True) column.set_attributes(cell, text=0) self.tree.append_column(column) right_vbox = gtk.VBox(False, 6) label = gtk.Label() label.set_markup(u"<b>Options for pattern files</b>") align = gtk.Alignment(0, 0.5) align.add(label) right_vbox.pack_start(align, False, False, 0) add_button = gtk.Button(stock=gtk.STOCK_ADD) add_button.connect("clicked", lambda button: self.add_file()) align = add_button.get_children()[0] hbox = align.get_children()[0] image, label = hbox.get_children() label.set_text(u"Add pattern file"); right_vbox.pack_start(add_button, False, False, 0) self.remove_button = gtk.Button(stock=gtk.STOCK_REMOVE) self.remove_button.connect("clicked", lambda button: self.remove_file()) self.remove_button.set_sensitive(False) align = self.remove_button.get_children()[0] hbox = align.get_children()[0] image, label = hbox.get_children() label.set_text(u"Remove pattern file(s)"); right_vbox.pack_start(self.remove_button, False, False, 0)
def on_copy_pattern(self, button):
def on_copy_patterns(self, button):
def on_copy_pattern(self, button): """Copy the currently selected patterns to a specified file.""" patterns = self._gather_selected_patterns() path = self._get_pattern_file() self.append_to_file(path, patterns)
self.append_to_file(path, patterns) def on_move_pattern(self, button):
if path: self.append_to_file(path, patterns) def on_move_patterns(self, button):
def on_copy_pattern(self, button): """Copy the currently selected patterns to a specified file.""" patterns = self._gather_selected_patterns() path = self._get_pattern_file() self.append_to_file(path, patterns)
self.append_to_file(path, patterns) self.remove_from_files(patterns)
if path: self.append_to_file(path, patterns) self.remove_from_files(patterns)
def on_move_pattern(self, button): """Move the currently selected patterns to a specified file.""" patterns = self._gather_selected_patterns() path = self._get_pattern_file() self.append_to_file(path, patterns) self.remove_from_files(patterns)
for word in self.lengths[length]: if self._predicate(constraints, word): if more_constraints is not None: filled_constraints = [(l, cs + [(i, word[j])]) for j, (i, l, cs) in enumerate(more_constraints)] for args in filled_constraints: if not self.has_matches(*args): yield word, False break
if length in self.lengths.keys(): for word in self.lengths[length]: if self._predicate(constraints, word): if more_constraints is not None: filled_constraints = [(l, cs + [(i, word[j])]) for j, (i, l, cs) in enumerate(more_constraints)] for args in filled_constraints: if not self.has_matches(*args): yield word, False break else: yield word, True
def search(self, length, constraints, more_constraints=None): for word in self.lengths[length]: if self._predicate(constraints, word): if more_constraints is not None: filled_constraints = [(l, cs + [(i, word[j])]) for j, (i, l, cs) in enumerate(more_constraints)] for args in filled_constraints: if not self.has_matches(*args): yield word, False break else: yield word, True else: yield word, True
else: yield word, True
def search(self, length, constraints, more_constraints=None): for word in self.lengths[length]: if self._predicate(constraints, word): if more_constraints is not None: filled_constraints = [(l, cs + [(i, word[j])]) for j, (i, l, cs) in enumerate(more_constraints)] for args in filled_constraints: if not self.has_matches(*args): yield word, False break else: yield word, True else: yield word, True
patterns = self._gather_selected_patterns() self.remove_from_files(patterns)
def on_remove_patterns(self, button): """Remove the currently selected patterns from their respective files.""" image = gtk.Image() image.set_from_stock(gtk.STOCK_DIALOG_WARNING, gtk.ICON_SIZE_DIALOG) dialog = gtk.Dialog(u"Remove patterns" , self , gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_MODAL , (gtk.STOCK_NO, gtk.RESPONSE_NO , gtk.STOCK_YES, gtk.RESPONSE_YES)) dialog.set_default_response(gtk.RESPONSE_CLOSE) dialog.set_title(u"Remove patterns")
def __init__(self, palabra_window, size=None):
def __init__(self, parent, size=None):
def __init__(self, palabra_window, size=None): gtk.Dialog.__init__(self, u"Pattern editor" , palabra_window, gtk.DIALOG_MODAL) self.palabra_window = palabra_window self.set_size_request(512, 384) self.size = size if size else (15, 15) all_vbox = gtk.VBox(False, 0) controls = gtk.HBox(False, 0) self.tile_starts = [(p, q) for p in xrange(2) for q in xrange(2)] tile_combo = gtk.combo_box_new_text() for x, y in self.tile_starts: content = str(''.join(["(", str(x + 1), ",", str(y + 1), ")" ])) tile_combo.append_text(content) tile_combo.connect("changed", self.on_tile_changed) controls.pack_start(gtk.Label(u"Tile from: "), False, False, 0) controls.pack_start(tile_combo, False, False, 0) all_vbox.pack_start(controls, False, False, 0) controls = gtk.HBox(False, 0) controls.pack_start(gtk.Label(u"Fill with: "), False, False, 0) fill_combo = gtk.combo_box_new_text() fill_combo.append_text(u"Block") fill_combo.append_text(u"Void") fill_combo.connect("changed", self.on_fill_changed) controls.pack_start(fill_combo, False, False, 0) all_vbox.pack_start(controls, False, False, 0) self.preview = GridPreview() self.preview.set_size_request(256, -1) self.display_pattern(None) hbox = gtk.HBox(False, 0) hbox.set_border_width(12) hbox.set_spacing(18) hbox.pack_start(all_vbox, True, True, 0) hbox.pack_start(self.preview, False, False, 0) self.vbox.pack_start(hbox, True, True, 0) self.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL) self.add_button(gtk.STOCK_OK, gtk.RESPONSE_OK)
, palabra_window, gtk.DIALOG_MODAL) self.palabra_window = palabra_window
, parent, gtk.DIALOG_MODAL)
def __init__(self, palabra_window, size=None): gtk.Dialog.__init__(self, u"Pattern editor" , palabra_window, gtk.DIALOG_MODAL) self.palabra_window = palabra_window self.set_size_request(512, 384) self.size = size if size else (15, 15) all_vbox = gtk.VBox(False, 0) controls = gtk.HBox(False, 0) self.tile_starts = [(p, q) for p in xrange(2) for q in xrange(2)] tile_combo = gtk.combo_box_new_text() for x, y in self.tile_starts: content = str(''.join(["(", str(x + 1), ",", str(y + 1), ")" ])) tile_combo.append_text(content) tile_combo.connect("changed", self.on_tile_changed) controls.pack_start(gtk.Label(u"Tile from: "), False, False, 0) controls.pack_start(tile_combo, False, False, 0) all_vbox.pack_start(controls, False, False, 0) controls = gtk.HBox(False, 0) controls.pack_start(gtk.Label(u"Fill with: "), False, False, 0) fill_combo = gtk.combo_box_new_text() fill_combo.append_text(u"Block") fill_combo.append_text(u"Void") fill_combo.connect("changed", self.on_fill_changed) controls.pack_start(fill_combo, False, False, 0) all_vbox.pack_start(controls, False, False, 0) self.preview = GridPreview() self.preview.set_size_request(256, -1) self.display_pattern(None) hbox = gtk.HBox(False, 0) hbox.set_border_width(12) hbox.set_spacing(18) hbox.pack_start(all_vbox, True, True, 0) hbox.pack_start(self.preview, False, False, 0) self.vbox.pack_start(hbox, True, True, 0) self.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL) self.add_button(gtk.STOCK_OK, gtk.RESPONSE_OK)
c = clue if len(clue) > 0 else "<span foreground=\"red\">No clue yet.</span>"
c = gobject.markup_escape_text(clue) if len(clue) > 0 else "<span foreground=\"red\">No clue yet.</span>"
def create_display_string(self, n, direction, word, clue): """Construct the displayed string for a word/clue item.""" c = clue if len(clue) > 0 else "<span foreground=\"red\">No clue yet.</span>" d = {"across": "Across", "down": "Down"}[direction] return ''.join(["<b>", d, ", ", str(n), "</b>:\n<i>", word, "</i>\n", c])
if not grid.is_available(x, y + 1):
if not grid.is_available(x, y + 1) or not grid.is_available(x, y):
def render(context, grid, props): context.set_line_width(props.line["width"]) lines = grid.lines_of_cell(x, y) for p, q, ltype, side in lines: sx = props.grid_to_screen_x(p, False) sy = props.grid_to_screen_y(q, False) bar = grid.is_valid(x, y) and grid.has_bar(x, y, ltype) border = "border" in side if ltype == "top": rx = sx if side == "normal": context.set_line_width(props.line["width"]) ry = sy - 0.5 * props.line["width"] rdx = props.cell["size"] elif border: context.set_line_width(props.border["width"]) if side == "outerborder": ry = sy - 0.5 * props.border["width"] elif side == "innerborder": ry = sy + 0.5 * props.border["width"] if not grid.is_available(x, y + 1): ry -= props.line["width"] rdx = props.cell["size"] # adjust horizontal lines to fill empty spaces in corners dxl, dxr, is_lb, is_rb = get_adjustments(lines, props, x, y) rx -= dxl rdx += dxl rdx += dxr render_line(context, props, rx, ry, rdx, 0, bar, border) if is_lb: rx -= props.border["width"] rdx = props.border["width"] render_line(context, props, rx, ry, rdx, 0, False, True) if is_rb: rx += (props.cell["size"] + dxl) rdx = props.border["width"] render_line(context, props, rx, ry, rdx, 0, False, True) elif ltype == "left": if side == "normal": context.set_line_width(props.line["width"]) rx = sx - 0.5 * props.line["width"] rdy = props.cell["size"] elif border: context.set_line_width(props.border["width"]) if side == "outerborder": rx = sx - 0.5 * props.border["width"] elif side == "innerborder": rx = sx + 0.5 * props.border["width"] if not grid.is_available(x + 1, y): rx -= props.line["width"] rdy = props.cell["size"] render_line(context, props, rx, sy, 0, rdy, bar, border)
if not grid.is_available(x + 1, y):
if not grid.is_available(x + 1, y) or not grid.is_available(x, y):
def render(context, grid, props): context.set_line_width(props.line["width"]) lines = grid.lines_of_cell(x, y) for p, q, ltype, side in lines: sx = props.grid_to_screen_x(p, False) sy = props.grid_to_screen_y(q, False) bar = grid.is_valid(x, y) and grid.has_bar(x, y, ltype) border = "border" in side if ltype == "top": rx = sx if side == "normal": context.set_line_width(props.line["width"]) ry = sy - 0.5 * props.line["width"] rdx = props.cell["size"] elif border: context.set_line_width(props.border["width"]) if side == "outerborder": ry = sy - 0.5 * props.border["width"] elif side == "innerborder": ry = sy + 0.5 * props.border["width"] if not grid.is_available(x, y + 1): ry -= props.line["width"] rdx = props.cell["size"] # adjust horizontal lines to fill empty spaces in corners dxl, dxr, is_lb, is_rb = get_adjustments(lines, props, x, y) rx -= dxl rdx += dxl rdx += dxr render_line(context, props, rx, ry, rdx, 0, bar, border) if is_lb: rx -= props.border["width"] rdx = props.border["width"] render_line(context, props, rx, ry, rdx, 0, False, True) if is_rb: rx += (props.cell["size"] + dxl) rdx = props.border["width"] render_line(context, props, rx, ry, rdx, 0, False, True) elif ltype == "left": if side == "normal": context.set_line_width(props.line["width"]) rx = sx - 0.5 * props.line["width"] rdy = props.cell["size"] elif border: context.set_line_width(props.border["width"]) if side == "outerborder": rx = sx - 0.5 * props.border["width"] elif side == "innerborder": rx = sx + 0.5 * props.border["width"] if not grid.is_available(x + 1, y): rx -= props.line["width"] rdy = props.cell["size"] render_line(context, props, rx, sy, 0, rdy, bar, border)
g, meta, data = read_pattern_file(path)
def add_file(self): dialog = gtk.FileChooserDialog(u"Add pattern file" , self , gtk.FILE_CHOOSER_ACTION_OPEN , (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL , gtk.STOCK_OPEN, gtk.RESPONSE_OK)) filter = gtk.FileFilter() filter.set_name(u"Palabra pattern files (*.xml)") filter.add_pattern("*.xml") dialog.add_filter(filter) dialog.show_all() response = dialog.run() path = dialog.get_filename() dialog.destroy() if response == gtk.RESPONSE_OK: for g, pattern in self.patterns.items(): if g == path: mdialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL , gtk.MESSAGE_INFO, gtk.BUTTONS_NONE, u"This file is already in the list.") mdialog.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) mdialog.set_title("Duplicate file") mdialog.run() mdialog.destroy() break else: try: preferences.prefs["pattern_files"].append(path) g, meta, data = read_pattern_file(path) self.patterns[path] = {"metadata": meta, "data": data} self._append_file(path, self.patterns[path]) self.tree.columns_autosize() except InvalidFileError: # TODO pass
return props.line["width"]
return False, props.line["width"]
def get_delta(x, y, side_no_extend, side_extend): """ Determine the delta in pixels. The delta is at least the normal line width. """ if ((x, y, "left", side_no_extend) in lines or (x, y - 1, "left", side_no_extend) in lines): return props.line["width"] elems = [(x, y, "left", "normal"), (x, y - 1, "left", "normal")] if True in map(lambda e: e in lines, elems): return props.line["width"] elems = [(x, y, "left", side_extend), (x, y - 1, "left", side_extend)] if True in map(lambda e: e in lines, elems): return props.border["width"] return 0
if True in map(lambda e: e in lines, elems): return props.line["width"]
if True in [e in lines for e in elems]: return False, props.line["width"]
def get_delta(x, y, side_no_extend, side_extend): """ Determine the delta in pixels. The delta is at least the normal line width. """ if ((x, y, "left", side_no_extend) in lines or (x, y - 1, "left", side_no_extend) in lines): return props.line["width"] elems = [(x, y, "left", "normal"), (x, y - 1, "left", "normal")] if True in map(lambda e: e in lines, elems): return props.line["width"] elems = [(x, y, "left", side_extend), (x, y - 1, "left", side_extend)] if True in map(lambda e: e in lines, elems): return props.border["width"] return 0
if True in map(lambda e: e in lines, elems): return props.border["width"] return 0 dx_left = get_delta(x, y, "innerborder", "outerborder") dx_right = get_delta(x + 1, y, "outerborder", "innerborder") return (dx_left, dx_right)
if True in [e in lines for e in elems]: return True, 0 return False, 0 is_left_border, dx_left = get_delta(x, y, "innerborder", "outerborder") is_right_border, dx_right = get_delta(x + 1, y, "outerborder", "innerborder") return (dx_left, dx_right, is_left_border, is_right_border)
def get_delta(x, y, side_no_extend, side_extend): """ Determine the delta in pixels. The delta is at least the normal line width. """ if ((x, y, "left", side_no_extend) in lines or (x, y - 1, "left", side_no_extend) in lines): return props.line["width"] elems = [(x, y, "left", "normal"), (x, y - 1, "left", "normal")] if True in map(lambda e: e in lines, elems): return props.line["width"] elems = [(x, y, "left", side_extend), (x, y - 1, "left", side_extend)] if True in map(lambda e: e in lines, elems): return props.border["width"] return 0
dxl, dxr = get_adjustments(lines, props, x, y)
dxl, dxr, is_lb, is_rb = get_adjustments(lines, props, x, y)
def render(context, grid, props): context.set_line_width(props.line["width"]) lines = grid.lines_of_cell(x, y) for p, q, ltype, side in lines: sx = props.grid_to_screen_x(p, False) sy = props.grid_to_screen_y(q, False) bar = grid.is_valid(x, y) and grid.has_bar(x, y, ltype) border = "border" in side if ltype == "top": rx = sx if side == "normal": context.set_line_width(props.line["width"]) ry = sy - 0.5 * props.line["width"] rdx = props.cell["size"] elif border: context.set_line_width(props.border["width"]) if side == "outerborder": ry = sy - 0.5 * props.border["width"] elif side == "innerborder": ry = sy + 0.5 * props.border["width"] if not grid.is_available(x, y + 1): ry -= props.line["width"] rdx = props.cell["size"] # adjust horizontal lines to fill empty spaces in corners dxl, dxr = get_adjustments(lines, props, x, y) rx -= dxl rdx += dxl rdx += dxr render_line(context, props, rx, ry, rdx, 0, bar, border) elif ltype == "left": if side == "normal": context.set_line_width(props.line["width"]) rx = sx - 0.5 * props.line["width"] rdy = props.cell["size"] elif border: context.set_line_width(props.border["width"]) if side == "outerborder": rx = sx - 0.5 * props.border["width"] elif side == "innerborder": rx = sx + 0.5 * props.border["width"] if not grid.is_available(x + 1, y): rx -= props.line["width"] rdy = props.cell["size"] render_line(context, props, rx, sy, 0, rdy, bar, border)
if node[0] == self.view_length:
if self.view_length == 0: return None if node[0] == self.view_length - 1:
def on_iter_next(self, node): if node[0] == self.view_length: return None return (node[0] + 1,)
p = self.in_direction(x, y, direction)
dx = 1 if direction == "across" else 0 dy = 1 if direction == "down" else 0 p = self.in_direction(x + dx, y + dy, direction)
def slot(self, x, y, direction): """Iterate over all cells of a slot that contains (x, y) in an unspecified order.""" p = self.in_direction(x, y, direction) q = self.in_direction(x, y, direction, reverse=True) for r, s in chain(p, q): yield r, s
main.set("Version", "1.0")
def write_xpf(puzzle, backup=True): root = etree.Element("Puzzles") main = etree.SubElement(root, "Puzzle") main.set("Version", "1.0") elems = [("type", "Type") , ("title", "Title") , ("creator", "Author") , ("contributor", "Editor") , ("publisher", "Publisher") , ("date", "Date")] for dc, e in elems: if dc in puzzle.metadata and puzzle.metadata[dc]: child = etree.SubElement(main, e) child.text = puzzle.metadata[dc] size = etree.SubElement(main, "Size") rows = etree.SubElement(size, "Rows") rows.text = str(puzzle.grid.height) cols = etree.SubElement(size, "Cols") cols.text = str(puzzle.grid.width) def calc_char(x, y): cell = puzzle.grid.cell(x, y) if cell["block"]: return '.' c = cell["char"] return c if c else ' ' egrid = etree.SubElement(main, "Grid") for y in xrange(puzzle.grid.height): erow = etree.SubElement(egrid, "Row") chars = [calc_char(x, y) for x in xrange(puzzle.grid.width)] erow.text = ''.join(chars) default = puzzle.view.properties.default styles = puzzle.view.properties.styles circles = [cell for cell in styles if styles[cell].circle != default.circle] if circles: circles.sort(key=itemgetter(0, 1)) ecircles = etree.SubElement(main, "Circles") for x, y in circles: ecircle = etree.SubElement(ecircles, "Circle") ecircle.set("Row", str(y + 1)) ecircle.set("Col", str(x + 1)) shades = [cell for cell in styles if styles[cell].cell["color"] != default.cell["color"]] if shades: shades.sort(key=itemgetter(0, 1)) eshades = etree.SubElement(main, "Shades") for x, y in shades: eshade = etree.SubElement(eshades, "Shade") eshade.set("Row", str(y + 1)) eshade.set("Col", str(x + 1)) def to_hex(value): hv = hex(int(value / 65535.0 * 255))[2:] return hv if len(hv) == 2 else '0' + hv text = '#' + ''.join([to_hex(v) for v in styles[x, y].cell["color"]]) eshade.text = text clues = etree.SubElement(main, "Clues") for n, x, y, d, word, clue, explanation in puzzle.grid.gather_words(): eclue = etree.SubElement(clues, "Clue") eclue.set("Row", str(y + 1)) eclue.set("Col", str(x + 1)) eclue.set("Num", str(n)) eclue.set("Dir", {"across": "Across", "down": "Down"}[d]) eclue.set("Ans", word) if clue: eclue.text = clue contents = etree.tostring(root, xml_declaration=True, encoding="UTF-8") _write_puzzle(puzzle.filename, contents, backup)
r_grid.set_char(x + i, y, c)
r_grid.set_char(x + i, y, c if c != ' ' else '')
def read_xpf(filename): # TODO check validity coordinates results = [] try: doc = etree.parse(filename) except etree.XMLSyntaxError: raise XPFParserError(u"No valid XML syntax.") puzzles = doc.getroot() if puzzles.tag != "Puzzles": raise XPFParserError(u"No root element called Puzzles found.") for puzzle in puzzles: if puzzle.tag != "Puzzle": print "Warning: skipping a child of Puzzles that is not a Puzzle." continue r_meta = {} r_width = None r_height = None r_grid = None r_notepad = "" r_styles = {} for child in puzzle: if child.tag == "Title": r_meta["title"] = child.text elif child.tag == "Author": r_meta["creator"] = child.text elif child.tag == "Editor": r_meta["contributor"] = child.text elif child.tag == "Copyright": r_meta["rights"] = child.text elif child.tag == "Publisher": r_meta["publisher"] = child.text elif child.tag == "Date": r_meta["date"] = child.text elif child.tag == "Size": for d in child: if d.tag == "Rows": r_height = int(d.text) elif d.tag == "Cols": r_width = int(d.text) elif child.tag == "Grid": if r_width is None: raise XPFParserError(u"The number of columns was not specified.") if r_height is None: raise XPFParserError(u"The number of rows was not specified.") assert r_width >= 0 assert r_height >= 0 r_grid = Grid(r_width, r_height) x, y = 0, 0 for row in child: if row.tag != "Row": print "Warning: skipping a child of Grid that is not a Row." continue content = row.text for i, c in enumerate(content): if c == '.': r_grid.set_block(x + i, y, True) else: r_grid.set_char(x + i, y, c) y += 1 elif child.tag == "Circles": for circle in child: if circle.tag != "Circle": print "Warning: skipping a child of Circles that is not a Circle." continue a_row = circle.get("Row") a_col = circle.get("Col") if a_row is None: print "Warning: skipping a child of Circles without a Row." continue if a_col is None: print "Warning: skipping a child of Circles without a Col." continue x = int(a_col) - 1 y = int(a_row) - 1 if (x, y) not in r_styles: r_styles[x, y] = CellStyle() r_styles[x, y].circle = True elif child.tag == "RebusEntries": pass # TODO elif child.tag == "Shades": for shade in child: if shade.tag != "Shade": print "Warning: skipping a child of Shades that is not a Shade." continue a_row = shade.get("Row") a_col = shade.get("Col") if a_row is None: print "Warning: skipping a child of Shades without a Row." continue if a_col is None: print "Warning: skipping a child of Shades without a Col." continue x = int(a_col) - 1 y = int(a_row) - 1 if shade.text: if (x, y) not in r_styles: r_styles[x, y] = CellStyle() if shade.text[0] == '#': colorhex = shade.text[1:] split = (colorhex[0:2], colorhex[2:4], colorhex[4:6]) rgb = [int((int(d, 16) / 255.0) * 65535) for d in split] r_styles[x, y].cell["color"] = tuple(rgb) else: print "TODO", shade.text else: print "Warning: Skipping a child of Shades with no content." continue elif child.tag == "Clues": for clue in child: if clue.tag != "Clue": print "Warning: skipping a child of Clues that is not a Clue." continue a_row = clue.get("Row") a_col = clue.get("Col") a_num = clue.get("Num") a_dir = clue.get("Dir") a_ans = clue.get("Ans") if a_row is not None and a_col is not None and a_dir is not None: x = int(a_col) - 1 y = int(a_row) - 1 if a_dir == "Across": direction = "across" elif a_dir == "Down": direction = "down" else: print "Warning: skipping a clue with a direction that is not across or down." continue r_grid.store_clue(x, y, direction, "text", clue.text) elif child.tag == "Notepad": r_notepad = child.text # TODO modify when arbitrary number schemes are implemented r_grid.assign_numbers() p = Puzzle(r_grid, r_styles) p.metadata = r_meta p.type = constants.PUZZLE_XPF p.notepad = r_notepad results.append(p) return results
r_grid.store_clue(x, y, direction, "text", clue.text)
if clue.text: r_grid.store_clue(x, y, direction, "text", clue.text) else: print "Warning: skipping a clue that has no text." continue
def read_xpf(filename): # TODO check validity coordinates results = [] try: doc = etree.parse(filename) except etree.XMLSyntaxError: raise XPFParserError(u"No valid XML syntax.") puzzles = doc.getroot() if puzzles.tag != "Puzzles": raise XPFParserError(u"No root element called Puzzles found.") for puzzle in puzzles: if puzzle.tag != "Puzzle": print "Warning: skipping a child of Puzzles that is not a Puzzle." continue r_meta = {} r_width = None r_height = None r_grid = None r_notepad = "" r_styles = {} for child in puzzle: if child.tag == "Title": r_meta["title"] = child.text elif child.tag == "Author": r_meta["creator"] = child.text elif child.tag == "Editor": r_meta["contributor"] = child.text elif child.tag == "Copyright": r_meta["rights"] = child.text elif child.tag == "Publisher": r_meta["publisher"] = child.text elif child.tag == "Date": r_meta["date"] = child.text elif child.tag == "Size": for d in child: if d.tag == "Rows": r_height = int(d.text) elif d.tag == "Cols": r_width = int(d.text) elif child.tag == "Grid": if r_width is None: raise XPFParserError(u"The number of columns was not specified.") if r_height is None: raise XPFParserError(u"The number of rows was not specified.") assert r_width >= 0 assert r_height >= 0 r_grid = Grid(r_width, r_height) x, y = 0, 0 for row in child: if row.tag != "Row": print "Warning: skipping a child of Grid that is not a Row." continue content = row.text for i, c in enumerate(content): if c == '.': r_grid.set_block(x + i, y, True) else: r_grid.set_char(x + i, y, c) y += 1 elif child.tag == "Circles": for circle in child: if circle.tag != "Circle": print "Warning: skipping a child of Circles that is not a Circle." continue a_row = circle.get("Row") a_col = circle.get("Col") if a_row is None: print "Warning: skipping a child of Circles without a Row." continue if a_col is None: print "Warning: skipping a child of Circles without a Col." continue x = int(a_col) - 1 y = int(a_row) - 1 if (x, y) not in r_styles: r_styles[x, y] = CellStyle() r_styles[x, y].circle = True elif child.tag == "RebusEntries": pass # TODO elif child.tag == "Shades": for shade in child: if shade.tag != "Shade": print "Warning: skipping a child of Shades that is not a Shade." continue a_row = shade.get("Row") a_col = shade.get("Col") if a_row is None: print "Warning: skipping a child of Shades without a Row." continue if a_col is None: print "Warning: skipping a child of Shades without a Col." continue x = int(a_col) - 1 y = int(a_row) - 1 if shade.text: if (x, y) not in r_styles: r_styles[x, y] = CellStyle() if shade.text[0] == '#': colorhex = shade.text[1:] split = (colorhex[0:2], colorhex[2:4], colorhex[4:6]) rgb = [int((int(d, 16) / 255.0) * 65535) for d in split] r_styles[x, y].cell["color"] = tuple(rgb) else: print "TODO", shade.text else: print "Warning: Skipping a child of Shades with no content." continue elif child.tag == "Clues": for clue in child: if clue.tag != "Clue": print "Warning: skipping a child of Clues that is not a Clue." continue a_row = clue.get("Row") a_col = clue.get("Col") a_num = clue.get("Num") a_dir = clue.get("Dir") a_ans = clue.get("Ans") if a_row is not None and a_col is not None and a_dir is not None: x = int(a_col) - 1 y = int(a_row) - 1 if a_dir == "Across": direction = "across" elif a_dir == "Down": direction = "down" else: print "Warning: skipping a clue with a direction that is not across or down." continue r_grid.store_clue(x, y, direction, "text", clue.text) elif child.tag == "Notepad": r_notepad = child.text # TODO modify when arbitrary number schemes are implemented r_grid.assign_numbers() p = Puzzle(r_grid, r_styles) p.metadata = r_meta p.type = constants.PUZZLE_XPF p.notepad = r_notepad results.append(p) return results
cell = self._default_cell() self.data = [[copy.copy(cell) for x in xrange(width)] for y in xrange(height)]
self.data = [[self._default_cell() for x in xrange(width)] for y in xrange(height)]
def initialize(self, width, height): """Reset the grid to the given dimensions with all empty cells.""" self.width = width self.height = height self.lines = {} # code below is faster than calling _default_cell all the time cell = self._default_cell() self.data = [[copy.copy(cell) for x in xrange(width)] for y in xrange(height)] # TODO modify when arbitrary number schemes are implemented self.assign_numbers() #self.compute_lines()
_write_grid(root, grid)
_write_crossword(root, Puzzle(grid))
def write_patterns(filename, patterns): root = etree.Element("palabra") root.set("version", constants.VERSION) for grid in patterns: _write_grid(root, grid) contents = etree.tostring(root, xml_declaration=True, encoding="UTF-8") f = open(filename, "w") f.write(contents) f.close()
word = "".join(map(lambda c: c.lower(), segment))
word = "".join([c.lower() if c else " " for c in segment])
def check_segment(direction, segment, cells): result = [] word = "".join(map(lambda c: c.lower(), segment)) badwords = self.palabra_window.blacklist.get_substring_matches(word) for i in xrange(len(word)): for b in badwords: if word[i:i + len(b)] == b: p, q = cells[i] result.append((p, q, direction, len(b))) return result
self.add_word(node.children[c], word, offset + 1)
self._add_word(node.children[c], word, offset + 1)
def _add_word(self, node, word, offset): if offset >= len(word): node.words.append(word) return c = word[offset] if c not in node.children: node.children[c] = Node() self.add_word(node.children[c], word, offset + 1)
raise XPFParserError("uNo version specified for this XPF file. Possible older than v1.0?")
raise XPFParserError(u"No version specified for this XPF file. Possible older than v1.0?")
def read_xpf(filename): # TODO check validity coordinates results = [] try: doc = etree.parse(filename) except etree.XMLSyntaxError: raise XPFParserError(u"No valid XML syntax.") puzzles = doc.getroot() if puzzles.tag != "Puzzles": raise XPFParserError(u"No root element called Puzzles found.") version = puzzles.get("Version") if version is None: raise XPFParserError("uNo version specified for this XPF file. Possible older than v1.0?") try: version = float(version) except ValueError: raise XPFParserError("uXPF version is not a valid number") if version < 1.0: raise XPFParserError("uXPF versions older than 1.0 are not supported.") for puzzle in puzzles: if puzzle.tag != "Puzzle": print "Warning: skipping a child of Puzzles that is not a Puzzle." continue r_meta = {} r_width = None r_height = None r_grid = None r_notepad = "" r_styles = {} for child in puzzle: if child.tag == "Type": r_meta["type"] = child.text elif child.tag == "Title": r_meta["title"] = child.text elif child.tag == "Author": r_meta["creator"] = child.text elif child.tag == "Editor": r_meta["contributor"] = child.text elif child.tag == "Copyright": r_meta["rights"] = child.text elif child.tag == "Publisher": r_meta["publisher"] = child.text elif child.tag == "Date": r_meta["date"] = child.text elif child.tag == "Size": for d in child: if d.tag == "Rows": r_height = int(d.text) elif d.tag == "Cols": r_width = int(d.text) elif child.tag == "Grid": if r_width is None: raise XPFParserError(u"The number of columns was not specified.") if r_height is None: raise XPFParserError(u"The number of rows was not specified.") assert r_width >= 0 assert r_height >= 0 r_grid = Grid(r_width, r_height) x, y = 0, 0 for row in child: if row.tag != "Row": print "Warning: skipping a child of Grid that is not a Row." continue content = row.text for i, c in enumerate(content): if c == '.': r_grid.set_block(x + i, y, True) else: r_grid.set_char(x + i, y, c if c != ' ' else '') y += 1 elif child.tag == "Circles": for circle in child: if circle.tag != "Circle": print "Warning: skipping a child of Circles that is not a Circle." continue a_row = circle.get("Row") a_col = circle.get("Col") if a_row is None: print "Warning: skipping a child of Circles without a Row." continue if a_col is None: print "Warning: skipping a child of Circles without a Col." continue x = int(a_col) - 1 y = int(a_row) - 1 if (x, y) not in r_styles: r_styles[x, y] = CellStyle() r_styles[x, y].circle = True elif child.tag == "RebusEntries": for rebus in child: if rebus.tag != "Rebus": print "Warning: skipping a child of RebusEntries that is not a Rebus." continue a_row = rebus.get("Row") if a_row is None: print "Warning: skipping a child of RebusEntries without a Row." continue a_col = rebus.get("Col") if a_col is None: print "Warning: skipping a child of RebusEntries without a Col." continue a_short = rebus.get("Short") if a_short is None: print "Warning: skipping a child of RebusEntries without a Short." continue content = rebus.text if len(content) == 0: print "Warning: skipping a child of RebusEntries without content." continue x = int(a_col) - 1 y = int(a_row) - 1 print "TODO - rebus found:", x, y, a_short, content elif child.tag == "Shades": for shade in child: if shade.tag != "Shade": print "Warning: skipping a child of Shades that is not a Shade." continue a_row = shade.get("Row") a_col = shade.get("Col") if a_row is None: print "Warning: skipping a child of Shades without a Row." continue if a_col is None: print "Warning: skipping a child of Shades without a Col." continue x = int(a_col) - 1 y = int(a_row) - 1 if shade.text: if (x, y) not in r_styles: r_styles[x, y] = CellStyle() if shade.text == "gray": shade.text = "#808080" if shade.text[0] == '#': colorhex = shade.text[1:] split = (colorhex[0:2], colorhex[2:4], colorhex[4:6]) rgb = [int((int(d, 16) / 255.0) * 65535) for d in split] r_styles[x, y].cell["color"] = tuple(rgb) else: print "Warning: Skipping a child of Shades with no content." continue elif child.tag == "Clues": for clue in child: if clue.tag != "Clue": print "Warning: skipping a child of Clues that is not a Clue." continue a_row = clue.get("Row") a_col = clue.get("Col") a_num = clue.get("Num") a_dir = clue.get("Dir") a_ans = clue.get("Ans") if a_row is not None and a_col is not None and a_dir is not None: x = int(a_col) - 1 y = int(a_row) - 1 if a_dir == "Across": direction = "across" elif a_dir == "Down": direction = "down" else: print "Warning: skipping a clue with a direction that is not across or down." continue if clue.text: r_grid.store_clue(x, y, direction, "text", clue.text) elif child.tag == "Notepad": r_notepad = child.text # TODO modify when arbitrary number schemes are implemented r_grid.assign_numbers() p = Puzzle(r_grid, r_styles) p.metadata = r_meta p.type = constants.PUZZLE_XPF p.filename = filename p.notepad = r_notepad results.append(p) return results
max_id = int(max(data.keys())) + 1
try: max_id = int(max(data.keys())) + 1 except ValueError: max_id = 1
def append_to_file(self, path, patterns): """Append all patterns to the specified file.""" try: g, meta, data = read_pattern_file(path) except InvalidFileError: # TODO return max_id = int(max(data.keys())) + 1 for f, keys in patterns.items(): for k in keys: data[str(max_id)] = self.patterns[f]["data"][k] max_id += 1 write_pattern_file(g, meta, data)
data = [d for (f, _, d) in self.patterns if f in files] grids = reduce(operator.add, data) stats = [(g.count_words(), g.count_blocks(), g) for g in grids] stats.sort() self.current_patterns = [grid for (_, _, grid) in stats] self.load_empty_grid(*self.size_component.get_size())
if files: data = [d for (f, _, d) in self.patterns if f in files] grids = reduce(operator.add, data) stats = [(g.count_words(), g.count_blocks(), g) for g in grids] stats.sort() self.current_patterns = [grid for (_, _, grid) in stats] self.load_empty_grid(*self.size_component.get_size())
def on_file_changed(self, combo): index = combo.get_active() if index == 0: files = preferences.prefs["pattern_files"] else: files = preferences.prefs["pattern_files"][index - 1:index] data = [d for (f, _, d) in self.patterns if f in files] grids = reduce(operator.add, data) stats = [(g.count_words(), g.count_blocks(), g) for g in grids] stats.sort() self.current_patterns = [grid for (_, _, grid) in stats] self.load_empty_grid(*self.size_component.get_size())
if all([is_file(store, p) for p in paths]):
if paths and all([is_file(store, p) for p in paths]):
def is_file(store, path): return store.iter_parent(store.get_iter(path)) is None
self.set_full_selection(x, y, direction)
self._set_full_selection(x, y, direction)
def select(x, y, direction): """Select the word at (x, y, direction) in the grid.""" self.tools["clue"].settings["use_scrolling"] = False self.set_full_selection(x, y, direction) self.tools["clue"].settings["use_scrolling"] = True
self.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
def __init__(self, palabra_window): gtk.Dialog.__init__(self, u"Pattern file manager" , palabra_window, gtk.DIALOG_MODAL) self.palabra_window = palabra_window self.set_size_request(640, 640) self.preview = GridPreview() self.preview.set_size_request(200, 250) self.patterns = {} for f in preferences.prefs["pattern_files"]: g, meta, data = read_pattern_file(f) self.patterns[f] = {"metadata": meta, "data": data} # display_string filename id_of_grid self.store = gtk.TreeStore(str, str, str) for item in self.patterns.items(): self._append_file(*item) self.tree = gtk.TreeView(self.store) self.tree.get_selection().set_mode(gtk.SELECTION_MULTIPLE) self.tree.get_selection().connect("changed", self.on_selection_changed) cell = gtk.CellRendererText() column = gtk.TreeViewColumn(u"Pattern files") column.pack_start(cell, True) column.set_attributes(cell, text=0) self.tree.append_column(column) right_vbox = gtk.VBox(False, 6) label = gtk.Label() label.set_markup(u"<b>Pattern files</b>") align = gtk.Alignment(0, 0.5) align.add(label) right_vbox.pack_start(align, False, False, 0) add_button = gtk.Button(stock=gtk.STOCK_ADD) add_button.connect("clicked", lambda button: self.add_file()) align = add_button.get_children()[0] hbox = align.get_children()[0] image, label = hbox.get_children() label.set_text(u"Add pattern file"); right_vbox.pack_start(add_button, False, False, 0) self.remove_button = gtk.Button(stock=gtk.STOCK_REMOVE) self.remove_button.connect("clicked", lambda button: self.remove_file()) self.remove_button.set_sensitive(False) align = self.remove_button.get_children()[0] hbox = align.get_children()[0] image, label = hbox.get_children() label.set_text(u"Remove pattern file(s)"); right_vbox.pack_start(self.remove_button, False, False, 0)
path = dialog.get_filename()
def add_file(self): dialog = gtk.FileChooserDialog(u"Add pattern file" , self , gtk.FILE_CHOOSER_ACTION_OPEN , (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL , gtk.STOCK_OPEN, gtk.RESPONSE_OK)) dialog.show_all() response = dialog.run() if response == gtk.RESPONSE_OK: path = dialog.get_filename() for g, pattern in self.patterns.items(): if g == path: dialog.destroy() mdialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL , gtk.MESSAGE_INFO, gtk.BUTTONS_NONE, u"This file is already in the list.") mdialog.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) mdialog.set_title("Duplicate file") mdialog.run() mdialog.destroy() break else: dialog.destroy() preferences.prefs["pattern_files"].append(path) g, meta, data = read_pattern_file(path) self.patterns[path] = {"metadata": meta, "data": data} self._append_file(path, self.patterns[path]) self.tree.columns_autosize()
dialog.destroy()
def add_file(self): dialog = gtk.FileChooserDialog(u"Add pattern file" , self , gtk.FILE_CHOOSER_ACTION_OPEN , (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL , gtk.STOCK_OPEN, gtk.RESPONSE_OK)) dialog.show_all() response = dialog.run() if response == gtk.RESPONSE_OK: path = dialog.get_filename() for g, pattern in self.patterns.items(): if g == path: dialog.destroy() mdialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL , gtk.MESSAGE_INFO, gtk.BUTTONS_NONE, u"This file is already in the list.") mdialog.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) mdialog.set_title("Duplicate file") mdialog.run() mdialog.destroy() break else: dialog.destroy() preferences.prefs["pattern_files"].append(path) g, meta, data = read_pattern_file(path) self.patterns[path] = {"metadata": meta, "data": data} self._append_file(path, self.patterns[path]) self.tree.columns_autosize()
r, g, b = puzzle.view.properties.cell["color"] context.set_source_rgb(r / 65535.0, g / 65535.0, b / 65535.0) context.fill()
def export_to_png(puzzle, filename, output, settings): width = puzzle.view.properties.visual_width(False) height = puzzle.view.properties.visual_height(False) surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) context = cairo.Context(surface) context.rectangle(0, 0, width, height) r, g, b = puzzle.view.properties.cell["color"] context.set_source_rgb(r / 65535.0, g / 65535.0, b / 65535.0) context.fill() if output == "grid": puzzle.view.render(context, constants.VIEW_MODE_EMPTY) elif output == "solution": puzzle.view.render(context, constants.VIEW_MODE_SOLUTION) surface.write_to_png(filename) surface.finish()
if transform >= constants.TRANSFORM_STRUCTURE: self.editor.puzzle.grid.assign_numbers() if transform >= constants.TRANSFORM_CONTENT: self.editor.refresh_clues()
if content_changed: if transform >= constants.TRANSFORM_STRUCTURE: self.editor.puzzle.grid.assign_numbers() if transform >= constants.TRANSFORM_CONTENT: self.editor.refresh_clues()
def update_window(self, content_changed=False, transform=constants.TRANSFORM_STRUCTURE): puzzle = self.puzzle_manager.current_puzzle if puzzle is None: self.set_title(u"Palabra") self.pop_status(constants.STATUS_GRID) else: status = puzzle.grid.determine_status(False) message = self.determine_status_message(status) self.update_status(constants.STATUS_GRID, message) selection = self.get_selection() if selection is not None: sel_x, sel_y = selection valid = puzzle.grid.is_valid(sel_x, sel_y) for item, predicate in self.selection_toggle_items: item.set_sensitive(valid and predicate(puzzle)) if valid and not puzzle.grid.is_available(sel_x, sel_y): self.set_selection(-1, -1) for item in self.puzzle_toggle_items: item.set_sensitive(puzzle is not None) self.update_undo_redo() try: if transform >= constants.TRANSFORM_STRUCTURE: # TODO modify when arbitrary number schemes are implemented self.editor.puzzle.grid.assign_numbers() if transform >= constants.TRANSFORM_CONTENT: self.editor.refresh_clues() self.editor.force_redraw = True self.editor.refresh_words() self.editor.refresh_visual_size() except AttributeError: pass self.panel.queue_draw()
self.editor.settings["symmetries"] = options
try: self.editor.settings["symmetries"] = options except AttributeError: pass
def set_symmetry(options): self.editor.settings["symmetries"] = options
pasted_id = view.connect("paste-clipboard", self.on_paste) doc.set_data("AutoTabPluginHandlerIds", (loaded_id, saved_id, pasted_id))
doc.set_data("AutoTabPluginHandlerIds", (loaded_id, saved_id))
def connect_handlers(self, view): doc = view.get_buffer() # Using connect_after() because we want other plugins to do their # thing first. loaded_id = doc.connect_after("loaded", self.auto_tab, view) saved_id = doc.connect_after("saved", self.auto_tab, view) pasted_id = view.connect("paste-clipboard", self.on_paste) doc.set_data("AutoTabPluginHandlerIds", (loaded_id, saved_id, pasted_id))
loaded_id, saved_id, pasted_id = doc.get_data("AutoTabPluginHandlerIds")
loaded_id, saved_id = doc.get_data("AutoTabPluginHandlerIds")
def disconnect_handlers(self, view): doc = view.get_buffer() loaded_id, saved_id, pasted_id = doc.get_data("AutoTabPluginHandlerIds") doc.disconnect(loaded_id) doc.disconnect(saved_id) view.disconnect(pasted_id) doc.set_data("AutoTabPluginHandlerIds", None)
view.disconnect(pasted_id)
def disconnect_handlers(self, view): doc = view.get_buffer() loaded_id, saved_id, pasted_id = doc.get_data("AutoTabPluginHandlerIds") doc.disconnect(loaded_id) doc.disconnect(saved_id) view.disconnect(pasted_id) doc.set_data("AutoTabPluginHandlerIds", None)
for i in (2, 3, 4, 8): if last_indent + i == indent: last_indent_spaces = i indent_count[i] += 1; last_indent = indent break
indent_diff = abs(indent - last_indent) if indent_diff in (2, 3, 4, 8): last_indent_spaces = indent_diff indent_count[indent_diff] += 1; last_indent = indent
def auto_tab(self, doc, error, view): if error is not None: pass
client = gconf.client_get_default()
client = gconf.client_get_default() if client.__class__.__name__ == 'FakeGConfClient': client.set_defaults(window)
def activate(self, window): self.window = window self.spaces_instead_of_tabs = False self.tabs_width = 2 # Prime the statusbar self.statusbar = window.get_statusbar() self.context_id = self.statusbar.get_context_id("AutoTab") self.message_id = None
self.statusbar.remove(self.context_id, self.message_id)
self.statusbar.remove_message(self.context_id, self.message_id)
def deactivate(self, window): tab_added_id = window.get_data("AutoTabPluginHandlerId") window.disconnect(tab_added_id) window.set_data("AutoTabPluginHandlerId", None)
self.statusbar.remove(self.context_id, self.message_id)
self.statusbar.remove_message(self.context_id, self.message_id)
def update_status(self): view = self.window.get_active_view() if view: space = view.get_insert_spaces_instead_of_tabs() size = view.get_tab_width() if space: message = "%i Spaces" % size else: message = "Tabs" if self.message_id: self.statusbar.remove(self.context_id, self.message_id) self.message_id = self.statusbar.push(self.context_id, "Indentation: %s" % message)
for status in self.render_flow:
for status in self.render_flow(data):
def render(self, data): """render the OpenDocument with the user data
self.vpan.set_position(275)
tmp = 0 w, h = self.window.get_size() self.vpan.set_position(h) tmp = self.vpan.get_position() print tmp self.vpan.set_position(int((275.0/450)*h))
def tree_select_changed(self, widget=None, event=None): model, iter = self.selection.get_selected() value = model.get_value(iter,0) #print value if value not in list_groups(): self.vpan.set_position(275) else: self.vpan.set_position(10000) detail = get_details(value) buff = self.output_txtview.get_buffer() buff.set_text(detail) self.output_txtview.set_buffer(buff)
self.get_group.append_text(grp)
tmp = list_groups() n = len(tmp) print n print self.get_group.get_text_column() for i in range(0,n): self.get_group.remove_text(0) for x in tmp: self.get_group.append_text(x)
def refresh_groups(self, grp): self.get_group.append_text(grp)
gtk.main_quit()
self.dialog.destroy()
def on_window_destroy(self, widget=None, event=None): gtk.main_quit()
self.dialog.destroy()
self.dialog.hide()
def on_dialog_proceed_clicked(self, widget=None, event=None): self.no_of_ques = self.count_ self.dialog.destroy() self.set_up_mcq() self.builder.get_object('window3').show()
gtk.main_quit()
def on_dialog_destroy(self, widget=None, event=None): self.dialog.destroy() #gtk.main_quit()
self.tree_value = self.model.get_value(self.iter,0) if self.tree_value not in wordz_db.list_groups(): self.hbox3.show() w, h = self.window.get_size() self.vpan.set_position(h) tmp = self.vpan.get_position() self.vpan.set_position(int((255.0/450)*h)) else: self.vpan.set_position(10000) self.hbox3.hide() if self.output_txtview.get_editable(): self.output_txtview.set_editable(False) detail = wordz_db.get_details(self.tree_value) buff = self.output_txtview.get_buffer() buff.set_text(detail) self.output_txtview.set_buffer(buff)
if self.iter is not None: self.tree_value = self.model.get_value(self.iter,0) if self.tree_value not in wordz_db.list_groups(): self.hbox3.show() w, h = self.window.get_size() self.vpan.set_position(h) tmp = self.vpan.get_position() self.vpan.set_position(int((255.0/450)*h)) else: self.vpan.set_position(10000) self.hbox3.hide() if self.output_txtview.get_editable(): self.output_txtview.set_editable(False) detail = wordz_db.get_details(self.tree_value) buff = self.output_txtview.get_buffer() buff.set_text(detail) self.output_txtview.set_buffer(buff)
def tree_select_changed(self, widget=None, event=None): self.model, self.iter = self.selection.get_selected() self.tree_value = self.model.get_value(self.iter,0)
print s
def get_def(self, word): l = self.match(word, db='!', strat='exact') for db, word in l: defs = self.definition(word, db=db) if defs == []: print >> sys.stderr, 'no-match' return 2 db, dbdescr, defstr = defs[0] s = '\n\n\n'.join([defstr for _, _, defstr in defs]) print s return s
""" self.chose_dict_hbox = self.builder.get_object('hbox6')
self.chose_dict_hbox = self.builder.get_object('hbox7') vseparator = gtk.VSeparator() vseparator.show() self.chose_dict_hbox.pack_start(vseparator, False, padding=5) label = gtk.Label('Dictionary') label.show() self.chose_dict_hbox.pack_start(label, False)
def __init__(self): self.builder = gtk.Builder() self.builder.add_from_file("wordgroupz_new.glade") self.window = self.builder.get_object("MainWindow") self.window.set_icon_from_file("/usr/share/pixmaps/wordgroupz.png") self.window.set_title("wordGroupz") self.builder.connect_signals(self) self.get_word = self.builder.get_object("get_word") self.get_group = gtk.combo_box_entry_new_text() self.get_group.set_tooltip_text("Enter a group for your word") self.details = self.builder.get_object("textview1") self.get_group.child.connect('key-press-event',self.item_list_changed) #self.vpan = self.builder.get_object("vpaned1") self.output_txtview = self.builder.get_object("textview2") for x in wordz_db.list_groups(): self.get_group.append_text(x) self.table1 = self.builder.get_object("table1") self.get_group.show() self.table1.attach(self.get_group, 1,2,1,2)
self.chose_dict_hbox.pack_start(self.chose_dict, True, True, padding = 5) """
self.chose_dict_hbox.pack_start(self.chose_dict, False, True, padding = 5)
def __init__(self): self.builder = gtk.Builder() self.builder.add_from_file("wordgroupz_new.glade") self.window = self.builder.get_object("MainWindow") self.window.set_icon_from_file("/usr/share/pixmaps/wordgroupz.png") self.window.set_title("wordGroupz") self.builder.connect_signals(self) self.get_word = self.builder.get_object("get_word") self.get_group = gtk.combo_box_entry_new_text() self.get_group.set_tooltip_text("Enter a group for your word") self.details = self.builder.get_object("textview1") self.get_group.child.connect('key-press-event',self.item_list_changed) #self.vpan = self.builder.get_object("vpaned1") self.output_txtview = self.builder.get_object("textview2") for x in wordz_db.list_groups(): self.get_group.append_text(x) self.table1 = self.builder.get_object("table1") self.get_group.show() self.table1.attach(self.get_group, 1,2,1,2)
print filepath
def on_speak_clicked(self, widget=None, event=None): filepath = audio_file_path+'/'+self.tree_value+'.ogg' print filepath if os.path.isfile(filepath): self.player.set_property("uri", "file://" + filepath) self.player.set_state(gst.STATE_PLAYING) else: self.player.set_state(gst.STATE_NULL)
print self.audio_file
def look_for_audio(self): page = self.browser.get_html() #print page soup = BeautifulSoup('<html>'+str(page)+'</html>') div = soup.html.body.findAll('div', attrs={'id':'ogg_player_1'}) if div is None: print "No audio available" else: l = str(div).split(',') for i in l: if i.find('videoUrl')>0: self.download_url = i.split(': ')[1].strip('"') #print self.download_url self.wiki_word = str(soup.html.title).split(' ')[0].split('>')[1] self.save_audio.set_sensitive(True) self.audio_file = self.wiki_word+'.ogg' print self.audio_file
print 'page switched' print page_num
def on_notebook1_switch_page(self, notebook, page, page_num): print 'page switched' print page_num width, height = self.window.get_size() if page_num==1: self.window.resize(max(width, 800), max(height, 550)) print self.tree_value, self.wiki_word, self.browser_load_status if self.tree_value is self.wiki_word and self.browser_load_status is 'finished' or 'loading': pass else: self.url = 'http://en.wiktionary.org/wiki/' + self.tree_value self.browser.open(self.url) elif page_num == 0: self.window.resize(min(width, 700), min(height, 550))
print self.tree_value, self.wiki_word, self.browser_load_status
def on_notebook1_switch_page(self, notebook, page, page_num): print 'page switched' print page_num width, height = self.window.get_size() if page_num==1: self.window.resize(max(width, 800), max(height, 550)) print self.tree_value, self.wiki_word, self.browser_load_status if self.tree_value is self.wiki_word and self.browser_load_status is 'finished' or 'loading': pass else: self.url = 'http://en.wiktionary.org/wiki/' + self.tree_value self.browser.open(self.url) elif page_num == 0: self.window.resize(min(width, 700), min(height, 550))
print self.tree_value
def tree_select_changed(self, widget=None, event=None): self.model, self.iter = self.selection.get_selected() if self.iter is not None: if self.welcome is self.hbox2.get_children()[1]: self.hbox2.remove(self.welcome) self.hbox2.pack_start(self.vbox7) self.tree_value = self.model.get_value(self.iter,0) self.notebook1 = self.builder.get_object('notebook1') cur_page = self.notebook1.get_current_page() if cur_page is 1: self.url = ('http://en.wiktionary.org/wiki/'+self.tree_value) self.browser.open(self.url) #self.get_audio()
print dic
def on_get_details1_clicked(self, widget, data=None): word = self.tree_value dic = self.chose_dict.get_active_text() print dic if dic == 'online webster': d = online_dict() defs = d.get_def(word) defs = '\n' + '='*10 + '\n' + "\nfrom online webster:\n" + defs elif dic == 'offline wordnet': defs = '\n' + '='*10 + '\n' + wordnet.get_definition(word) buff = self.output_txtview.get_buffer() end = buff.get_iter_at_offset(-1) buff.place_cursor(end) buff.insert_interactive_at_cursor(defs, True)
if not 'groups' in tables: c.execute('''create table groups (grp text)''')
def db_init(self): if not os.path.exists(wordgroupz_dir): os.mkdir(wordgroupz_dir, 0755) conn = sqlite3.connect(db_file_path) c = conn.cursor() tables = [] for x in c.execute('''select name from sqlite_master'''): tables.append(x[0]) if not 'word_groups' in tables: c.execute('''create table word_groups (word text, grp text, details text)''') #if not 'groups' in tables: # c.execute('''create table groups # (grp text)''') conn.commit() c.close() conn.close()
def delete_group(self, tree_value): conn = sqlite3.connect(db_file_path) c = conn.cursor() t = (tree_value,) c.execute("""delete from groups where grp=?""",t) conn.commit() c.close()
def list_groups(self): conn = sqlite3.connect(db_file_path) c = conn.cursor() groups = [] for row in c.execute("""select grp from groups order by grp"""): if row[0] is not u'': groups.append(row[0]) c.close() return groups
self.audio_file = str(soup.html.title).split(' ')[0].strip('<title>')+'.ogg'
self.audio_file = str(soup.html.title).split(' ')[0].split('>')[1]+'.ogg' print self.audio_file
def look_for_audio(self): page = self.browser.get_html() #print page soup = BeautifulSoup('<html>'+str(page)+'</html>') div = soup.html.body.findAll('div', attrs={'id':'ogg_player_1'}) if div is None: print "No audio available" else: l = str(div).split(',') for i in l: if i.find('videoUrl')>0: self.download_url = i.split(': ')[1].strip('"') print self.download_url self.save_audio.set_sensitive(True) self.audio_file = str(soup.html.title).split(' ')[0].strip('<title>')+'.ogg'
wordz_db.delete_word(self.tree_value)
if self.tree_value in wordz_db.list_groups(): wordz_db.delete_group(self.tree_value) else: wordz_db.delete_word(self.tree_value)
def on_delete_clicked(self, widget=None, event=None): wordz_db.delete_word(self.tree_value) self.treestore.remove(self.iter)
def refresh_groups(self, grp):
def refresh_groups(self, grp, flag=0):
def refresh_groups(self, grp): tmp = wordz_db.list_groups() n = len(tmp) for i in range(0,n): self.get_group.remove_text(0) for x in tmp: self.get_group.append_text(x)
for i in range(0,n):
for i in range(0,n+flag):
def refresh_groups(self, grp): tmp = wordz_db.list_groups() n = len(tmp) for i in range(0,n): self.get_group.remove_text(0) for x in tmp: self.get_group.append_text(x)
if row[0] is not 'dummy':
if row[0] is not u'':
def list_groups(): conn = sqlite3.connect(db_file_path) c = conn.cursor() groups = [] for row in c.execute("""select grp from groups order by grp"""): if row[0] is not 'dummy': groups.append(row[0]) c.close() return groups
if word is not '':
if word is not '' and word not in list_words_per_group(grp):
def add_to_db(word, grp): conn = sqlite3.connect(db_file_path) c = conn.cursor() t = (grp,) if grp not in list_groups(): c.execute("""insert into groups values (?)""",t) conn.commit() if word is not '': t = (word, grp) c.execute('''insert into word_groups values(?,?)''', t) conn.commit() c.close()
elif i[1] != '0:0' and i[1] in self.new_word:
elif i[0] != '0:0' and i[1] in self.new_word:
def custom_tree_col_view(self, column, renderer, model, iter, data): word = model.get_value(iter, 0) for i in data: if i[0] == word and i[1] == '0:0' and word not in self.new_word: self.new_word.append(word) elif i[1] != '0:0' and i[1] in self.new_word: self.new_word.remove(i[0]) if word in self.new_word: renderer.set_property('text', 'New') else: renderer.set_property('text', None)
print self.new_word
def on_add_clicked(self, widget, data=None): word = self.get_word.get_text() get_group_ch = self.get_group.child group = get_group_ch.get_text() conts = self.details.get_buffer() start = conts.get_iter_at_offset(0) end = conts.get_iter_at_offset(-1) detail = conts.get_text(start, end) wordz_db.add_to_db(word, group, detail) self.refresh_groups(group) self.treestore.clear() self.new_word.append(word) if word not in self.new_word: self.new_word.append(word) print self.new_word self.on_back_clicked()
self.delete_b = self.builder.get_object('delete') self.play_b = self.builder.get_object('speak')
def __init__(self): self.builder = gtk.Builder() self.builder.add_from_file("wordgroupz.glade") self.window = self.builder.get_object("MainWindow") self.window.set_icon_from_file("/usr/share/pixmaps/wordgroupz.png") self.window.set_title("wordGroupz") self.builder.connect_signals(self) self.get_word = self.builder.get_object("get_word") self.get_group = gtk.combo_box_entry_new_text() self.get_group.set_tooltip_text("Enter a group for your word") self.details = self.builder.get_object("textview1") self.eventbox1 = self.builder.get_object('eventbox1') self.eventbox1.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#444444')) self.get_group.child.connect('key-press-event',self.item_list_changed) #self.vpan = self.builder.get_object("vpaned1") self.output_txtview = self.builder.get_object("textview2") for x in wordz_db.list_groups(): self.get_group.append_text(x) self.table1 = self.builder.get_object("table1") self.get_group.show() self.table1.attach(self.get_group, 1,2,1,2)
piter = self.treestore.append(None, [i])
piter = self.treestore.append(None, [i, self.acc_dict[i]])
def on_search_changed(self,widget=None,event=None): search_txt = self.search.get_text() words = list self.treestore.clear() if search_txt == '': self.on_back_clicked() return for group in wordz_db.list_groups(): for i in wordz_db.list_words_per_group(group): if i.startswith(search_txt): piter = self.treestore.append(None, [i]) #for word in wordz_db.list_words_per_group(group): # self.treestore.append(piter, [word])
self.delete_b = self.builder.get_object('delete') self.play_b = self.builder.get_object('speak')
def tree_select_changed(self, widget=None, event=None): self.model, self.iter = self.selection.get_selected() self.frame2.show() if self.iter is not None: self.delete_b = self.builder.get_object('delete') self.play_b = self.builder.get_object('speak') self.delete_b.set_sensitive(True) self.play_b.set_sensitive(True) if self.welcome is self.hbox2.get_children()[1]: self.welcome.hide() # self.hbox2.remove(self.welcome) # self.hbox2.pack_start(self.builder.get_object('frame2')) self.tree_value = self.model.get_value(self.iter,0) #print self.tree_value self.selected_word.show() self.selected_word.set_text(self.tree_value) #self.notebook2 = self.builder.get_object('notebook2') #cur_page = self.notebook2.get_current_page() #if self.tree_value not in wordz_db.list_groups(): #print self.tree_value self.hbox5.show() ''' w, h = self.window.get_size() self.vpan.set_position(h) tmp = self.vpan.get_position() self.vpan.set_position(int((240.0/450)*h)) else: self.vpan.set_position(10000) self.hbox3.hide()''' #if self.output_txtview.get_editable(): # self.output_txtview.set_editable(False) detail = wordz_db.get_details(self.tree_value) buff = self.output_txtview.get_buffer() buff.set_text(detail) self.output_txtview.set_buffer(buff) #self.output_txtview.modify_font(self.fontdesc) self.show_details_tree()
piter = self.treestore.append(None, [group])
l = wordz_db.list_words_per_group(group) t = 0 count = 0 for i in l: t = t + self.acc_dict[i] count = count + 1 t = t/count piter = self.treestore.append(None, [group, t])
def on_back_clicked(self, widget=None, data=None): if self.search.get_text()!= '': self.frame2.hide() self.search.set_text('') self.welcome.show() self.note.set_alignment(0.5, 0.1) self.note.set_markup('<span foreground="white"><b>Nothing selected</b></span>') return self.treestore.clear() #self.search.set_text('') for group in wordz_db.list_groups(): piter = self.treestore.append(None, [group]) for word in wordz_db.list_words_per_group(group): self.treestore.append(piter, [word]) self.treeview.expand_all() #buff = self.output_txtview.get_buffer() #buff.set_text('Nothing selected') #self.output_txtview.set_buffer(buff) self.selected_word.set_text('') #self.show_details_tree() #self.selected_word.hide() self.frame2.hide() self.welcome.show() self.note.set_alignment(0.5, 0.1) self.note.set_markup('<span foreground="white"><b>Nothing selected</b></span>')
self.treestore.append(piter, [word])
self.treestore.append(piter, [word, self.acc_dict[word]])
def on_back_clicked(self, widget=None, data=None): if self.search.get_text()!= '': self.frame2.hide() self.search.set_text('') self.welcome.show() self.note.set_alignment(0.5, 0.1) self.note.set_markup('<span foreground="white"><b>Nothing selected</b></span>') return self.treestore.clear() #self.search.set_text('') for group in wordz_db.list_groups(): piter = self.treestore.append(None, [group]) for word in wordz_db.list_words_per_group(group): self.treestore.append(piter, [word]) self.treeview.expand_all() #buff = self.output_txtview.get_buffer() #buff.set_text('Nothing selected') #self.output_txtview.set_buffer(buff) self.selected_word.set_text('') #self.show_details_tree() #self.selected_word.hide() self.frame2.hide() self.welcome.show() self.note.set_alignment(0.5, 0.1) self.note.set_markup('<span foreground="white"><b>Nothing selected</b></span>')
elif i[0] != '0:0' and i[1] in self.new_word:
elif i[1] != '0:0' and i[0] in self.new_word:
def custom_tree_col_view(self, column, renderer, model, iter, data): word = model.get_value(iter, 0) for i in data: if i[0] == word and i[1] == '0:0' and word not in self.new_word: self.new_word.append(word) elif i[0] != '0:0' and i[1] in self.new_word: self.new_word.remove(i[0]) if word in self.new_word: renderer.set_property('text', 'New') else: renderer.set_property('text', None)
if word not in self.new_word: self.new_word.append(word)
def on_add_clicked(self, widget, data=None): word = self.get_word.get_text() get_group_ch = self.get_group.child group = get_group_ch.get_text() conts = self.details.get_buffer() start = conts.get_iter_at_offset(0) end = conts.get_iter_at_offset(-1) detail = conts.get_text(start, end) wordz_db.add_to_db(word, group, detail) self.refresh_groups(group) self.treestore.clear() self.new_word.append(word) if word not in self.new_word: self.new_word.append(word) #print self.new_word self.on_back_clicked()
db_file_path = wordgroupz_dir+'/wordz'
db_file_path = wordgroupz_dir+'/wordgroupz.db'
def stopped(self): return self._stop.isSet()
c.execute("""insert into groups values ('no-category','Uncategorized words')""")
c.execute("""insert into groups values ('no-category','Uncategorized words', '', '', '')""")
def add_to_db(self,word, grp, detail): conn = sqlite3.connect(db_file_path) c = conn.cursor() conn.text_factory = str if grp not in self.list_groups() and grp is not '': if word is '': wn = wordnet.get_definition(grp) t = (grp,detail,wn, '', '') else: wn = wordnet.get_definition(grp) t = (grp,'', wn, '', '') c.execute("""insert into groups values (?,?,?,?,?)""",t) conn.commit() #allow words with no groups to be added elif 'no-category' not in self.list_groups() and grp is '': c.execute("""insert into groups values ('no-category','Uncategorized words')""") if word is not '' and word not in self.list_words_per_group(grp): if grp == '': grp = 'no-category' wn = wordnet.get_definition(word) #print wn t = (word, grp, detail, wn, '', '', '0:0') c.execute('''insert into word_groups values(?,?,?,?,?,?,?)''', t) conn.commit() c.close()
t = t + self.acc_dict[i] count = count + 1 t = t/count
if i not in self.new_word: t = t + self.acc_dict[i] count = count + 1 if count != 0: t = t/count else: t = 0
def __init__(self): self.builder = gtk.Builder() self.builder.add_from_file("wordgroupz.glade") self.window = self.builder.get_object("MainWindow") self.window.set_icon_from_file("/usr/share/pixmaps/wordgroupz.png") self.window.set_title("wordGroupz") self.builder.connect_signals(self) self.get_word = self.builder.get_object("get_word") self.get_group = gtk.combo_box_entry_new_text() self.get_group.set_tooltip_text("Enter a group for your word") self.details = self.builder.get_object("textview1") self.eventbox1 = self.builder.get_object('eventbox1') self.eventbox1.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#444444')) self.get_group.child.connect('key-press-event',self.item_list_changed) self.frame2 = self.builder.get_object('frame2') self.frame2.hide() #self.vpan = self.builder.get_object("vpaned1") self.output_txtview = self.builder.get_object("textview2") for x in wordz_db.list_groups(): self.get_group.append_text(x) self.table1 = self.builder.get_object("table1") self.get_group.show() self.table1.attach(self.get_group, 1,2,1,2)
if i[0] == word and i[1] == '0:0':
if i[0] == word and i[1] == '0:0' and word not in self.new_word:
def custom_tree_col_view(self, column, renderer, model, iter, data): word = model.get_value(iter, 0) for i in data: if i[0] == word and i[1] == '0:0': self.new_word.append(word) if word in self.new_word: renderer.set_property('text', 'New') else: renderer.set_property('text', None)
class get_def_thread(threading.Thread): stopthread = threading.Event() def run(self): word = win.tree_value dic = 'webster' if wordz_db.check_ws(win.tree_value): defs = wordz_db.get_dict_data(dic, win.tree_value)[0] else: d = online_dict() defs = d.get_def(word) wordz_db.save_webster(win.tree_value, defs) defs = '\n' + "webster:\n" + defs + '\n' """ elif dic == 'wordnet': if wordz_db.check_wn(win.tree_value): defs = wordz_db.get_dict_data(dic, win.tree_value)[0] else: defs = wordnet.get_definition(word) defs = '\n' + 'wordnet:\n' + defs + '\n' elif dic == 'wiktionary': if wordz_db.check_wik(win.tree_value): defs = wordz_db.get_dict_data(dic, win.tree_value)[0].strip("'").strip('"') defs = '\n' + 'wiktionary:\n'+defs + '\n' else: defs = '' buff = win.output_txtview.get_buffer() end = buff.get_iter_at_offset(-1) buff.place_cursor(end) buff.insert_interactive_at_cursor(defs, True)""" label = win.builder.get_object('label13') label.set_text(defs) def stop(self): self._stop.set() def stopped(self): return self._stop.isSet()
def wrapper(*args): t = threading.Thread(target=f, args = args) t.start()
if ws != u'' or ws !=None:
if ws != u'' and ws !=None: self.builder.get_object('label10').hide() self.builder.get_object('label9').hide() self.builder.get_object('scrolledwindow7').show()
def show_details_tree(self): self.details_treestore.clear() wn = '' wik = '' ws = '' for i in self.vbox12.get_children(): self.vbox12.remove(i) for i in self.vbox8.get_children(): self.vbox8.remove(i) for i in self.vbox13.get_children(): self.vbox13.remove(i) try: wn = wordz_db.get_dict_data('wordnet', self.tree_value)[0] except: pass try: ws = wordz_db.get_dict_data('webster', self.tree_value)[0] except: pass try: wik = wordz_db.get_dict_data('wiktionary', self.tree_value)[0].strip("'") #print "wiktionary"+ wik except: pass try: if wn != u'': table = gtk.Table(columns=2) table.show() self.vbox12.pack_start(table, False, padding = 5) i = 0 t = wn.split('\n') #piter = self.details_treestore.append(None, ['<span foreground="blue"><big><b>Wordnet</b></big></span>']) for x in t: if not x.startswith('\t') and x is not u'': #sub_iter = self.details_treestore.append(piter, ['<b>'+x+'</b>']) #hbox_n = gtk.HBox() event_b = gtk.EventBox() event_b.set_visible_window(True) event_b.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#AED6EF")) frame = gtk.Frame() frame.set_shadow_type(gtk.SHADOW_OUT) #frame.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("grey")) frame.show() event_b.show() #hbox_n.pack_start(frame, false) #hbox_n.show_all() label = gtk.Label(x) label.set_alignment(0.0, 0) #hbox_n.pack_start(label, False, padding = 2) table.attach(label, 0, 1, i, i+1, xoptions = gtk.FILL) label.show() #hbox_n.pack_start(frame, padding = 10) table.attach(frame, 1, 2, i, i+1) table.set_row_spacing(i, 10) table.set_col_spacing(0, 5) #hbox_n.show() #self.vbox12.pack_start(hbox_n, False, padding=5) vbox = gtk.VBox() vbox.show_all() event_b.add(vbox) frame.add(event_b) i = i + 1 elif x.startswith('\t') and not x.startswith('\tSynonyms:'): #sub_sub_iter = self.details_treestore.append(sub_iter, [x.strip('\t')]) vbox1 = gtk.VBox() label = gtk.Label() l = len(x.strip('\t')) label.set_markup('<b><big>'+x.strip('\t')[0:2]+'</big></b>'+x.strip('\t')[2:l]) #label.set_markup(x.strip('\t')) ##print x.lstrip('\t')[0:2] #l = len(x.strip('\t')) #print x.lstrip('\t')[0:l] if self.window.get_size() == self.window.get_default_size(): label.set_line_wrap(True) label.set_selectable(True) label.set_alignment(0.0, 0.5) label.show() #label.show() vbox1.pack_start(label, True) vbox1.show() vbox.pack_start(vbox1, False) elif x.startswith('\tSynonyms:'): #self.details_treestore.append(sub_sub_iter, [x.strip('\t').replace('Synonyms', '<span foreground="blue">Synonyms</span>')]) frame = gtk.Frame('Synonyms') label = gtk.Label() label.set_markup(('<b><span foreground="white">'+ cgi.escape(x.strip('\tSynonyms:')) + '</span></b>')) label.set_alignment(0.0, 0.5) label.show() eventbox = gtk.EventBox() eventbox.set_visible_window(True) eventbox.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#5C97BF")) #eventbox.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse("white")) eventbox.add(label) eventbox.show() frame.add(eventbox) frame.show() hbox = gtk.HBox() label = gtk.Label(' '*5) #label.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("blue")) label.show() hbox.pack_start(label, False) hbox.pack_start(frame) hbox.show() vbox1.pack_start(hbox, False) except: pass if wik != u'': t = wik.split('\n') #print t[0:6] #piter = self.details_treestore.append(None,['<span foreground="blue"><big><b>Wiktionary</b></big></span>']) table = gtk.Table(1, 2) table.set_col_spacing(0, 5) table.show() self.vbox8.pack_start(table, False) i = 0 h1 = [] j = 0 for x in t: #print 'j = ', #print j #j = j+1 if x.startswith('#'): #print sub_str #sub_iter = self.details_treestore.append(piter, ['<b>'+x.lstrip('#')+'</b>']) #h1.append(x.lstrip('#')) #print x.lstrip('#') #sub_str = '' #sub_sub_str = '' #sub_sub_str = '' eventb = gtk.EventBox() eventb.set_visible_window(True) eventb.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#AED6EF")) eventb.show() main_label = gtk.Label() main_label.set_markup('<b>'+x.lstrip('#')+'</b>') main_label.set_alignment(0.1, 0) main_label.show() table.attach(main_label, 0, 1, i, i+1, xoptions=gtk.FILL) main_frame = gtk.Frame() main_frame.show() main_vbox = gtk.VBox() main_vbox.show() main_frame.add(main_vbox) sub_vbox = gtk.VBox() sub_vbox.show() main_vbox.pack_start(sub_vbox, False) label = gtk.Label(' ') label.show() label.set_alignment(0, 0.5) #label.set_line_wrap(True) eventb.add(label) sub_vbox.pack_start(eventb, False) table.attach(main_frame, 1, 2, i, i+1) table.set_row_spacing(i, 10) table.set_col_spacing(0, 5) i = i + 1 elif not x.startswith('\t') and not x.startswith('#') and not x.startswith('\t#'): #print 'hi' #self.details_treestore.append(sub_iter, [x]) s = label.get_text() if x == u'': label.set_text( s + '\n' + x) else: label.set_text(s + x) #print label.get_text() #label.show() elif x.startswith('\t#'): #print sub_str #sub_sub_iter = self.details_treestore.append(sub_iter, ['<b>'+x.lstrip('\t#')+'</b>']) #print x.lstrip('\t#') #sub_sub_str = '' #pass eventb = gtk.EventBox() eventb.set_visible_window(True) eventb.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#AED6EF")) eventb.show() sub_sub_vbox = gtk.VBox() sub_sub_vbox.show() hbox = gtk.HBox() hbox.show() sub_sub_label = gtk.Label('\t') sub_sub_label.show() hbox.pack_start(sub_sub_vbox, False) sub_sub_vbox.pack_start(sub_sub_label, False) sub_sub_frame = gtk.Frame(' ') label = sub_sub_frame.get_label_widget() label.set_markup('<b>'+x.lstrip('\t#')+'</b>') try: if sub_sub_frame.get_label_widget()!=NULL: sub_sub_frame.set_label_widget(label) except: pass sub_sub_frame.show() sub_label = gtk.Label('') sub_label.show() sub_sub_sub_vbox = gtk.VBox() sub_sub_sub_vbox.show() sub_sub_frame.add(sub_sub_sub_vbox) eventb.add(sub_label) sub_label.set_alignment(0,0.5) sub_label.set_use_markup(True) sub_sub_sub_vbox.pack_start(eventb, False) hbox.pack_start(sub_sub_frame) sub_vbox.pack_start(hbox, False) elif x.startswith('\t') and not x.startswith('\t#') and not x.startswith('\t\t'): #self.details_treestore.append(sub_sub_iter, [x.lstrip('\t')]) #sub_sub_str = sub_sub_str + x.lstrip('\t') if sub_label.get_use_markup() == False: sub_label.set_use_markup(True) if x == '\t': sub_label.set_label(sub_label.get_text() + '\n' + x) else: x = x.lstrip('\t') if len(x)>1: x.lstrip() #print x[0:2] if x[0].isdigit(): sub_label.set_label(sub_label.get_label()+'<b>'+x[0:2]+'</b>'+x[2:len(x)]) else: sub_label.set_label(sub_label.get_label()+x) pass elif x.startswith('\t\t#'): #print x.split('#') #sub_sub_sub_iter = self.details_treestore.append(sub_sub_iter, ['<b>'+x.lstrip('\t\t#')+'</b>']) eventb = gtk.EventBox() eventb.set_visible_window(True) eventb.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#AED6EF")) eventb.show() sub_sub_sub_frame = gtk.Frame(' ') label = sub_sub_sub_frame.get_label_widget() label.set_markup('<b>'+x.lstrip('\t\t#')+'</b>') try: if sub_sub_sub_frame.get_label_widget()!=NULL: sub_sub_sub_frame.set_label_widget(label) except: pass sub_sub_sub_frame.show() sub_sub_sub_sub_vbox = gtk.VBox() sub_sub_sub_sub_vbox.show() sub_sub_sub_vbox.pack_start(sub_sub_sub_frame, False) sub_sub_sub_frame.add(sub_sub_sub_sub_vbox) sub_sub_label = gtk.Label(' ') sub_sub_label.set_alignment(0,0.5) eventb.add(sub_sub_label) sub_sub_label.show() sub_sub_sub_sub_vbox.pack_start(eventb, False) #sub_sub_vbox.pack_start(sub_sub_sub_frame, False) elif x.startswith('\t\t') and not x.startswith('\t\t#'): #print x ''' if x.strip('\t\t') != '': if x.find('terms derived from')>=0: self.details_treestore.append(sub_sub_sub_iter, ['<u><i>'+ x.lstrip('\t\t')+'</i></u>']) else: self.details_treestore.append(sub_sub_sub_iter, [x.lstrip('\t\t')])''' if x.strip('\t\t') !='': if x.find('terms derived from')>=0: sub_sub_label.set_text( sub_sub_label.get_text()+'\n'+ x.lstrip('\t\t')) else: sub_sub_label.set_text( sub_sub_label.get_text()+'\n'+ x.lstrip('\t\t'))
else: self.builder.get_object('look_webster').set_sensitive(True) label = gtk.Label() label.show() try: label.set_alignment(0.10, 0.10) except: pass label.set_text('Webster definition not in database,\nPlease click on "Look up"') self.vbox13.pack_start(label, False)
else: self.builder.get_object('look_webster').set_sensitive(True) self.builder.get_object('label9').show() self.builder.get_object('label10').hide() self.builder.get_object('scrolledwindow7').hide()
def show_details_tree(self): self.details_treestore.clear() wn = '' wik = '' ws = '' for i in self.vbox12.get_children(): self.vbox12.remove(i) for i in self.vbox8.get_children(): self.vbox8.remove(i) for i in self.vbox13.get_children(): self.vbox13.remove(i) try: wn = wordz_db.get_dict_data('wordnet', self.tree_value)[0] except: pass try: ws = wordz_db.get_dict_data('webster', self.tree_value)[0] except: pass try: wik = wordz_db.get_dict_data('wiktionary', self.tree_value)[0].strip("'") #print "wiktionary"+ wik except: pass try: if wn != u'': table = gtk.Table(columns=2) table.show() self.vbox12.pack_start(table, False, padding = 5) i = 0 t = wn.split('\n') #piter = self.details_treestore.append(None, ['<span foreground="blue"><big><b>Wordnet</b></big></span>']) for x in t: if not x.startswith('\t') and x is not u'': #sub_iter = self.details_treestore.append(piter, ['<b>'+x+'</b>']) #hbox_n = gtk.HBox() event_b = gtk.EventBox() event_b.set_visible_window(True) event_b.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#AED6EF")) frame = gtk.Frame() frame.set_shadow_type(gtk.SHADOW_OUT) #frame.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("grey")) frame.show() event_b.show() #hbox_n.pack_start(frame, false) #hbox_n.show_all() label = gtk.Label(x) label.set_alignment(0.0, 0) #hbox_n.pack_start(label, False, padding = 2) table.attach(label, 0, 1, i, i+1, xoptions = gtk.FILL) label.show() #hbox_n.pack_start(frame, padding = 10) table.attach(frame, 1, 2, i, i+1) table.set_row_spacing(i, 10) table.set_col_spacing(0, 5) #hbox_n.show() #self.vbox12.pack_start(hbox_n, False, padding=5) vbox = gtk.VBox() vbox.show_all() event_b.add(vbox) frame.add(event_b) i = i + 1 elif x.startswith('\t') and not x.startswith('\tSynonyms:'): #sub_sub_iter = self.details_treestore.append(sub_iter, [x.strip('\t')]) vbox1 = gtk.VBox() label = gtk.Label() l = len(x.strip('\t')) label.set_markup('<b><big>'+x.strip('\t')[0:2]+'</big></b>'+x.strip('\t')[2:l]) #label.set_markup(x.strip('\t')) ##print x.lstrip('\t')[0:2] #l = len(x.strip('\t')) #print x.lstrip('\t')[0:l] if self.window.get_size() == self.window.get_default_size(): label.set_line_wrap(True) label.set_selectable(True) label.set_alignment(0.0, 0.5) label.show() #label.show() vbox1.pack_start(label, True) vbox1.show() vbox.pack_start(vbox1, False) elif x.startswith('\tSynonyms:'): #self.details_treestore.append(sub_sub_iter, [x.strip('\t').replace('Synonyms', '<span foreground="blue">Synonyms</span>')]) frame = gtk.Frame('Synonyms') label = gtk.Label() label.set_markup(('<b><span foreground="white">'+ cgi.escape(x.strip('\tSynonyms:')) + '</span></b>')) label.set_alignment(0.0, 0.5) label.show() eventbox = gtk.EventBox() eventbox.set_visible_window(True) eventbox.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#5C97BF")) #eventbox.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse("white")) eventbox.add(label) eventbox.show() frame.add(eventbox) frame.show() hbox = gtk.HBox() label = gtk.Label(' '*5) #label.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("blue")) label.show() hbox.pack_start(label, False) hbox.pack_start(frame) hbox.show() vbox1.pack_start(hbox, False) except: pass if wik != u'': t = wik.split('\n') #print t[0:6] #piter = self.details_treestore.append(None,['<span foreground="blue"><big><b>Wiktionary</b></big></span>']) table = gtk.Table(1, 2) table.set_col_spacing(0, 5) table.show() self.vbox8.pack_start(table, False) i = 0 h1 = [] j = 0 for x in t: #print 'j = ', #print j #j = j+1 if x.startswith('#'): #print sub_str #sub_iter = self.details_treestore.append(piter, ['<b>'+x.lstrip('#')+'</b>']) #h1.append(x.lstrip('#')) #print x.lstrip('#') #sub_str = '' #sub_sub_str = '' #sub_sub_str = '' eventb = gtk.EventBox() eventb.set_visible_window(True) eventb.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#AED6EF")) eventb.show() main_label = gtk.Label() main_label.set_markup('<b>'+x.lstrip('#')+'</b>') main_label.set_alignment(0.1, 0) main_label.show() table.attach(main_label, 0, 1, i, i+1, xoptions=gtk.FILL) main_frame = gtk.Frame() main_frame.show() main_vbox = gtk.VBox() main_vbox.show() main_frame.add(main_vbox) sub_vbox = gtk.VBox() sub_vbox.show() main_vbox.pack_start(sub_vbox, False) label = gtk.Label(' ') label.show() label.set_alignment(0, 0.5) #label.set_line_wrap(True) eventb.add(label) sub_vbox.pack_start(eventb, False) table.attach(main_frame, 1, 2, i, i+1) table.set_row_spacing(i, 10) table.set_col_spacing(0, 5) i = i + 1 elif not x.startswith('\t') and not x.startswith('#') and not x.startswith('\t#'): #print 'hi' #self.details_treestore.append(sub_iter, [x]) s = label.get_text() if x == u'': label.set_text( s + '\n' + x) else: label.set_text(s + x) #print label.get_text() #label.show() elif x.startswith('\t#'): #print sub_str #sub_sub_iter = self.details_treestore.append(sub_iter, ['<b>'+x.lstrip('\t#')+'</b>']) #print x.lstrip('\t#') #sub_sub_str = '' #pass eventb = gtk.EventBox() eventb.set_visible_window(True) eventb.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#AED6EF")) eventb.show() sub_sub_vbox = gtk.VBox() sub_sub_vbox.show() hbox = gtk.HBox() hbox.show() sub_sub_label = gtk.Label('\t') sub_sub_label.show() hbox.pack_start(sub_sub_vbox, False) sub_sub_vbox.pack_start(sub_sub_label, False) sub_sub_frame = gtk.Frame(' ') label = sub_sub_frame.get_label_widget() label.set_markup('<b>'+x.lstrip('\t#')+'</b>') try: if sub_sub_frame.get_label_widget()!=NULL: sub_sub_frame.set_label_widget(label) except: pass sub_sub_frame.show() sub_label = gtk.Label('') sub_label.show() sub_sub_sub_vbox = gtk.VBox() sub_sub_sub_vbox.show() sub_sub_frame.add(sub_sub_sub_vbox) eventb.add(sub_label) sub_label.set_alignment(0,0.5) sub_label.set_use_markup(True) sub_sub_sub_vbox.pack_start(eventb, False) hbox.pack_start(sub_sub_frame) sub_vbox.pack_start(hbox, False) elif x.startswith('\t') and not x.startswith('\t#') and not x.startswith('\t\t'): #self.details_treestore.append(sub_sub_iter, [x.lstrip('\t')]) #sub_sub_str = sub_sub_str + x.lstrip('\t') if sub_label.get_use_markup() == False: sub_label.set_use_markup(True) if x == '\t': sub_label.set_label(sub_label.get_text() + '\n' + x) else: x = x.lstrip('\t') if len(x)>1: x.lstrip() #print x[0:2] if x[0].isdigit(): sub_label.set_label(sub_label.get_label()+'<b>'+x[0:2]+'</b>'+x[2:len(x)]) else: sub_label.set_label(sub_label.get_label()+x) pass elif x.startswith('\t\t#'): #print x.split('#') #sub_sub_sub_iter = self.details_treestore.append(sub_sub_iter, ['<b>'+x.lstrip('\t\t#')+'</b>']) eventb = gtk.EventBox() eventb.set_visible_window(True) eventb.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#AED6EF")) eventb.show() sub_sub_sub_frame = gtk.Frame(' ') label = sub_sub_sub_frame.get_label_widget() label.set_markup('<b>'+x.lstrip('\t\t#')+'</b>') try: if sub_sub_sub_frame.get_label_widget()!=NULL: sub_sub_sub_frame.set_label_widget(label) except: pass sub_sub_sub_frame.show() sub_sub_sub_sub_vbox = gtk.VBox() sub_sub_sub_sub_vbox.show() sub_sub_sub_vbox.pack_start(sub_sub_sub_frame, False) sub_sub_sub_frame.add(sub_sub_sub_sub_vbox) sub_sub_label = gtk.Label(' ') sub_sub_label.set_alignment(0,0.5) eventb.add(sub_sub_label) sub_sub_label.show() sub_sub_sub_sub_vbox.pack_start(eventb, False) #sub_sub_vbox.pack_start(sub_sub_sub_frame, False) elif x.startswith('\t\t') and not x.startswith('\t\t#'): #print x ''' if x.strip('\t\t') != '': if x.find('terms derived from')>=0: self.details_treestore.append(sub_sub_sub_iter, ['<u><i>'+ x.lstrip('\t\t')+'</i></u>']) else: self.details_treestore.append(sub_sub_sub_iter, [x.lstrip('\t\t')])''' if x.strip('\t\t') !='': if x.find('terms derived from')>=0: sub_sub_label.set_text( sub_sub_label.get_text()+'\n'+ x.lstrip('\t\t')) else: sub_sub_label.set_text( sub_sub_label.get_text()+'\n'+ x.lstrip('\t\t'))