def test_set_multiple_column_titles(self): dicts = [{ "key1_1": "val1_1", "key1_2": "val1_2", "key1_3": "val1_3" }, { "key1_1": "val2_1", "key1_2": "val2_2", "key1_3": "val2_3" }, { "key1_1": "val3_1", "key1_2": "val3_2", "key1_3": "val3_3" }, { "key1_1": "val4_1", "key1_2": "val4_2", "key1_3": "val4_3" }, { "key1_1": "val5_1", "key1_2": "val5_2", "key1_3": "val5_3" }] grid = DictionaryGrid(dicts) titles = {"key1_1": "KEY1", "key1_2": "KEY2", "key1_3": "KEY3"} grid.set_column_titles(titles) for c in grid.columns: self.assertTrue(grid.columns[c].get_title() in ("KEY1", "KEY2", "KEY3"))
def openbutton(self, widget, data=None): response, path = prompts.choose_directory() if response == gtk.RESPONSE_OK: media_files = [] formats = self.supported_audio_formats + self.supported_video_formats for root, dirs, files in os.walk(path): for f in files: for format in formats: if f.lower().endswith(format): file_url = "file://" + os.path.join(root, f) data = {"File" : f, "url" : file_url, "format" : format, } media_files.append(data) for format in self.supported_album_art_formats: if f.lower().endswith(format): self.image_url = os.path.join(root, f) #exception if no supported is found.. if self.image_url is '': self.image_url = "background.png" #print media_files scrolledwindow = self.builder.get_object('scrolledwindow1') #print scrolledwindow for c in scrolledwindow.get_children(): scrolledwindow.remove(c) media_grid = DictionaryGrid(media_files, keys=["File"]) media_grid.connect("selection_changed", self.play_file) media_grid.show() #print media_files scrolledwindow.add(media_grid)
def test_set_a_column_title(self): dicts = [{ "key1_1": "val1_1", "key1_2": "val1_2", "key1_3": "val1_3" }, { "key1_1": "val2_1", "key1_2": "val2_2", "key1_3": "val2_3" }, { "key1_1": "val3_1", "key1_2": "val3_2", "key1_3": "val3_3" }, { "key1_1": "val4_1", "key1_2": "val4_2", "key1_3": "val4_3" }, { "key1_1": "val5_1", "key1_2": "val5_2", "key1_3": "val5_3" }] grid = DictionaryGrid(dicts) grid.columns["key1_1"].set_title("KEY") for c in grid.get_columns(): if c.key == "key1_1": self.assertEqual(c.get_title(), "KEY")
class OpenDialog(Gtk.Dialog): __gtype_name__ = "OpenDialog" def __new__(cls): """Special static method that's automatically called by Python when constructing a new instance of this class. Returns a fully instantiated OpenDialog object. """ builder = get_builder('OpenDialog') new_object = builder.get_object('open_dialog') new_object.finish_initializing(builder) return new_object def finish_initializing(self, builder): """Called when we're finished initializing. finish_initalizing should be called after parsing the ui definition and creating a OpenDialog object with it in order to finish initializing the start of the new OpenDialog instance. """ # Get a reference to the builder and set up the signals. self.builder = builder self.ui = builder.get_ui(self) #get the jotty document names data_dir = GLib.get_user_data_dir() jotty_dir = os.path.join(data_dir, "jotty") filenames = os.listdir(jotty_dir) #put them into a grid dicts = [{'Name': x, 'File': os.path.join(jotty_dir, x)} for x in filenames] self.grid = DictionaryGrid(dictionaries=dicts, keys=['Name']) #add grid to dialog self.grid.show() self.ui.box1.pack_end(self.grid, True, True, 0) def on_btn_ok_clicked(self, widget, data=None): """The user has elected to save the changes. Called before the dialog returns Gtk.ResponseType.OK from run(). """ pass def on_btn_cancel_clicked(self, widget, data=None): """The user has elected cancel changes. Called before the dialog returns Gtk.ResponseType.CANCEL for run() """ pass @property def selected_file(self): rows = self.grid.selected_rows if len(rows) < 1: return None else: return rows[0]['Name']
def finish_initializing(self, builder): """Called when we're finished initializing. finish_initalizing should be called after parsing the ui definition and creating a OpenDialog object with it in order to finish initializing the start of the new OpenDialog instance. """ # Get a reference to the builder and set up the signals. self.builder = builder self.ui = builder.get_ui(self) #get the jotty document names data_dir = GLib.get_user_data_dir() jotty_dir = os.path.join(data_dir, "jotty") filenames = os.listdir(jotty_dir) #put them into a grid dicts = [{ 'Name': x, 'File': os.path.join(jotty_dir, x) } for x in filenames] self.grid = DictionaryGrid(dictionaries=dicts, keys=['Name']) #add grid to dialog self.grid.show() self.ui.box1.pack_end(self.grid, True, True, 0)
def test_use_custom_columns(self): """Ensure that type hins work so inferred types can be overridden and non-inferred type can be set. """ keys = ["id", "price", "bool?", "foo"] hints = { "id": StringColumn, "price": IntegerColumn, "bool?": CurrencyColumn, "foo": CheckColumn } dicts = [{"price": 100, "id": "asdfas", "bool?": 10.01, "foo": True}] grid = DictionaryGrid(dicts, keys=keys, type_hints=hints) for c in grid.get_columns(): key = c.key col_type = c.column_type if key == "id": self.assertEqual(col_type, gobject.TYPE_STRING) elif key == "price": self.assertEqual(col_type, gobject.TYPE_STRING) elif key == "bool?": self.assertEqual(col_type, gobject.TYPE_STRING) elif key == "foo": self.assertEqual(col_type, gobject.TYPE_INT) else: self.assertEqual("Extra key Found", False)
def test_with_set_column_titles(self): dicts = [{"key1_1": "val1_1", "key1_2": "val1_2", "key1_3": "val1_3"}, {"key1_1": "val2_1", "key1_2": "val2_2", "key1_3": "val2_3"}, {"key1_1": "val3_1", "key1_2": "val3_2", "key1_3": "val3_3"}, {"key1_1": "val4_1", "key1_2": "val4_2", "key1_3": "val4_3"}, {"key1_1": "val5_1", "key1_2": "val5_2", "key1_3": "val5_3"}] grid = DictionaryGrid(dictionaries = dicts, keys=["key1_1","key1_2","key1_3"]) titles = {"key1_1":"KEY1","key1_2":"KEY2","key1_3":"KEY3"} grid.set_column_titles(titles) grid_filter = GridFilter(grid) filter_row = grid_filter.rows[0] column_combo = filter_row.get_children()[0].get_children()[0] #make sure the correct titles are appearing itr = column_combo.get_model().get_iter(0) self.assertEqual(column_combo.get_model().get_value(itr,0),"KEY1") itr = column_combo.get_model().get_iter(1) self.assertEqual(column_combo.get_model().get_value(itr,0),"KEY2") itr = column_combo.get_model().get_iter(2) self.assertEqual(column_combo.get_model().get_value(itr,0),"KEY3") #make sure filtering still works filter_combo = filter_row.get_children()[1].get_children()[0].get_children()[0] filter_combo.set_active(1) entry = filter_row.get_children()[1].get_children()[0].get_children()[1] entry.set_text("val5_1") self.assertEqual(len(grid.get_model()),4)
def test_extra_data_from_selected(self): """Ensure that keys starting with _ are not displayed, but the valuesa retrievable. """ dicts = [{ "key1_1": "val1_1", "key1_2": "val1_2", "__extra": ["boo", "biz", "baz"] }, { "key1_1": "val2_1", "key1_2": "val2_2", "__extra": self }] grid = DictionaryGrid(dicts) #make sure there are 2 columns self.assertEqual(len(grid.get_model()), 2) #ensure that none of the columns are named _extra cols = grid.get_columns() for c in cols: self.assertEqual(c.get_title().startswith("key"), True) #select the first row selection = grid.get_selection() selection.select_path((0, )) selected_dict = grid.selected_rows[0] self.assertEqual(selected_dict["__extra"], ["boo", "biz", "baz"])
def test_create_a_grid(self): dicts = [{"key1_1": "val1_1", "key1_2": "val1_2", "key1_3": "val1_3"}, {"key1_1": "val2_1", "key1_2": "val2_2", "key1_3": "val2_3"}, {"key1_1": "val3_1", "key1_2": "val3_2", "key1_3": "val3_3"}, {"key1_1": "val4_1", "key1_2": "val4_2", "key1_3": "val4_3"}, {"key1_1": "val5_1", "key1_2": "val5_2", "key1_3": "val5_3"}] grid = DictionaryGrid(dicts) grid_filter = GridFilter(grid) self.assertEqual(len(grid.get_model()),5)
def update_list(response, kind): '''Return a DictionaryGrid with the sorted response in it''' plural = ''.join([kind, 's']) label = ''.join(['[All ', plural.capitalize(), ']']) kind_id = ''.join([kind, 'id']) items = sorted(response[plural], key=lambda k: k['label']) items.insert(0, {kind_id: -1, 'label': label}) grid = DictionaryGrid(items, keys=['label']) title = plural.capitalize() grid.columns['label'].set_title(title) grid.set_headers_clickable(False) return grid
def _refresh_treeview(self): """ _refresh_treeview: internal function to handle rebuilding the gtk.TreeView along with columns and cell renderers. extends DictionaryGrid._refresh_treeview by retrieving stored desktopcouch records before calling DictionaryGrid._refresh_treeview. _refresh_treeview is not typically called directly, but may be useful to override in subclasses. """ #if the database is not set up, just return if self._db is None or self._record_type is None: return #if keys aren't set, infer them from the collection if len(self._dictionaries) > 0 and self.keys is None: self._infer_keys_from_dictionaries() #retrieve the docs for the record_type, if any results = self._db.get_records( record_type=self._record_type,create_view=True) #if there are no rows and no keys set, there is no #way to build the grid, just raise an error if len(results) == 0 and self._keys is None: raise RuntimeError("Cannot infer columns for CouchGrid") dicts = [] for r in results: d = r.value #hmmm, maybe make these so they get hidden rather than delete them #hide the desktopcouch variabls for key in d: if key.startswith("_") and not key.startswith("__desktopcouch"): d["__desktopcouch" + key] = d[key] del(d[key]) d["__record_type"] = d["record_type"] del(d["record_type"]) dicts.append(d) self._dictionaries = dicts DictionaryGrid._refresh_treeview(self) for c in self.get_columns(): if type(c) == CheckColumn: c.renderer.connect("toggled",self._edited_toggled, c) else: c.renderer.connect("edited",self._edited, c)
def test_mismatched_col_and_val_types(self): """Ensure robustness for strings passed in for non-str column types """ keys = ["id", "price", "bool?"] dicts = [{"price": "100.00", "id": "50", "bool?": "Yes"}] grid = DictionaryGrid(dicts, keys) test_dict = grid.get_dictionaries_copy()[0] self.assertEqual(test_dict["id"], 50) self.assertEqual(test_dict["price"], 100.00) self.assertEqual(test_dict["bool?"], True)
def finish_initializing(self, builder): """Called when we're finished initializing. finish_initalizing should be called after parsing the ui definition and creating a OpenDialog object with it in order to finish initializing the start of the new OpenDialog instance. """ # Get a reference to the builder and set up the signals. self.builder = builder self.ui = builder.get_ui(self) self.supported_shape_formats = [".shp"] #let the user choose a path with the directory chooser response, path = prompts.choose_directory() #make certain the user said ok before working if response == Gtk.ResponseType.OK: #make one list of support formats formats = self.supported_shape_formats #make a list of the supported media files media_files = [] #iterate through root directory for files in glob.glob(path + "/*.shp"): for format in formats: if files.endswith(format): #create a URI in a format gstreamer likes file_uri = path fileSplit = files.split(path + "/") #add a dictionary to the list of media files media_files.append({ "File": fileSplit[1], "uri": file_uri, "format": format }) #remove any children in scrolled window #for c in self.ui.scrolledwindow1.get_children(): # self.ui.scrolledwindow1.remove(c) #create the grid with list of dictionaries #only show the File column global media_grid media_grid = DictionaryGrid(media_files, keys=["File"]) #show the grid, and add it to the scrolled window media_grid.show() self.ui.box1.pack_end(media_grid, True, True, 0)
def test_dicts_with_different_keys(self): dicts = [{ "key1_1": "val1_1", "key1_2": "val1_2", "__extra": ["boo", "biz", "baz"] }, { "key2_1": "val2_1", "key2_2": "val2_2", "__extra": self }] grid = DictionaryGrid(dicts) #make sure there are 5 columns self.assertEqual(grid.get_model().get_n_columns(), 5)
def test_filter_a_row(self): dicts = [{"key1_1": "val1_1", "key1_2": "val1_2", "key1_3": "val1_3"}, {"key1_1": "val2_1", "key1_2": "val2_2", "key1_3": "val2_3"}, {"key1_1": "val3_1", "key1_2": "val3_2", "key1_3": "val3_3"}, {"key1_1": "val4_1", "key1_2": "val4_2", "key1_3": "val4_3"}, {"key1_1": "val5_1", "key1_2": "val5_2", "key1_3": "val5_3"}] grid = DictionaryGrid(dicts) grid_filter = GridFilter(grid) filter_row = grid_filter.rows[0] filter_combo = filter_row.get_children()[1].get_children()[0].get_children()[0] filter_combo.set_active(1) entry = filter_row.get_children()[1].get_children()[0].get_children()[1] entry.set_text("val5_1") self.assertEqual(len(grid.get_model()),4)
def test_columns_property(self): dicts = [{ "key1_1": "val1_1", "key1_2": "val1_2", "key1_3": "val1_3" }, { "key1_1": "val2_1", "key1_2": "val2_2", "key1_3": "val2_3" }, { "key1_1": "val3_1", "key1_2": "val3_2", "key1_3": "val3_3" }, { "key1_1": "val4_1", "key1_2": "val4_2", "key1_3": "val4_3" }, { "key1_1": "val5_1", "key1_2": "val5_2", "key1_3": "val5_3" }] grid = DictionaryGrid(dicts) self.assertTrue("key1_1" in grid.columns) self.assertTrue("key1_2" in grid.columns) self.assertTrue("key1_3" in grid.columns)
def test_constructor_with_dicts(self): """test creating a grid with dictionaries in the contructor""" dicts = [{ "key1_1": "val1_1", "key1_2": "val1_2", "key1_3": "val1_3" }, { "key1_1": "val2_1", "key1_2": "val2_2", "key1_3": "val2_3" }] #build the CouchGrid grid = DictionaryGrid(dicts) self.assertEqual(grid.get_model().get_n_columns(), 4) self.assertEqual(len(grid.get_model()), 2)
def finish_initializing(self, builder): """Called when we're finished initializing. finish_initalizing should be called after parsing the ui definition and creating a OpenDialog object with it in order to finish initializing the start of the new OpenDialog instance. """ # Get a reference to the builder and set up the signals. self.builder = builder self.ui = builder.get_ui(self) self.supported_shape_formats = [".shp"] #let the user choose a path with the directory chooser response, path = prompts.choose_directory() #make certain the user said ok before working if response == Gtk.ResponseType.OK: #make one list of support formats formats = self.supported_shape_formats #make a list of the supported media files media_files = [] #iterate through root directory for files in glob.glob(path + "/*.shp"): for format in formats: if files.endswith(format): #create a URI in a format gstreamer likes file_uri = path fileSplit = files.split(path + "/") #add a dictionary to the list of media files media_files.append({"File":fileSplit[1],"uri":file_uri, "format":format}) #remove any children in scrolled window #for c in self.ui.scrolledwindow1.get_children(): # self.ui.scrolledwindow1.remove(c) #create the grid with list of dictionaries #only show the File column global media_grid media_grid = DictionaryGrid(media_files, keys=["File"]) #show the grid, and add it to the scrolled window media_grid.show() self.ui.box1.pack_end(media_grid, True, True, 0)
def test_infer_boolean_values(self): """Ensure that inferring boolean values from strings works""" keys = ["a?", "b?", "c?", "d?", "e?", "f?"] dicts = [{ "a?": True, "b?": False, "c?": "Yes", "d?": "No", "e?": 1.5, "f?": 0 }] grid = DictionaryGrid(dicts, keys) test_dict = grid.get_dictionaries_copy()[0] self.assertEqual(test_dict["a?"], True) self.assertEqual(test_dict["b?"], False) self.assertEqual(test_dict["c?"], True) self.assertEqual(test_dict["d?"], False) self.assertEqual(test_dict["e?"], True) self.assertEqual(test_dict["f?"], False)
def append_row(self, dictionary): """append_row: add a row to the TreeView and to DesktopCouch. If keys are already set up only the the keys in the dictionary matching the keys used for columns will be displayed, though all the key value pairs will be saved to the DesktopCouch. If no keys are set up, and this is the first row, keys will be inferred from the dictionary keys. arguments: dictionary - a dictionary to add to the Treeview and to DesktopCouch """ if dictionary is None: dictionary = {} #Here we add rows to desktopcouch if needed if "__desktopcouch_id" not in dictionary: self._persist_dict_to_couch(dictionary) DictionaryGrid.append_row(self,dictionary)
def test_constructor_with_dicts_and_keys(self): """test creating a grid with dictionaries in the contructor as well as keys in the contructor, with fewer keys than items in the dictionary """ dicts = [{ "key1_1": "val1_1", "key1_2": "val1_2", "key1_3": "val1_3" }, { "key1_1": "val2_1", "key1_2": "val2_2", "key1_3": "val2_3" }] keys = ["key1_1", "key1_3"] #build the CouchGrid grid = DictionaryGrid(dicts, keys) self.assertEqual(grid.get_model().get_n_columns(), 4) self.assertEqual(len(grid.get_model()), 2)
def test_empty_construction(self): """Test a simple creating An AsynchTaskProgressBox and then adding keys and dictionaries after creation """ grid = DictionaryGrid() self.assertEqual((grid != None), True) grid.keys = ["key1", "key2"] self.assertEqual(grid.get_model().get_n_columns(), 3) grid.append_row({"key1": "val11", "key2": "val12"}) self.assertEqual(len(grid.get_model()), 1)
def openbutton_clicked_event(self, widget, data=None): #let the user choose a path with the directory chooser response, path = prompts.choose_directory() #make certain the user said ok before working if response == gtk.RESPONSE_OK: #make one list of support formats formats = self.allowed_formats #make a list of the supported media files media_files = [] #iterate through root directory for root, dirs, files in os.walk(path): #iterate through each file for f in files: #check if the file is a supported formats for format in formats: if f.lower().endswith(format): #create a URI in a format gstreamer likes file_uri = "file://" + os.path.join(root,f) #add a dictionary to the list of media files media_files.append({"File":f,"uri":file_uri, "format":format}) #remove any children in scrolled window for c in self.ui.scrolledwindow1.get_children(): self.ui.scrolledwindow1.remove(c) #create the grid with list of dictionaries #only show the File column media_grid = DictionaryGrid(media_files, keys=["File"]) #hook up to the selection_changed event media_grid.connect("selection_changed", self.play_file) #show the grid, and add it to the scrolled window media_grid.show() self.ui.scrolledwindow1.add(media_grid)
def test_auto_set_col_types(self): """Ensure that collumn types are set properly""" data = [{ "id": 0, "price": 1.00, "bool?": True, "sale price": .50, "count": 50, "full count": 100, "date": "2010-05-05", "sale date": "2010-05-06" }] grid = DictionaryGrid(data) c_type = type(grid.columns["id"]) self.assertEqual(c_type, IntegerColumn) c_type = type(grid.columns["price"]) self.assertEqual(c_type, CurrencyColumn) c_type = type(grid.columns["bool?"]) self.assertEqual(c_type, CheckColumn) c_type = type(grid.columns["sale price"]) self.assertEqual(c_type, CurrencyColumn) c_type = type(grid.columns["count"]) self.assertEqual(c_type, IntegerColumn) c_type = type(grid.columns["full count"]) self.assertEqual(c_type, IntegerColumn) c_type = type(grid.columns["date"]) self.assertEqual(c_type, DateColumn) c_type = type(grid.columns["sale date"]) self.assertEqual(c_type, DateColumn)
def finish_initializing(self, builder): """Called when we're finished initializing. finish_initalizing should be called after parsing the ui definition and creating a OpenDialog object with it in order to finish initializing the start of the new OpenDialog instance. """ # Get a reference to the builder and set up the signals. self.builder = builder self.ui = builder.get_ui(self) #get the jotty document names data_dir = GLib.get_user_data_dir() jotty_dir = os.path.join(data_dir, "jotty") filenames = os.listdir(jotty_dir) #put them into a grid dicts = [{'Name': x, 'File': os.path.join(jotty_dir, x)} for x in filenames] self.grid = DictionaryGrid(dictionaries=dicts, keys=['Name']) #add grid to dialog self.grid.show() self.ui.box1.pack_end(self.grid, True, True, 0)
def openbutton_clicked_event(self, widget, data=None): #let the user choose a path with the directory chooser response, path = prompts.choose_directory() #make certain the user said ok before working if response == gtk.RESPONSE_OK: #make one list of support formats formats = self.allowed_formats #make a list of the supported media files media_files = [] #iterate through root directory for root, dirs, files in os.walk(path): #iterate through each file for f in files: #check if the file is a supported formats for format in formats: if f.lower().endswith(format): #create a URI in a format gstreamer likes file_uri = "file://" + os.path.join(root, f) #add a dictionary to the list of media files media_files.append({ "File": f, "uri": file_uri, "format": format }) #remove any children in scrolled window for c in self.ui.scrolledwindow1.get_children(): self.ui.scrolledwindow1.remove(c) #create the grid with list of dictionaries #only show the File column media_grid = DictionaryGrid(media_files, keys=["File"]) #hook up to the selection_changed event media_grid.connect("selection_changed", self.play_file) #show the grid, and add it to the scrolled window media_grid.show() self.ui.scrolledwindow1.add(media_grid)
def test_copy_dictionaries(self): """Testcase for LP: #497664""" dicts = [{ "key1_1": "val1_1", "key1_2": "val1_2", "key1_3": "val1_3" }, { "key1_1": "val2_1", "key1_2": "val2_2", "key1_3": "val2_3" }] #build the CouchGrid grid1 = DictionaryGrid(dicts) # added two dicts, so length should be 2 self.assertEqual(len(grid1.get_dictionaries_copy()), 2) #no dicts, so it should be 0 grid2 = DictionaryGrid() self.assertEqual(len(grid2.get_dictionaries_copy()), 0)
def test_remove_selected_with_filter(self): dicts = [{"key1_1": "val1_1", "key1_2": "val1_2", "key1_3": "val1_3"}, {"key1_1": "val2_1", "key1_2": "val2_2", "key1_3": "val2_3"}, {"key1_1": "val3_1", "key1_2": "val3_2", "key1_3": "val3_3"}, {"key1_1": "val4_1", "key1_2": "val4_2", "key1_3": "val4_3"}, {"key1_1": "val5_1", "key1_2": "val5_2", "key1_3": "val5_3"}] grid = DictionaryGrid(dicts) grid_filter = GridFilter(grid) filter_row = grid_filter.rows[0] filter_combo = filter_row.get_children()[1].get_children()[0].get_children()[0] filter_combo.set_active(1) entry = filter_row.get_children()[1].get_children()[0].get_children()[1] entry.set_text("val5_1") selection = grid.get_selection() selection.select_path((1,)) selection.select_path((2,)) grid.remove_selected_rows() self.assertEqual(len(grid.get_model()),2)
def __init__( self, database_name, record_type=None, dictionaries=None, editable=False, keys=None, type_hints=None, uri=None): """Create a new Couchwidget arguments: database_name - specify the name of the database in the desktop couchdb to use. If the specified database does not exist, it will be created. optional arguments: record_type - a string to specify the record_type to use in retrieving and creating records. Note that if no records exist in the CouchDB then the keys argument must also be used or a RuntimeError will result. dictionaries - a list of dictionaries to initialize in the grid. If these haven't been added to desktopcouch, the will be automatically persisted and updated using the recored_type specified. Any previously saved data of the same record_type will also be displayed. keys - a list of strings specifying keys to use in the columns of the CouchGrid. The keys will also be used for the column titles and keys in desktop couch. If a record does not contain a value for a specified key the CouchGrid will simply display an empty cell of the appropriate type. If the widget is set to editable, the user will be able to add values to the database. The types for the columns will be inferred by the key based on some conventions. the key "id" is assumed to be an integer, as is any key ending in " count". A key ending in "?" is assumed to be a Boolean displayed with a checkbox. The key "price" is assumed to be currency, as is any key ending in "count". There may be others. Defaults can be overridden using type-hints. All other keys will be assumed to be strings. type-hints - a dictionary containing keys specificed for the TreeView and GridColumns. Used to override types inferred by convention, or for changing the type of a column from the default of a string to something else. uri - A uri for the DesktopCouch. This is only used to choose a Couch database running remotely. The default is to use the local desktopcouch database. """ if type(database_name) is not type(str()): raise TypeError("database_name is required and must be a string") #set up the database before trying to use it self.uri = uri self._record_type = None self._db = None if record_type is not None: self._record_type = record_type if dictionaries is not None and keys is None: DictionaryGrid.__init__(self, None, editable, keys, type_hints) else: DictionaryGrid.__init__(self, None, editable, keys, type_hints) if self.uri: self._db = CouchDatabase(database_name, create=True, uri=self.uri) else: self._db = CouchDatabase(database_name, create=True) if dictionaries is not None: for d in dictionaries: self._persist_dict_to_couch(d) self._refresh_treeview()
def test_remove_selected_rows(self): dicts = [{ "key1_1": "val1_1", "key1_2": "val1_2", "key1_3": "val1_3" }, { "key1_1": "val2_1", "key1_2": "val2_2", "key1_3": "val2_3" }, { "key1_1": "val3_1", "key1_2": "val3_2", "key1_3": "val3_3" }, { "key1_1": "val4_1", "key1_2": "val4_2", "key1_3": "val4_3" }, { "key1_1": "val5_1", "key1_2": "val5_2", "key1_3": "val5_3" }] grid = DictionaryGrid(dicts) selection = grid.get_selection() grid.remove_selected_rows() #select the last row and remove it selection.select_path((4, )) grid.remove_selected_rows() #the last row should then be selected and there should be 4 rows now self.assertEqual(len(grid.get_model()), 4) self.assertEqual(len(grid.selected_rows), 1) self.assertEqual(grid.selected_rows[0]["key1_1"], "val4_1") #select the first and third rows and remove them selection = grid.get_selection() selection.unselect_all() selection.select_path((0, )) selection.select_path((2, )) grid.remove_selected_rows() #make sure the now last row is selected, and there are 2 rows left self.assertEqual(len(grid.get_model()), 2) self.assertEqual(len(grid.selected_rows), 1) self.assertEqual(grid.selected_rows[0]["key1_2"], "val4_2")
class OpenDialog(Gtk.Dialog): __gtype_name__ = "OpenDialog" def __new__(cls): """Special static method that's automatically called by Python when constructing a new instance of this class. Returns a fully instantiated OpenDialog object. """ builder = get_builder('OpenDialog') new_object = builder.get_object('open_dialog') new_object.finish_initializing(builder) return new_object def finish_initializing(self, builder): """Called when we're finished initializing. finish_initalizing should be called after parsing the ui definition and creating a OpenDialog object with it in order to finish initializing the start of the new OpenDialog instance. """ # Get a reference to the builder and set up the signals. self.builder = builder self.ui = builder.get_ui(self) #get the jotty document names data_dir = GLib.get_user_data_dir() jotty_dir = os.path.join(data_dir, "jotty") filenames = os.listdir(jotty_dir) #put them into a grid dicts = [{ 'Name': x, 'File': os.path.join(jotty_dir, x) } for x in filenames] self.grid = DictionaryGrid(dictionaries=dicts, keys=['Name']) #add grid to dialog self.grid.show() self.ui.box1.pack_end(self.grid, True, True, 0) def on_btn_ok_clicked(self, widget, data=None): """The user has elected to save the changes. Called before the dialog returns Gtk.ResponseType.OK from run(). """ pass def on_btn_cancel_clicked(self, widget, data=None): """The user has elected cancel changes. Called before the dialog returns Gtk.ResponseType.CANCEL for run() """ pass @property def selected_file(self): rows = self.grid.selected_rows if len(rows) < 1: return None else: return rows[0]['Name']
def remove_selected_rows(self, delete=False): rows_to_delete = self.selected_rows if delete: for r in rows_to_delete: self.database.delete_record(r["__desktopcouch_id"]) DictionaryGrid.remove_selected_rows(self)
def test_NONE_values(self): keys = ["id", "price", "bool?", "foo"] dicts = [{"price": None, "id": None, "bool?": None, "foo": None}] grid = DictionaryGrid(dicts) self.assertEqual(len(grid.get_model()), 1)