Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
db_manager: migrate to new style signals
  • Loading branch information
jef-n committed Mar 15, 2016
1 parent 4151a3b commit 8bda5c0
Show file tree
Hide file tree
Showing 42 changed files with 334 additions and 287 deletions.
16 changes: 8 additions & 8 deletions python/plugins/db_manager/db_manager.py
Expand Up @@ -24,9 +24,9 @@

import functools

from PyQt4.QtCore import QObject, Qt, QSettings, QByteArray, SIGNAL, QSize
from PyQt4.QtGui import QMainWindow, QApplication, QMenu, QIcon, QTabWidget, QGridLayout, QSpacerItem, QSizePolicy, \
QDockWidget, QStatusBar, QMenuBar, QToolBar, QKeySequence, QTabBar
from PyQt.QtCore import QObject, Qt, QSettings, QByteArray, QSize
from PyQt.QtWidgets import QMainWindow, QApplication, QMenu, QTabWidget, QGridLayout, QSpacerItem, QSizePolicy, QDockWidget, QStatusBar, QMenuBar, QToolBar, QTabBar
from PyQt.QtGui import QIcon, QKeySequence

from qgis.gui import QgsMessageBar
from .info_viewer import InfoViewer
Expand All @@ -52,8 +52,8 @@ def __init__(self, iface, parent=None):
self.restoreGeometry(settings.value("/DB_Manager/mainWindow/geometry", QByteArray(), type=QByteArray))
self.restoreState(settings.value("/DB_Manager/mainWindow/windowState", QByteArray(), type=QByteArray))

self.connect(self.tabs, SIGNAL("currentChanged(int)"), self.tabChanged)
self.connect(self.tree, SIGNAL("selectedItemChanged"), self.itemChanged)
self.tabs.currentChanged.connect(self.tabChanged)
self.tree.selectedItemChanged.connect(self.itemChanged)
self.itemChanged(None)

def closeEvent(self, e):
Expand Down Expand Up @@ -189,7 +189,7 @@ def runSqlWindow(self):
self.tabs.setCurrentIndex(0)
return

from dlg_sql_window import DlgSqlWindow
from .dlg_sql_window import DlgSqlWindow

query = DlgSqlWindow(self.iface, db, self)
dbname = db.connection().connectionName()
Expand Down Expand Up @@ -224,7 +224,7 @@ def registerAction(self, action, menuName, callback=None):
self._registeredDbActions[menuName].append(action)

if callback is not None:
QObject.connect(action, SIGNAL("triggered(bool)"), invoke_callback)
action.triggered.connect(invoke_callback)
return True

# search for the menu
Expand Down Expand Up @@ -270,7 +270,7 @@ def registerAction(self, action, menuName, callback=None):
self._registeredDbActions[menuName].append(action)

if callback is not None:
QObject.connect(action, SIGNAL("triggered(bool)"), invoke_callback)
action.triggered.connect(invoke_callback)

return True

Expand Down
13 changes: 8 additions & 5 deletions python/plugins/db_manager/db_manager_plugin.py
Expand Up @@ -20,8 +20,11 @@
***************************************************************************/
"""

from PyQt4.QtCore import Qt, QObject, SIGNAL
from PyQt4.QtGui import QAction, QIcon, QApplication
from PyQt.QtCore import Qt, QObject
from PyQt.QtWidgets import QAction, QApplication
from PyQt.QtGui import QIcon

from . import resources_rc


class DBManagerPlugin:
Expand All @@ -34,7 +37,7 @@ def initGui(self):
self.action = QAction(QIcon(":/db_manager/icon"), QApplication.translate("DBManagerPlugin", "DB Manager"),
self.iface.mainWindow())
self.action.setObjectName("dbManager")
QObject.connect(self.action, SIGNAL("triggered()"), self.run)
self.action.triggered.connect(self.run)
# Add toolbar button and menu item
if hasattr(self.iface, 'addDatabaseToolBarIcon'):
self.iface.addDatabaseToolBarIcon(self.action)
Expand Down Expand Up @@ -62,10 +65,10 @@ def unload(self):
def run(self):
# keep opened only one instance
if self.dlg is None:
from db_manager import DBManager
from .db_manager import DBManager

self.dlg = DBManager(self.iface)
QObject.connect(self.dlg, SIGNAL("destroyed(QObject *)"), self.onDestroyed)
self.dlg.destroyed.connect(self.onDestroyed)
self.dlg.show()
self.dlg.raise_()
self.dlg.setWindowState(self.dlg.windowState() & ~Qt.WindowMinimized)
Expand Down
105 changes: 63 additions & 42 deletions python/plugins/db_manager/db_model.py
Expand Up @@ -20,18 +20,28 @@
***************************************************************************/
"""

from PyQt4.QtCore import Qt, QObject, SIGNAL, qDebug, QByteArray, QMimeData, QDataStream, QIODevice, QFileInfo, \
QAbstractItemModel, QModelIndex
from PyQt4.QtGui import QApplication, QIcon, QMessageBox
from PyQt.QtCore import Qt, QObject, qDebug, QByteArray, QMimeData, QDataStream, QIODevice, QFileInfo, QAbstractItemModel, QModelIndex, pyqtSignal
from PyQt.QtWidgets import QApplication, QMessageBox
from PyQt.QtGui import QIcon

from .db_plugins import supportedDbTypes, createDbPlugin
from .db_plugins.plugin import BaseError, Table
from .db_plugins.plugin import BaseError, Table, Database
from .dlg_db_error import DlgDbError

import qgis.core
from qgis.core import QgsDataSourceURI, QgsVectorLayer, QgsRasterLayer, QgsMimeDataUtils

from . import resources_rc

try:
from qgis.core import QgsVectorLayerImport
isImportVectorAvail = True
except:
isImportVectorAvail = False


class TreeItem(QObject):
itemRemoved = pyqtSignal()
itemChanged = pyqtSignal()

def __init__(self, data, parent=None):
QObject.__init__(self, parent)
Expand All @@ -41,14 +51,14 @@ def __init__(self, data, parent=None):
if parent:
parent.appendChild(self)

def childRemoved(self, child):
self.itemChanged()
def childRemoved(self):
self.itemWasChanged()

def itemChanged(self):
self.emit(SIGNAL("itemChanged"), self)
def itemWasChanged(self):
self.itemChanged.emit()

def itemRemoved(self):
self.emit(SIGNAL("itemRemoved"), self)
def itemWasRemoved(self):
self.itemRemoved.emit()

def populate(self):
self.populated = True
Expand All @@ -59,15 +69,15 @@ def getItemData(self):

def appendChild(self, child):
self.childItems.append(child)
self.connect(child, SIGNAL("itemRemoved"), self.childRemoved)
child.itemRemoved.connect(self.childRemoved)

def child(self, row):
return self.childItems[row]

def removeChild(self, row):
if row >= 0 and row < len(self.childItems):
self.childItems[row].itemData.deleteLater()
self.disconnect(self.childItems[row], SIGNAL("itemRemoved"), self.childRemoved)
self.childItems[row].itemRemoved.disconnect(self.childRemoved)
del self.childItems[row]

def childCount(self):
Expand Down Expand Up @@ -129,8 +139,8 @@ class ConnectionItem(TreeItem):

def __init__(self, connection, parent=None):
TreeItem.__init__(self, connection, parent)
self.connect(connection, SIGNAL("changed"), self.itemChanged)
self.connect(connection, SIGNAL("deleted"), self.itemRemoved)
connection.changed.connect(self.itemChanged)
connection.deleted.connect(self.itemRemoved)

# load (shared) icon with first instance of table item
if not hasattr(ConnectionItem, 'connectedIcon'):
Expand Down Expand Up @@ -158,8 +168,8 @@ def populate(self):
return False

database = connection.database()
self.connect(database, SIGNAL("changed"), self.itemChanged)
self.connect(database, SIGNAL("deleted"), self.itemRemoved)
database.changed.connect(self.itemChanged)
database.deleted.connect(self.itemRemoved)

schemas = database.schemas()
if schemas is not None:
Expand All @@ -184,8 +194,8 @@ class SchemaItem(TreeItem):

def __init__(self, schema, parent):
TreeItem.__init__(self, schema, parent)
self.connect(schema, SIGNAL("changed"), self.itemChanged)
self.connect(schema, SIGNAL("deleted"), self.itemRemoved)
schema.changed.connect(self.itemChanged)
schema.deleted.connect(self.itemRemoved)

# load (shared) icon with first instance of schema item
if not hasattr(SchemaItem, 'schemaIcon'):
Expand Down Expand Up @@ -214,8 +224,8 @@ class TableItem(TreeItem):

def __init__(self, table, parent):
TreeItem.__init__(self, table, parent)
self.connect(table, SIGNAL("changed"), self.itemChanged)
self.connect(table, SIGNAL("deleted"), self.itemRemoved)
table.changed.connect(self.itemChanged)
table.deleted.connect(self.itemRemoved)
self.populate()

# load (shared) icon with first instance of table item
Expand Down Expand Up @@ -273,23 +283,26 @@ def path(self):


class DBModel(QAbstractItemModel):
importVector = pyqtSignal(QgsVectorLayer, Database, QgsDataSourceURI, QModelIndex)
notPopulated = pyqtSignal(QModelIndex)

def __init__(self, parent=None):
global isImportVectorAvail

QAbstractItemModel.__init__(self, parent)
self.treeView = parent
self.header = [self.tr('Databases')]

self.isImportVectorAvail = hasattr(qgis.core, 'QgsVectorLayerImport')
if self.isImportVectorAvail:
self.connect(self, SIGNAL("importVector"), self.importVector)
if isImportVectorAvail:
self.importVector.connect(self.vectorImport)

self.hasSpatialiteSupport = "spatialite" in supportedDbTypes()

self.rootItem = TreeItem(None, None)
for dbtype in supportedDbTypes():
dbpluginclass = createDbPlugin(dbtype)
item = PluginItem(dbpluginclass, self.rootItem)
self.connect(item, SIGNAL("itemChanged"), self.refreshItem)
item.itemChanged.connect(self.refreshItem)

def refreshItem(self, item):
if isinstance(item, TreeItem):
Expand Down Expand Up @@ -360,6 +373,8 @@ def data(self, index, role):
return retval

def flags(self, index):
global isImportVectorAvail

if not index.isValid():
return Qt.NoItemFlags

Expand All @@ -375,7 +390,7 @@ def flags(self, index):
flags |= Qt.ItemIsDragEnabled

# vectors/tables can be dropped on connected databases to be imported
if self.isImportVectorAvail:
if isImportVectorAvail:
if isinstance(item, ConnectionItem) and item.populated:
flags |= Qt.ItemIsDropEnabled

Expand Down Expand Up @@ -471,10 +486,10 @@ def _refreshIndex(self, index, force=False):
if prevPopulated or force:
if item.populate():
for child in item.childItems:
self.connect(child, SIGNAL("itemChanged"), self.refreshItem)
child.itemChanged.connect(self.refreshItem)
self._onDataChanged(index)
else:
self.emit(SIGNAL("notPopulated"), index)
self.notPopulated.emit(index)

except BaseError as e:
item.populated = False
Expand All @@ -486,7 +501,7 @@ def _refreshIndex(self, index, force=False):
def _onDataChanged(self, indexFrom, indexTo=None):
if indexTo is None:
indexTo = indexFrom
self.emit(SIGNAL('dataChanged(const QModelIndex &, const QModelIndex &)'), indexFrom, indexTo)
self.dataChanged.emit(indexFrom, indexTo)

QGIS_URI_MIME = "application/x-vnd.qgis.qgis.uri"

Expand All @@ -511,11 +526,13 @@ def mimeData(self, indexes):
return mimeData

def dropMimeData(self, data, action, row, column, parent):
global isImportVectorAvail

if action == Qt.IgnoreAction:
return True

# vectors/tables to be imported must be dropped on connected db, schema or table
canImportLayer = self.isImportVectorAvail and parent.isValid() and \
canImportLayer = isImportVectorAvail and parent.isValid() and \
(isinstance(parent.internalPointer(), (SchemaItem, TableItem)) or
(isinstance(parent.internalPointer(), ConnectionItem) and parent.internalPointer().populated))

Expand All @@ -538,15 +555,15 @@ def dropMimeData(self, data, action, row, column, parent):
item = index.internalPointer()

conn_name = QFileInfo(filename).fileName()
uri = qgis.core.QgsDataSourceURI()
uri = QgsDataSourceURI()
uri.setDatabase(filename)
item.getItemData().addConnection(conn_name, uri)
item.emit(SIGNAL('itemChanged'), item)
item.itemChanged.emit(item)
added += 1
continue

if canImportLayer:
if qgis.core.QgsRasterLayer.isValidRasterFileName(filename):
if QgsRasterLayer.isValidRasterFileName(filename):
layerType = 'raster'
providerKey = 'gdal'
else:
Expand All @@ -558,22 +575,24 @@ def dropMimeData(self, data, action, row, column, parent):
added += 1

if data.hasFormat(self.QGIS_URI_MIME):
for uri in qgis.core.QgsMimeDataUtils.decodeUriList(data):
for uri in QgsMimeDataUtils.decodeUriList(data):
if canImportLayer:
if self.importLayer(uri.layerType, uri.providerKey, uri.name, uri.uri, parent):
added += 1

return added > 0

def importLayer(self, layerType, providerKey, layerName, uriString, parent):
if not self.isImportVectorAvail:
global isImportVectorAvail

if not isImportVectorAvail:
return False

if layerType == 'raster':
return False # not implemented yet
inLayer = qgis.core.QgsRasterLayer(uriString, layerName, providerKey)
inLayer = QgsRasterLayer(uriString, layerName, providerKey)
else:
inLayer = qgis.core.QgsVectorLayer(uriString, layerName, providerKey)
inLayer = QgsVectorLayer(uriString, layerName, providerKey)

if not inLayer.isValid():
# invalid layer
Expand Down Expand Up @@ -602,24 +621,26 @@ def importLayer(self, layerType, providerKey, layerName, uriString, parent):

# default pk and geom field name value
if providerKey in ['postgres', 'spatialite']:
inUri = qgis.core.QgsDataSourceURI(inLayer.source())
inUri = QgsDataSourceURI(inLayer.source())
pkCol = inUri.keyColumn()
geomCol = inUri.geometryColumn()

outUri = outDb.uri()
outUri.setDataSource(schema, layerName, geomCol, "", pkCol)

self.emit(SIGNAL("importVector"), inLayer, outDb, outUri, toIndex)
self.importVector.emit(inLayer, outDb, outUri, toIndex)
return True

return False

def importVector(self, inLayer, outDb, outUri, parent):
if not self.isImportVectorAvail:
def vectorImport(self, inLayer, outDb, outUri, parent):
global isImportVectorAvail

if not isImportVectorAvail:
return False

try:
from dlg_import_vector import DlgImportVector
from .dlg_import_vector import DlgImportVector

dlg = DlgImportVector(inLayer, outDb, outUri)
QApplication.restoreOverrideCursor()
Expand Down
9 changes: 5 additions & 4 deletions python/plugins/db_manager/db_plugins/data_model.py
Expand Up @@ -20,8 +20,9 @@
***************************************************************************/
"""

from PyQt4.QtCore import Qt, QTime, QRegExp, QAbstractTableModel
from PyQt4.QtGui import QFont, QStandardItemModel, QStandardItem, QApplication
from PyQt.QtCore import Qt, QTime, QRegExp, QAbstractTableModel
from PyQt.QtGui import QFont, QStandardItemModel, QStandardItem
from PyQt.QtWidgets import QApplication

from .plugin import DbError

Expand Down Expand Up @@ -266,7 +267,7 @@ def __init__(self, parent, editable=False):
QApplication.translate("DBManagerPlugin", 'Column(s)')], editable, parent)

def append(self, constr):
field_names = map(lambda k_v: unicode(k_v[1].name), constr.fields().iteritems())
field_names = map(lambda k_v: unicode(k_v[1].name), iter(constr.fields().items()))
data = [constr.name, constr.type2String(), u", ".join(field_names)]
self.appendRow(self.rowFromData(data))
row = self.rowCount() - 1
Expand Down Expand Up @@ -302,7 +303,7 @@ def __init__(self, parent, editable=False):
QApplication.translate("DBManagerPlugin", 'Column(s)')], editable, parent)

def append(self, idx):
field_names = map(lambda k_v1: unicode(k_v1[1].name), idx.fields().iteritems())
field_names = map(lambda k_v1: unicode(k_v1[1].name), iter(idx.fields().items()))
data = [idx.name, u", ".join(field_names)]
self.appendRow(self.rowFromData(data))
row = self.rowCount() - 1
Expand Down

0 comments on commit 8bda5c0

Please sign in to comment.