eldoc/mods/catalogs.py

96 lines
3.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from mods.db import db, Catalog, CatalogIndex
import re
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GObject
from mods.utils import show_msg, ConditionalFilter
from mods.files import catalog_row_ui_str, new_catalog_win_file
from mods.root import builder
import peewee
class CatalogRow(Gtk.ListBoxRow):
@GObject.Property
def db_id(self):
return self._db_id
@db_id.setter
def db_id_setter(self, value):
self._db_id = value
@GObject.Property
def name(self):
return self._name
@name.setter
def name_setter(self, value):
self._name = value
def add_catalog(name):
with db.atomic():
catalog = Catalog.create(name=name)
CatalogIndex.insert(
{
CatalogIndex.rowid: catalog.id,
CatalogIndex.text: name
}
).execute()
return catalog
def search_catalogs(q):
q = re.sub(r'\s+', ' ', q).strip()
q = ' '.join([ f'{x}*' for x in q.split(' ')])
with db.atomic():
return (Catalog.select()
.join(
CatalogIndex,
on=(Catalog.id == CatalogIndex.rowid))
.where(CatalogIndex.match(q))
.order_by(CatalogIndex.bm25()))
catalog_filter = ConditionalFilter(search_catalogs)
###########################################################################
def build_catalog_row(catalog):
b = Gtk.Builder()
b.add_from_string(catalog_row_ui_str)
win = b.get_object('win')
box = b.get_object('catalog_box')
b.get_object('name').set_text(catalog.name)
row = CatalogRow()
row.props.db_id = catalog.id
row.name = catalog.name
win.remove(win.get_children()[0])
row.add(box)
return row
def create_new_catalog_win(catalog_list):
b = Gtk.Builder()
class NewCatalogHandler:
def save_catalog(self, *a):
catname = re.sub(r'\s+', ' ', b.get_object('catalog_name').get_text()).strip()
if not len(catname):
return show_msg('Не указано имя справочника', 'Данное поле должно быть заполнено', level='warn')
try:
catalog = add_catalog(catname)
except peewee.IntegrityError:
return show_msg('Данный справочник уже существует', 'Справочник с указанным названием уже есть с базе данных', level='warn')
row = build_catalog_row(catalog)
catalog_list.add(row)
catalog_list.select_row(row)
catalog_list.show_all()
b.get_object('new_catalog_window').close()
b.add_from_file(new_catalog_win_file)
b.connect_signals(NewCatalogHandler())
w = b.get_object('new_catalog_window')
return w
def catalog_sort_func(row1, row2, *a):
text1 = row1.props.name
text2 = row2.props.name
return (text1 > text2) - (text1 < text2)
def catalog_filter_func(row):
fstr = builder.get_object('catalog_filter').get_text().strip()
if not fstr:
catalog_filter.reset()
return True
return row.props.db_id in catalog_filter.filter(fstr)