Improve spacebar navigation

Refactor variables
This commit is contained in:
BasioMeusPuga
2018-04-10 12:39:52 +05:30
parent bc54d6b686
commit 528c2e387c
8 changed files with 177 additions and 169 deletions

1
TODO
View File

@@ -79,6 +79,7 @@ TODO
✓ Define every widget in code ✓ Define every widget in code
Bugs: Bugs:
Deselecting all directories in the settings dialog also filters out manually added books Deselecting all directories in the settings dialog also filters out manually added books
Clean up 'switch' page layout
Secondary: Secondary:
Graphical themes Graphical themes

View File

@@ -265,7 +265,7 @@ class MainUI(QtWidgets.QMainWindow, mainwindow.Ui_MainWindow):
self.tableView.horizontalHeader().resizeSection(5, 30) self.tableView.horizontalHeader().resizeSection(5, 30)
self.tableView.horizontalHeader().setStretchLastSection(False) self.tableView.horizontalHeader().setStretchLastSection(False)
self.tableView.horizontalHeader().sectionClicked.connect( self.tableView.horizontalHeader().sectionClicked.connect(
self.lib_ref.table_proxy_model.sort_table_columns) self.lib_ref.tableProxyModel.sort_table_columns)
self.tableView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.tableView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.tableView.customContextMenuRequested.connect( self.tableView.customContextMenuRequested.connect(
self.generate_library_context_menu) self.generate_library_context_menu)
@@ -404,14 +404,14 @@ class MainUI(QtWidgets.QMainWindow, mainwindow.Ui_MainWindow):
selected_indexes = None selected_indexes = None
if library_widget == self.listView: if library_widget == self.listView:
selected_books = self.lib_ref.item_proxy_model.mapSelectionToSource( selected_books = self.lib_ref.itemProxyModel.mapSelectionToSource(
self.listView.selectionModel().selection()) self.listView.selectionModel().selection())
selected_indexes = [i.indexes()[0] for i in selected_books] selected_indexes = [i.indexes()[0] for i in selected_books]
elif library_widget == self.tableView: elif library_widget == self.tableView:
selected_books = self.tableView.selectionModel().selectedRows() selected_books = self.tableView.selectionModel().selectedRows()
selected_indexes = [ selected_indexes = [
self.lib_ref.table_proxy_model.mapToSource(i) for i in selected_books] self.lib_ref.tableProxyModel.mapToSource(i) for i in selected_books]
return selected_indexes return selected_indexes
@@ -437,12 +437,12 @@ class MainUI(QtWidgets.QMainWindow, mainwindow.Ui_MainWindow):
# Persistent model indexes are required beause deletion mutates the model # Persistent model indexes are required beause deletion mutates the model
# Generate and delete by persistent index # Generate and delete by persistent index
delete_hashes = [ delete_hashes = [
self.lib_ref.view_model.data( self.lib_ref.libraryModel.data(
i, QtCore.Qt.UserRole + 6) for i in selected_indexes] i, QtCore.Qt.UserRole + 6) for i in selected_indexes]
persistent_indexes = [QtCore.QPersistentModelIndex(i) for i in selected_indexes] persistent_indexes = [QtCore.QPersistentModelIndex(i) for i in selected_indexes]
for i in persistent_indexes: for i in persistent_indexes:
self.lib_ref.view_model.removeRow(i.row()) self.lib_ref.libraryModel.removeRow(i.row())
# Update the database in the background # Update the database in the background
self.thread = BackGroundBookDeletion( self.thread = BackGroundBookDeletion(
@@ -484,7 +484,7 @@ class MainUI(QtWidgets.QMainWindow, mainwindow.Ui_MainWindow):
self.lib_ref.generate_library_tags() self.lib_ref.generate_library_tags()
self.statusMessage.setText( self.statusMessage.setText(
str(self.lib_ref.item_proxy_model.rowCount()) + str(self.lib_ref.itemProxyModel.rowCount()) +
self._translate('Main_UI', ' books')) self._translate('Main_UI', ' books'))
if not self.settings['perform_culling']: if not self.settings['perform_culling']:
@@ -522,11 +522,11 @@ class MainUI(QtWidgets.QMainWindow, mainwindow.Ui_MainWindow):
self.bookToolBar.hide() self.bookToolBar.hide()
self.libraryToolBar.show() self.libraryToolBar.show()
if self.lib_ref.item_proxy_model: if self.lib_ref.itemProxyModel:
# Making the proxy model available doesn't affect # Making the proxy model available doesn't affect
# memory utilization at all. Bleh. # memory utilization at all. Bleh.
self.statusMessage.setText( self.statusMessage.setText(
str(self.lib_ref.item_proxy_model.rowCount()) + str(self.lib_ref.itemProxyModel.rowCount()) +
self._translate('Main_UI', ' Books')) self._translate('Main_UI', ' Books'))
else: else:
@@ -610,11 +610,11 @@ class MainUI(QtWidgets.QMainWindow, mainwindow.Ui_MainWindow):
sender = self.sender().objectName() sender = self.sender().objectName()
if sender == 'listView': if sender == 'listView':
source_index = self.lib_ref.item_proxy_model.mapToSource(index) source_index = self.lib_ref.itemProxyModel.mapToSource(index)
elif sender == 'tableView': elif sender == 'tableView':
source_index = self.lib_ref.table_proxy_model.mapToSource(index) source_index = self.lib_ref.tableProxyModel.mapToSource(index)
item = self.lib_ref.view_model.item(source_index.row(), 0) item = self.lib_ref.libraryModel.item(source_index.row(), 0)
metadata = item.data(QtCore.Qt.UserRole + 3) metadata = item.data(QtCore.Qt.UserRole + 3)
path = {metadata['path']: metadata['hash']} path = {metadata['path']: metadata['hash']}
@@ -731,7 +731,7 @@ class MainUI(QtWidgets.QMainWindow, mainwindow.Ui_MainWindow):
if not index.isValid(): if not index.isValid():
return return
# It's worth remembering that these are indexes of the view_model # It's worth remembering that these are indexes of the libraryModel
# and NOT of the proxy models # and NOT of the proxy models
selected_indexes = self.get_selection(self.sender()) selected_indexes = self.get_selection(self.sender())
@@ -762,28 +762,28 @@ class MainUI(QtWidgets.QMainWindow, mainwindow.Ui_MainWindow):
if action == openAction: if action == openAction:
books_to_open = {} books_to_open = {}
for i in selected_indexes: for i in selected_indexes:
metadata = self.lib_ref.view_model.data(i, QtCore.Qt.UserRole + 3) metadata = self.lib_ref.libraryModel.data(i, QtCore.Qt.UserRole + 3)
books_to_open[metadata['path']] = metadata['hash'] books_to_open[metadata['path']] = metadata['hash']
self.open_files(books_to_open) self.open_files(books_to_open)
if action == editAction: if action == editAction:
edit_book = selected_indexes[0] edit_book = selected_indexes[0]
metadata = self.lib_ref.view_model.data( metadata = self.lib_ref.libraryModel.data(
edit_book, QtCore.Qt.UserRole + 3) edit_book, QtCore.Qt.UserRole + 3)
is_cover_loaded = self.lib_ref.view_model.data( is_cover_loaded = self.lib_ref.libraryModel.data(
edit_book, QtCore.Qt.UserRole + 8) edit_book, QtCore.Qt.UserRole + 8)
# Loads a cover in case culling is enabled and the table view is visible # Loads a cover in case culling is enabled and the table view is visible
if not is_cover_loaded: if not is_cover_loaded:
book_hash = self.lib_ref.view_model.data( book_hash = self.lib_ref.libraryModel.data(
edit_book, QtCore.Qt.UserRole + 6) edit_book, QtCore.Qt.UserRole + 6)
book_item = self.lib_ref.view_model.item(edit_book.row()) book_item = self.lib_ref.libraryModel.item(edit_book.row())
book_cover = database.DatabaseFunctions( book_cover = database.DatabaseFunctions(
self.database_path).fetch_covers_only([book_hash])[0][1] self.database_path).fetch_covers_only([book_hash])[0][1]
self.cover_functions.cover_loader(book_item, book_cover) self.cover_functions.cover_loader(book_item, book_cover)
cover = self.lib_ref.view_model.item(edit_book.row()).icon() cover = self.lib_ref.libraryModel.item(edit_book.row()).icon()
title = metadata['title'] title = metadata['title']
author = metadata['author'] author = metadata['author']
year = str(metadata['year']) year = str(metadata['year'])
@@ -799,8 +799,8 @@ class MainUI(QtWidgets.QMainWindow, mainwindow.Ui_MainWindow):
if action == readAction or action == unreadAction: if action == readAction or action == unreadAction:
for i in selected_indexes: for i in selected_indexes:
metadata = self.lib_ref.view_model.data(i, QtCore.Qt.UserRole + 3) metadata = self.lib_ref.libraryModel.data(i, QtCore.Qt.UserRole + 3)
book_hash = self.lib_ref.view_model.data(i, QtCore.Qt.UserRole + 6) book_hash = self.lib_ref.libraryModel.data(i, QtCore.Qt.UserRole + 6)
position = metadata['position'] position = metadata['position']
if position: if position:
@@ -824,9 +824,9 @@ class MainUI(QtWidgets.QMainWindow, mainwindow.Ui_MainWindow):
last_accessed_time = QtCore.QDateTime().currentDateTime() last_accessed_time = QtCore.QDateTime().currentDateTime()
position_perc = 1 position_perc = 1
self.lib_ref.view_model.setData(i, metadata, QtCore.Qt.UserRole + 3) self.lib_ref.libraryModel.setData(i, metadata, QtCore.Qt.UserRole + 3)
self.lib_ref.view_model.setData(i, position_perc, QtCore.Qt.UserRole + 7) self.lib_ref.libraryModel.setData(i, position_perc, QtCore.Qt.UserRole + 7)
self.lib_ref.view_model.setData(i, last_accessed_time, QtCore.Qt.UserRole + 12) self.lib_ref.libraryModel.setData(i, last_accessed_time, QtCore.Qt.UserRole + 12)
self.lib_ref.update_proxymodels() self.lib_ref.update_proxymodels()
database_dict = { database_dict = {

View File

@@ -340,6 +340,8 @@ class PliantQTextBrowser(QtWidgets.QTextBrowser):
self.ignore_wheel_event = False self.ignore_wheel_event = False
self.ignore_wheel_event_number = 0 self.ignore_wheel_event_number = 0
self.at_end = False
def wheelEvent(self, event): def wheelEvent(self, event):
self.record_position() self.record_position()
self.common_functions.wheelEvent(event) self.common_functions.wheelEvent(event)
@@ -348,8 +350,11 @@ class PliantQTextBrowser(QtWidgets.QTextBrowser):
QtWidgets.QTextEdit.keyPressEvent(self, event) QtWidgets.QTextEdit.keyPressEvent(self, event)
if event.key() == QtCore.Qt.Key_Space: if event.key() == QtCore.Qt.Key_Space:
if self.verticalScrollBar().value() == self.verticalScrollBar().maximum(): if self.verticalScrollBar().value() == self.verticalScrollBar().maximum():
self.common_functions.change_chapter(1, True) if self.at_end: # This makes sure the last lines of the chapter don't get skipped
self.common_functions.change_chapter(1, True)
self.at_end = True
else: else:
self.at_end = False
self.set_top_line_cleanly() self.set_top_line_cleanly()
self.record_position() self.record_position()
@@ -530,10 +535,10 @@ class PliantWidgetsCommonFunctions:
# Set a baseline model index in case the item gets deleted # Set a baseline model index in case the item gets deleted
# E.g It's open in a tab and deleted from the library # E.g It's open in a tab and deleted from the library
model_index = None model_index = None
start_index = self.main_window.lib_ref.view_model.index(0, 0) start_index = self.main_window.lib_ref.libraryModel.index(0, 0)
# Find index of the model item that corresponds to the tab # Find index of the model item that corresponds to the tab
model_index = self.main_window.lib_ref.view_model.match( model_index = self.main_window.lib_ref.libraryModel.match(
start_index, start_index,
QtCore.Qt.UserRole + 6, QtCore.Qt.UserRole + 6,
self.pw.parent.metadata['hash'], self.pw.parent.metadata['hash'],
@@ -548,7 +553,7 @@ class PliantWidgetsCommonFunctions:
# Update position percentage # Update position percentage
if model_index: if model_index:
self.main_window.lib_ref.view_model.setData( self.main_window.lib_ref.libraryModel.setData(
model_index[0], position_percentage, QtCore.Qt.UserRole + 7) model_index[0], position_percentage, QtCore.Qt.UserRole + 7)
def generate_combo_box_action(self, contextMenu): def generate_combo_box_action(self, contextMenu):

View File

@@ -51,8 +51,8 @@ class CoverLoadingAndCulling:
# listView to go blank on a resize # listView to go blank on a resize
all_indexes = set() all_indexes = set()
for i in range(self.lib_ref.item_proxy_model.rowCount()): for i in range(self.lib_ref.itemProxyModel.rowCount()):
all_indexes.add(self.lib_ref.item_proxy_model.index(i, 0)) all_indexes.add(self.lib_ref.itemProxyModel.index(i, 0))
y_range = list(range(0, self.listView.viewport().height(), 100)) y_range = list(range(0, self.listView.viewport().height(), 100))
y_range.extend((-20, self.listView.viewport().height() + 20)) y_range.extend((-20, self.listView.viewport().height() + 20))
@@ -66,8 +66,8 @@ class CoverLoadingAndCulling:
invisible_indexes = all_indexes - visible_indexes invisible_indexes = all_indexes - visible_indexes
for i in invisible_indexes: for i in invisible_indexes:
model_index = self.lib_ref.item_proxy_model.mapToSource(i) model_index = self.lib_ref.itemProxyModel.mapToSource(i)
this_item = self.lib_ref.view_model.item(model_index.row()) this_item = self.lib_ref.libraryModel.item(model_index.row())
if this_item: if this_item:
this_item.setIcon(QtGui.QIcon(blank_pixmap)) this_item.setIcon(QtGui.QIcon(blank_pixmap))
@@ -76,11 +76,11 @@ class CoverLoadingAndCulling:
hash_index_dict = {} hash_index_dict = {}
hash_list = [] hash_list = []
for i in visible_indexes: for i in visible_indexes:
model_index = self.lib_ref.item_proxy_model.mapToSource(i) model_index = self.lib_ref.itemProxyModel.mapToSource(i)
book_hash = self.lib_ref.view_model.data( book_hash = self.lib_ref.libraryModel.data(
model_index, QtCore.Qt.UserRole + 6) model_index, QtCore.Qt.UserRole + 6)
cover_displayed = self.lib_ref.view_model.data( cover_displayed = self.lib_ref.libraryModel.data(
model_index, QtCore.Qt.UserRole + 8) model_index, QtCore.Qt.UserRole + 8)
if book_hash and not cover_displayed: if book_hash and not cover_displayed:
@@ -95,7 +95,7 @@ class CoverLoadingAndCulling:
cover = i[1] cover = i[1]
model_index = hash_index_dict[book_hash] model_index = hash_index_dict[book_hash]
book_item = self.lib_ref.view_model.item(model_index.row()) book_item = self.lib_ref.libraryModel.item(model_index.row())
self.cover_loader(book_item, cover) self.cover_loader(book_item, cover)
def load_all_covers(self): def load_all_covers(self):
@@ -112,8 +112,8 @@ class CoverLoadingAndCulling:
all_covers = { all_covers = {
i[0]: i[1] for i in all_covers_db} i[0]: i[1] for i in all_covers_db}
for i in range(self.lib_ref.view_model.rowCount()): for i in range(self.lib_ref.libraryModel.rowCount()):
this_item = self.lib_ref.view_model.item(i, 0) this_item = self.lib_ref.libraryModel.item(i, 0)
is_cover_already_displayed = this_item.data(QtCore.Qt.UserRole + 8) is_cover_already_displayed = this_item.data(QtCore.Qt.UserRole + 8)
if is_cover_already_displayed: if is_cover_already_displayed:

View File

@@ -28,19 +28,19 @@ from lector.models import TableProxyModel, ItemProxyModel
class Library: class Library:
def __init__(self, parent): def __init__(self, parent):
self.parent = parent self.main_window = parent
self.view_model = None self.libraryModel = None
self.item_proxy_model = None self.itemProxyModel = None
self.table_proxy_model = None self.tableProxyModel = None
self._translate = QtCore.QCoreApplication.translate self._translate = QtCore.QCoreApplication.translate
def generate_model(self, mode, parsed_books=None, is_database_ready=True): def generate_model(self, mode, parsed_books=None, is_database_ready=True):
if mode == 'build': if mode == 'build':
self.view_model = QtGui.QStandardItemModel() self.libraryModel = QtGui.QStandardItemModel()
self.view_model.setColumnCount(10) self.libraryModel.setColumnCount(10)
books = database.DatabaseFunctions( books = database.DatabaseFunctions(
self.parent.database_path).fetch_data( self.main_window.database_path).fetch_data(
('Title', 'Author', 'Year', 'DateAdded', 'Path', ('Title', 'Author', 'Year', 'DateAdded', 'Path',
'Position', 'ISBN', 'Tags', 'Hash', 'LastAccessed', 'Position', 'ISBN', 'Tags', 'Hash', 'LastAccessed',
'Addition'), 'Addition'),
@@ -53,7 +53,7 @@ class Library:
return return
elif mode == 'addition': elif mode == 'addition':
# Assumes self.view_model already exists and may be extended # Assumes self.libraryModel already exists and may be extended
# Because any additional books have already been added to the # Because any additional books have already been added to the
# database using background threads # database using background threads
@@ -164,57 +164,57 @@ class Library:
item.setData(last_accessed, QtCore.Qt.UserRole + 12) item.setData(last_accessed, QtCore.Qt.UserRole + 12)
item.setIcon(QtGui.QIcon(img_pixmap)) item.setIcon(QtGui.QIcon(img_pixmap))
self.view_model.appendRow(item) self.libraryModel.appendRow(item)
# The is_database_ready boolean is required when a new thread sends # The is_database_ready boolean is required when a new thread sends
# books here for model generation. # books here for model generation.
if not self.parent.settings['perform_culling'] and is_database_ready: if not self.main_window.settings['perform_culling'] and is_database_ready:
self.parent.cover_functions.load_all_covers() self.main_window.cover_functions.load_all_covers()
def generate_proxymodels(self): def generate_proxymodels(self):
self.item_proxy_model = ItemProxyModel() self.itemProxyModel = ItemProxyModel()
self.item_proxy_model.setSourceModel(self.view_model) self.itemProxyModel.setSourceModel(self.libraryModel)
self.item_proxy_model.setSortCaseSensitivity(False) self.itemProxyModel.setSortCaseSensitivity(False)
s = QtCore.QSize(160, 250) # Set icon sizing here s = QtCore.QSize(160, 250) # Set icon sizing here
self.parent.listView.setIconSize(s) self.main_window.listView.setIconSize(s)
self.parent.listView.setModel(self.item_proxy_model) self.main_window.listView.setModel(self.itemProxyModel)
self.table_proxy_model = TableProxyModel( self.tableProxyModel = TableProxyModel(
self.parent.temp_dir.path(), self.main_window.temp_dir.path(),
self.parent.tableView.horizontalHeader(), self.main_window.tableView.horizontalHeader(),
self.parent.settings['consider_read_at']) self.main_window.settings['consider_read_at'])
self.table_proxy_model.setSourceModel(self.view_model) self.tableProxyModel.setSourceModel(self.libraryModel)
self.table_proxy_model.setSortCaseSensitivity(False) self.tableProxyModel.setSortCaseSensitivity(False)
self.parent.tableView.setModel(self.table_proxy_model) self.main_window.tableView.setModel(self.tableProxyModel)
self.update_proxymodels() self.update_proxymodels()
def update_proxymodels(self): def update_proxymodels(self):
# Table proxy model # Table proxy model
self.table_proxy_model.invalidateFilter() self.tableProxyModel.invalidateFilter()
self.table_proxy_model.setFilterParams( self.tableProxyModel.setFilterParams(
self.parent.libraryToolBar.searchBar.text(), self.main_window.libraryToolBar.searchBar.text(),
self.parent.active_library_filters, self.main_window.active_library_filters,
0) # This doesn't need to know the sorting box position 0) # This doesn't need to know the sorting box position
self.table_proxy_model.setFilterFixedString( self.tableProxyModel.setFilterFixedString(
self.parent.libraryToolBar.searchBar.text()) self.main_window.libraryToolBar.searchBar.text())
# ^^^ This isn't needed, but it forces a model update every time the # ^^^ This isn't needed, but it forces a model update every time the
# text in the line edit changes. So I guess it is needed. # text in the line edit changes. So I guess it is needed.
self.table_proxy_model.sort_table_columns( self.tableProxyModel.sort_table_columns(
self.parent.tableView.horizontalHeader().sortIndicatorSection()) self.main_window.tableView.horizontalHeader().sortIndicatorSection())
self.table_proxy_model.sort_table_columns() self.tableProxyModel.sort_table_columns()
# Item proxy model # Item proxy model
self.item_proxy_model.invalidateFilter() self.itemProxyModel.invalidateFilter()
self.item_proxy_model.setFilterParams( self.itemProxyModel.setFilterParams(
self.parent.libraryToolBar.searchBar.text(), self.main_window.libraryToolBar.searchBar.text(),
self.parent.active_library_filters, self.main_window.active_library_filters,
self.parent.libraryToolBar.sortingBox.currentIndex()) self.main_window.libraryToolBar.sortingBox.currentIndex())
self.item_proxy_model.setFilterFixedString( self.itemProxyModel.setFilterFixedString(
self.parent.libraryToolBar.searchBar.text()) self.main_window.libraryToolBar.searchBar.text())
self.parent.statusMessage.setText( self.main_window.statusMessage.setText(
str(self.item_proxy_model.rowCount()) + str(self.itemProxyModel.rowCount()) +
self._translate('Library', ' books')) self._translate('Library', ' books'))
# TODO # TODO
@@ -233,20 +233,20 @@ class Library:
5: 7} 5: 7}
# Sorting according to roles and the drop down in the library toolbar # Sorting according to roles and the drop down in the library toolbar
self.item_proxy_model.setSortRole( self.itemProxyModel.setSortRole(
QtCore.Qt.UserRole + sort_roles[self.parent.libraryToolBar.sortingBox.currentIndex()]) QtCore.Qt.UserRole + sort_roles[self.main_window.libraryToolBar.sortingBox.currentIndex()])
# This can be expanded to other fields by appending to the list # This can be expanded to other fields by appending to the list
sort_order = QtCore.Qt.AscendingOrder sort_order = QtCore.Qt.AscendingOrder
if self.parent.libraryToolBar.sortingBox.currentIndex() in [3, 4, 5]: if self.main_window.libraryToolBar.sortingBox.currentIndex() in [3, 4, 5]:
sort_order = QtCore.Qt.DescendingOrder sort_order = QtCore.Qt.DescendingOrder
self.item_proxy_model.sort(0, sort_order) self.itemProxyModel.sort(0, sort_order)
self.parent.start_culling_timer() self.main_window.start_culling_timer()
def generate_library_tags(self): def generate_library_tags(self):
db_library_directories = database.DatabaseFunctions( db_library_directories = database.DatabaseFunctions(
self.parent.database_path).fetch_data( self.main_window.database_path).fetch_data(
('Path', 'Name', 'Tags'), ('Path', 'Name', 'Tags'),
'directories', # This checks the directories table NOT the book one 'directories', # This checks the directories table NOT the book one
{'Path': ''}, {'Path': ''},
@@ -258,7 +258,7 @@ class Library:
else: else:
db_library_directories = database.DatabaseFunctions( db_library_directories = database.DatabaseFunctions(
self.parent.database_path).fetch_data( self.main_window.database_path).fetch_data(
('Path',), ('Path',),
'books', # THIS CHECKS THE BOOKS TABLE 'books', # THIS CHECKS THE BOOKS TABLE
{'Path': ''}, {'Path': ''},
@@ -294,8 +294,8 @@ class Library:
# Generate tags for the QStandardItemModel # Generate tags for the QStandardItemModel
# This isn't triggered for an empty view model # This isn't triggered for an empty view model
for i in range(self.view_model.rowCount()): for i in range(self.libraryModel.rowCount()):
this_item = self.view_model.item(i, 0) this_item = self.libraryModel.item(i, 0)
all_metadata = this_item.data(QtCore.Qt.UserRole + 3) all_metadata = this_item.data(QtCore.Qt.UserRole + 3)
directory_name, directory_tags = get_tags(all_metadata) directory_name, directory_tags = get_tags(all_metadata)
@@ -310,8 +310,8 @@ class Library:
invalid_paths = [] invalid_paths = []
deletable_persistent_indexes = [] deletable_persistent_indexes = []
for i in range(self.view_model.rowCount()): for i in range(self.libraryModel.rowCount()):
item = self.view_model.item(i) item = self.libraryModel.item(i)
item_metadata = item.data(QtCore.Qt.UserRole + 3) item_metadata = item.data(QtCore.Qt.UserRole + 3)
book_path = item_metadata['path'] book_path = item_metadata['path']
@@ -330,8 +330,8 @@ class Library:
if deletable_persistent_indexes: if deletable_persistent_indexes:
for i in deletable_persistent_indexes: for i in deletable_persistent_indexes:
self.view_model.removeRow(i.row()) self.libraryModel.removeRow(i.row())
# Remove invalid paths from the database as well # Remove invalid paths from the database as well
database.DatabaseFunctions( database.DatabaseFunctions(
self.parent.database_path).delete_from_database('Path', invalid_paths) self.main_window.database_path).delete_from_database('Path', invalid_paths)

View File

@@ -86,7 +86,7 @@ class MetadataUI(QtWidgets.QDialog, metadata.Ui_Dialog):
self.coverView.setScene(graphics_scene) self.coverView.setScene(graphics_scene)
def ok_pressed(self, event=None): def ok_pressed(self, event=None):
book_item = self.parent.lib_ref.view_model.item(self.book_index.row()) book_item = self.parent.lib_ref.libraryModel.item(self.book_index.row())
title = self.titleLine.text() title = self.titleLine.text()
author = self.authorLine.text() author = self.authorLine.text()

View File

@@ -40,15 +40,15 @@ class SettingsUI(QtWidgets.QDialog, settingswindow.Ui_Dialog):
self.verticalLayout_4.setContentsMargins(0, 0, 0, 0) self.verticalLayout_4.setContentsMargins(0, 0, 0, 0)
self._translate = QtCore.QCoreApplication.translate self._translate = QtCore.QCoreApplication.translate
self.parent = parent self.main_window = parent
self.database_path = self.parent.database_path self.database_path = self.main_window.database_path
self.image_factory = self.parent.QImageFactory self.image_factory = self.main_window.QImageFactory
# The annotation dialog will use the settings dialog as its parent # The annotation dialog will use the settings dialog as its parent
self.annotationsDialog = AnnotationsUI(self) self.annotationsDialog = AnnotationsUI(self)
self.resize(self.parent.settings['settings_dialog_size']) self.resize(self.main_window.settings['settings_dialog_size'])
self.move(self.parent.settings['settings_dialog_position']) self.move(self.main_window.settings['settings_dialog_position'])
install_dir = os.path.realpath(__file__) install_dir = os.path.realpath(__file__)
install_dir = pathlib.Path(install_dir).parents[1] install_dir = pathlib.Path(install_dir).parents[1]
@@ -58,7 +58,7 @@ class SettingsUI(QtWidgets.QDialog, settingswindow.Ui_Dialog):
self.paths = None self.paths = None
self.thread = None self.thread = None
self.filesystem_model = None self.filesystemModel = None
self.tag_data_copy = None self.tag_data_copy = None
english_string = self._translate('SettingsUI', 'English') english_string = self._translate('SettingsUI', 'English')
@@ -67,7 +67,7 @@ class SettingsUI(QtWidgets.QDialog, settingswindow.Ui_Dialog):
languages = [english_string, spanish_string, hindi_string] languages = [english_string, spanish_string, hindi_string]
self.languageBox.addItems(languages) self.languageBox.addItems(languages)
current_language = self.parent.settings['dictionary_language'] current_language = self.main_window.settings['dictionary_language']
if current_language == 'en': if current_language == 'en':
self.languageBox.setCurrentIndex(0) self.languageBox.setCurrentIndex(0)
elif current_language == 'es': elif current_language == 'es':
@@ -82,7 +82,7 @@ class SettingsUI(QtWidgets.QDialog, settingswindow.Ui_Dialog):
self.cancelButton.clicked.connect(self.cancel_pressed) self.cancelButton.clicked.connect(self.cancel_pressed)
# Radio buttons # Radio buttons
if self.parent.settings['icon_theme'] == 'DarkIcons': if self.main_window.settings['icon_theme'] == 'DarkIcons':
self.darkIconsRadio.setChecked(True) self.darkIconsRadio.setChecked(True)
else: else:
self.lightIconsRadio.setChecked(True) self.lightIconsRadio.setChecked(True)
@@ -90,15 +90,15 @@ class SettingsUI(QtWidgets.QDialog, settingswindow.Ui_Dialog):
self.lightIconsRadio.clicked.connect(self.change_icon_theme) self.lightIconsRadio.clicked.connect(self.change_icon_theme)
# Check boxes # Check boxes
self.autoTags.setChecked(self.parent.settings['auto_tags']) self.autoTags.setChecked(self.main_window.settings['auto_tags'])
self.coverShadows.setChecked(self.parent.settings['cover_shadows']) self.coverShadows.setChecked(self.main_window.settings['cover_shadows'])
self.refreshLibrary.setChecked(self.parent.settings['scan_library']) self.refreshLibrary.setChecked(self.main_window.settings['scan_library'])
self.fileRemember.setChecked(self.parent.settings['remember_files']) self.fileRemember.setChecked(self.main_window.settings['remember_files'])
self.performCulling.setChecked(self.parent.settings['perform_culling']) self.performCulling.setChecked(self.main_window.settings['perform_culling'])
self.cachingEnabled.setChecked(self.parent.settings['caching_enabled']) self.cachingEnabled.setChecked(self.main_window.settings['caching_enabled'])
self.hideScrollBars.setChecked(self.parent.settings['hide_scrollbars']) self.hideScrollBars.setChecked(self.main_window.settings['hide_scrollbars'])
self.scrollSpeedSlider.setValue(self.parent.settings['scroll_speed']) self.scrollSpeedSlider.setValue(self.main_window.settings['scroll_speed'])
self.readAtPercent.setValue(self.parent.settings['consider_read_at']) self.readAtPercent.setValue(self.main_window.settings['consider_read_at'])
self.autoTags.clicked.connect(self.manage_checkboxes) self.autoTags.clicked.connect(self.manage_checkboxes)
self.coverShadows.clicked.connect(self.manage_checkboxes) self.coverShadows.clicked.connect(self.manage_checkboxes)
@@ -166,7 +166,7 @@ class SettingsUI(QtWidgets.QDialog, settingswindow.Ui_Dialog):
{'Path': ''}, {'Path': ''},
'LIKE') 'LIKE')
self.parent.generate_library_filter_menu(paths) self.main_window.generate_library_filter_menu(paths)
directory_data = {} directory_data = {}
if not paths: if not paths:
print('Database: No paths for settings...') print('Database: No paths for settings...')
@@ -179,9 +179,9 @@ class SettingsUI(QtWidgets.QDialog, settingswindow.Ui_Dialog):
'tags': i[2], 'tags': i[2],
'check_state': i[3]} 'check_state': i[3]}
self.filesystem_model = MostExcellentFileSystemModel(directory_data) self.filesystemModel = MostExcellentFileSystemModel(directory_data)
self.filesystem_model.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.Dirs) self.filesystemModel.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.Dirs)
self.treeView.setModel(self.filesystem_model) self.treeView.setModel(self.filesystemModel)
# TODO # TODO
# This here might break on them pestilent non unixy OSes # This here might break on them pestilent non unixy OSes
@@ -189,7 +189,7 @@ class SettingsUI(QtWidgets.QDialog, settingswindow.Ui_Dialog):
root_directory = QtCore.QDir().rootPath() root_directory = QtCore.QDir().rootPath()
self.treeView.setRootIndex( self.treeView.setRootIndex(
self.filesystem_model.setRootPath(root_directory)) self.filesystemModel.setRootPath(root_directory))
# Set the treeView and QFileSystemModel to its desired state # Set the treeView and QFileSystemModel to its desired state
selected_paths = [ selected_paths = [
@@ -211,10 +211,10 @@ class SettingsUI(QtWidgets.QDialog, settingswindow.Ui_Dialog):
expand_paths.remove(root_directory) expand_paths.remove(root_directory)
for i in expand_paths: for i in expand_paths:
this_index = self.filesystem_model.index(i) this_index = self.filesystemModel.index(i)
self.treeView.expand(this_index) self.treeView.expand(this_index)
header_sizes = self.parent.settings['settings_dialog_headers'] header_sizes = self.main_window.settings['settings_dialog_headers']
if header_sizes: if header_sizes:
for count, i in enumerate((0, 4)): for count, i in enumerate((0, 4)):
self.treeView.setColumnWidth(i, int(header_sizes[count])) self.treeView.setColumnWidth(i, int(header_sizes[count]))
@@ -232,7 +232,7 @@ class SettingsUI(QtWidgets.QDialog, settingswindow.Ui_Dialog):
self.hide() self.hide()
data_pairs = [] data_pairs = []
for i in self.filesystem_model.tag_data.items(): for i in self.filesystemModel.tag_data.items():
data_pairs.append([ data_pairs.append([
i[0], i[1]['name'], i[1]['tags'], i[1]['check_state'] i[0], i[1]['name'], i[1]['tags'], i[1]['check_state']
]) ])
@@ -250,24 +250,24 @@ class SettingsUI(QtWidgets.QDialog, settingswindow.Ui_Dialog):
database.DatabaseFunctions( database.DatabaseFunctions(
self.database_path).delete_from_database('*', '*') self.database_path).delete_from_database('*', '*')
self.parent.lib_ref.generate_model('build') self.main_window.lib_ref.generate_model('build')
self.parent.lib_ref.generate_proxymodels() self.main_window.lib_ref.generate_proxymodels()
self.parent.generate_library_filter_menu() self.main_window.generate_library_filter_menu()
return return
# Update the main window library filter menu # Update the main window library filter menu
self.parent.generate_library_filter_menu(data_pairs) self.main_window.generate_library_filter_menu(data_pairs)
self.parent.set_library_filter() self.main_window.set_library_filter()
# Disallow rechecking until the first check completes # Disallow rechecking until the first check completes
self.okButton.setEnabled(False) self.okButton.setEnabled(False)
self.parent.libraryToolBar.reloadLibraryButton.setEnabled(False) self.main_window.libraryToolBar.reloadLibraryButton.setEnabled(False)
self.okButton.setToolTip( self.okButton.setToolTip(
self._translate('SettingsUI', 'Library scan in progress...')) self._translate('SettingsUI', 'Library scan in progress...'))
# Traverse directories looking for files # Traverse directories looking for files
self.parent.statusMessage.setText( self.main_window.statusMessage.setText(
self._translate('SettingsUI', 'Checking library folders')) self._translate('SettingsUI', 'Checking library folders'))
self.thread = BackGroundBookSearch(data_pairs) self.thread = BackGroundBookSearch(data_pairs)
self.thread.finished.connect(self.finished_iterating) self.thread.finished.connect(self.finished_iterating)
@@ -277,19 +277,19 @@ class SettingsUI(QtWidgets.QDialog, settingswindow.Ui_Dialog):
# The books the search thread has found # The books the search thread has found
# are now in self.thread.valid_files # are now in self.thread.valid_files
if not self.thread.valid_files: if not self.thread.valid_files:
self.parent.move_on() self.main_window.move_on()
return return
# Hey, messaging is important, okay? # Hey, messaging is important, okay?
self.parent.statusBar.setVisible(True) self.main_window.statusBar.setVisible(True)
self.parent.sorterProgress.setVisible(True) self.main_window.sorterProgress.setVisible(True)
self.parent.statusMessage.setText( self.main_window.statusMessage.setText(
self._translate('SettingsUI', 'Parsing files')) self._translate('SettingsUI', 'Parsing files'))
# We now create a new thread to put those files into the database # We now create a new thread to put those files into the database
self.thread = BackGroundBookAddition( self.thread = BackGroundBookAddition(
self.thread.valid_files, self.database_path, 'automatic', self.parent) self.thread.valid_files, self.database_path, 'automatic', self.main_window)
self.thread.finished.connect(self.parent.move_on) self.thread.finished.connect(self.main_window.move_on)
self.thread.start() self.thread.start()
def page_switch(self, index): def page_switch(self, index):
@@ -300,7 +300,7 @@ class SettingsUI(QtWidgets.QDialog, settingswindow.Ui_Dialog):
self.okButton.setVisible(False) self.okButton.setVisible(False)
def cancel_pressed(self): def cancel_pressed(self):
self.filesystem_model.tag_data = copy.deepcopy(self.tag_data_copy) self.filesystemModel.tag_data = copy.deepcopy(self.tag_data_copy)
self.hide() self.hide()
def hideEvent(self, event): def hideEvent(self, event):
@@ -309,41 +309,42 @@ class SettingsUI(QtWidgets.QDialog, settingswindow.Ui_Dialog):
def showEvent(self, event): def showEvent(self, event):
self.format_preview() self.format_preview()
self.tag_data_copy = copy.deepcopy(self.filesystem_model.tag_data) self.tag_data_copy = copy.deepcopy(self.filesystemModel.tag_data)
event.accept() event.accept()
def no_more_settings(self): def no_more_settings(self):
self.parent.libraryToolBar.settingsButton.setChecked(False) self.main_window.libraryToolBar.settingsButton.setChecked(False)
self.gather_annotations() self.gather_annotations()
Settings(self.parent).save_settings() Settings(self.main_window).save_settings()
self.resizeEvent() self.resizeEvent()
def resizeEvent(self, event=None): def resizeEvent(self, event=None):
self.parent.settings['settings_dialog_size'] = self.size() self.main_window.settings['settings_dialog_size'] = self.size()
self.parent.settings['settings_dialog_position'] = self.pos() self.main_window.settings['settings_dialog_position'] = self.pos()
table_headers = [] table_headers = []
for i in [0, 4]: for i in [0, 4]:
table_headers.append(self.treeView.columnWidth(i)) table_headers.append(self.treeView.columnWidth(i))
self.parent.settings['settings_dialog_headers'] = table_headers self.main_window.settings['settings_dialog_headers'] = table_headers
def change_icon_theme(self): def change_icon_theme(self):
if self.sender() == self.darkIconsRadio: if self.sender() == self.darkIconsRadio:
self.parent.settings['icon_theme'] = 'DarkIcons' self.main_window.settings['icon_theme'] = 'DarkIcons'
else: else:
self.parent.settings['icon_theme'] = 'LightIcons' self.main_window.settings['icon_theme'] = 'LightIcons'
def change_dictionary_language(self, event): def change_dictionary_language(self, event):
language_dict = { language_dict = {
0: 'en', 0: 'en',
1: 'es', 1: 'es',
2: 'hi'} 2: 'hi'}
self.parent.settings['dictionary_language'] = language_dict[self.languageBox.currentIndex()] self.main_window.settings[
'dictionary_language'] = language_dict[self.languageBox.currentIndex()]
def change_scroll_speed(self, event=None): def change_scroll_speed(self, event=None):
self.parent.settings['scroll_speed'] = self.scrollSpeedSlider.value() self.main_window.settings['scroll_speed'] = self.scrollSpeedSlider.value()
def change_read_at(self, event=None): def change_read_at(self, event=None):
self.parent.settings['consider_read_at'] = self.readAtPercent.value() self.main_window.settings['consider_read_at'] = self.readAtPercent.value()
def manage_checkboxes(self, event=None): def manage_checkboxes(self, event=None):
sender = self.sender().objectName() sender = self.sender().objectName()
@@ -357,13 +358,14 @@ class SettingsUI(QtWidgets.QDialog, settingswindow.Ui_Dialog):
'cachingEnabled': 'caching_enabled', 'cachingEnabled': 'caching_enabled',
'hideScrollBars': 'hide_scrollbars'} 'hideScrollBars': 'hide_scrollbars'}
self.parent.settings[sender_dict[sender]] = not self.parent.settings[sender_dict[sender]] self.main_window.settings[
sender_dict[sender]] = not self.main_window.settings[sender_dict[sender]]
if not self.performCulling.isChecked(): if not self.performCulling.isChecked():
self.parent.cover_functions.load_all_covers() self.main_window.cover_functions.load_all_covers()
def generate_annotations(self): def generate_annotations(self):
saved_annotations = self.parent.settings['annotations'] saved_annotations = self.main_window.settings['annotations']
for i in saved_annotations: for i in saved_annotations:
item = QtGui.QStandardItem() item = QtGui.QStandardItem()
@@ -379,8 +381,8 @@ class SettingsUI(QtWidgets.QDialog, settingswindow.Ui_Dialog):
self.previewView.setTextCursor(cursor) self.previewView.setTextCursor(cursor)
self.previewView.setText('Vidistine nuper imagines moventes bonas?') self.previewView.setText('Vidistine nuper imagines moventes bonas?')
profile_index = self.parent.bookToolBar.profileBox.currentIndex() profile_index = self.main_window.bookToolBar.profileBox.currentIndex()
current_profile = self.parent.bookToolBar.profileBox.itemData( current_profile = self.main_window.bookToolBar.profileBox.itemData(
profile_index, QtCore.Qt.UserRole) profile_index, QtCore.Qt.UserRole)
if not current_profile: if not current_profile:
@@ -457,4 +459,4 @@ class SettingsUI(QtWidgets.QDialog, settingswindow.Ui_Dialog):
annotation_data = annotation_item.data(QtCore.Qt.UserRole) annotation_data = annotation_item.data(QtCore.Qt.UserRole)
annotations_out.append(annotation_data) annotations_out.append(annotation_data)
self.parent.settings['annotations'] = annotations_out self.main_window.settings['annotations'] = annotations_out

View File

@@ -135,8 +135,8 @@ class Tab(QtWidgets.QWidget):
self.dockListView.clicked.connect(self.navigate_to_bookmark) self.dockListView.clicked.connect(self.navigate_to_bookmark)
self.dockWidget.setWidget(self.dockListView) self.dockWidget.setWidget(self.dockListView)
self.bookmark_model = QtGui.QStandardItemModel(self) self.bookmarkModel = QtGui.QStandardItemModel(self)
self.proxy_model = BookmarkProxyModel(self) self.bookmarkProxyModel = BookmarkProxyModel(self)
self.generate_bookmark_model() self.generate_bookmark_model()
self.generate_keyboard_shortcuts() self.generate_keyboard_shortcuts()
@@ -169,15 +169,15 @@ class Tab(QtWidgets.QWidget):
def update_last_accessed_time(self): def update_last_accessed_time(self):
self.metadata['last_accessed'] = QtCore.QDateTime().currentDateTime() self.metadata['last_accessed'] = QtCore.QDateTime().currentDateTime()
start_index = self.main_window.lib_ref.view_model.index(0, 0) start_index = self.main_window.lib_ref.libraryModel.index(0, 0)
matching_item = self.main_window.lib_ref.view_model.match( matching_item = self.main_window.lib_ref.libraryModel.match(
start_index, start_index,
QtCore.Qt.UserRole + 6, QtCore.Qt.UserRole + 6,
self.metadata['hash'], self.metadata['hash'],
1, QtCore.Qt.MatchExactly) 1, QtCore.Qt.MatchExactly)
try: try:
self.main_window.lib_ref.view_model.setData( self.main_window.lib_ref.libraryModel.setData(
matching_item[0], self.metadata['last_accessed'], QtCore.Qt.UserRole + 12) matching_item[0], self.metadata['last_accessed'], QtCore.Qt.UserRole + 12)
except IndexError: # The file has been deleted except IndexError: # The file has been deleted
pass pass
@@ -408,15 +408,15 @@ class Tab(QtWidgets.QWidget):
bookmark.setData(cursor_position, QtCore.Qt.UserRole + 1) bookmark.setData(cursor_position, QtCore.Qt.UserRole + 1)
bookmark.setData(identifier, QtCore.Qt.UserRole + 2) bookmark.setData(identifier, QtCore.Qt.UserRole + 2)
self.bookmark_model.appendRow(bookmark) self.bookmarkModel.appendRow(bookmark)
self.update_bookmark_proxy_model() self.update_bookmark_proxy_model()
def navigate_to_bookmark(self, index): def navigate_to_bookmark(self, index):
if not index.isValid(): if not index.isValid():
return return
chapter = self.proxy_model.data(index, QtCore.Qt.UserRole) chapter = self.bookmarkProxyModel.data(index, QtCore.Qt.UserRole)
cursor_position = self.proxy_model.data(index, QtCore.Qt.UserRole + 1) cursor_position = self.bookmarkProxyModel.data(index, QtCore.Qt.UserRole + 1)
self.main_window.bookToolBar.tocBox.setCurrentIndex(chapter - 1) self.main_window.bookToolBar.tocBox.setCurrentIndex(chapter - 1)
if not self.are_we_doing_images_only: if not self.are_we_doing_images_only:
@@ -444,16 +444,16 @@ class Tab(QtWidgets.QWidget):
self.generate_bookmark_proxy_model() self.generate_bookmark_proxy_model()
def generate_bookmark_proxy_model(self): def generate_bookmark_proxy_model(self):
self.proxy_model.setSourceModel(self.bookmark_model) self.bookmarkProxyModel.setSourceModel(self.bookmarkModel)
self.proxy_model.setSortCaseSensitivity(False) self.bookmarkProxyModel.setSortCaseSensitivity(False)
self.proxy_model.setSortRole(QtCore.Qt.UserRole) self.bookmarkProxyModel.setSortRole(QtCore.Qt.UserRole)
self.dockListView.setModel(self.proxy_model) self.dockListView.setModel(self.bookmarkProxyModel)
def update_bookmark_proxy_model(self): def update_bookmark_proxy_model(self):
self.proxy_model.invalidateFilter() self.bookmarkProxyModel.invalidateFilter()
self.proxy_model.setFilterParams( self.bookmarkProxyModel.setFilterParams(
self.main_window.bookToolBar.searchBar.text()) self.main_window.bookToolBar.searchBar.text())
self.proxy_model.setFilterFixedString( self.bookmarkProxyModel.setFilterFixedString(
self.main_window.bookToolBar.searchBar.text()) self.main_window.bookToolBar.searchBar.text())
def generate_bookmark_context_menu(self, position): def generate_bookmark_context_menu(self, position):
@@ -461,15 +461,15 @@ class Tab(QtWidgets.QWidget):
if not index.isValid(): if not index.isValid():
return return
bookmark_menu = QtWidgets.QMenu() bookmarkMenu = QtWidgets.QMenu()
editAction = bookmark_menu.addAction( editAction = bookmarkMenu.addAction(
self.main_window.QImageFactory.get_image('edit-rename'), self.main_window.QImageFactory.get_image('edit-rename'),
self._translate('Tab', 'Edit')) self._translate('Tab', 'Edit'))
deleteAction = bookmark_menu.addAction( deleteAction = bookmarkMenu.addAction(
self.main_window.QImageFactory.get_image('trash-empty'), self.main_window.QImageFactory.get_image('trash-empty'),
self._translate('Tab', 'Delete')) self._translate('Tab', 'Delete'))
action = bookmark_menu.exec_( action = bookmarkMenu.exec_(
self.dockListView.mapToGlobal(position)) self.dockListView.mapToGlobal(position))
if action == editAction: if action == editAction:
@@ -477,10 +477,10 @@ class Tab(QtWidgets.QWidget):
if action == deleteAction: if action == deleteAction:
row = index.row() row = index.row()
delete_uuid = self.bookmark_model.item(row).data(QtCore.Qt.UserRole + 2) delete_uuid = self.bookmarkModel.item(row).data(QtCore.Qt.UserRole + 2)
self.metadata['bookmarks'].pop(delete_uuid) self.metadata['bookmarks'].pop(delete_uuid)
self.bookmark_model.removeRow(index.row()) self.bookmarkModel.removeRow(index.row())
def hide_mouse(self): def hide_mouse(self):
self.contentView.viewport().setCursor(QtCore.Qt.BlankCursor) self.contentView.viewport().setCursor(QtCore.Qt.BlankCursor)