Example #1
0
        def registerDatabaseActions(self, mainWindow):
                action = QAction(QApplication.translate("DBManagerPlugin", "&Re-connect"), self)
                mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Database"), self.reconnectActionSlot )

                if self.schemas() is not None:
                        action = QAction(QApplication.translate("DBManagerPlugin", "&Create schema"), self)
                        mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Schema"), self.createSchemaActionSlot )
                        action = QAction(QApplication.translate("DBManagerPlugin", "&Delete (empty) schema"), self)
                        mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Schema"), self.deleteSchemaActionSlot )

                action = QAction(QApplication.translate("DBManagerPlugin", "Delete selected item"), self)
                mainWindow.registerAction( action, None, self.deleteActionSlot )
                action.setShortcuts(QKeySequence.Delete)

                action = QAction(QIcon(":/db_manager/actions/create_table"), QApplication.translate("DBManagerPlugin", "&Create table"), self)
                mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Table"), self.createTableActionSlot )
                action = QAction(QIcon(":/db_manager/actions/edit_table"), QApplication.translate("DBManagerPlugin", "&Edit table"), self)
                mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Table"), self.editTableActionSlot )
                action = QAction(QIcon(":/db_manager/actions/del_table"), QApplication.translate("DBManagerPlugin", "&Delete table/view"), self)
                mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Table"), self.deleteTableActionSlot )
                action = QAction(QApplication.translate("DBManagerPlugin", "&Empty table"), self)
                mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Table"), self.emptyTableActionSlot )

                if self.schemas() is not None:
                        action = QAction(QApplication.translate("DBManagerPlugin", "&Move to schema"), self)
                        action.setMenu( QMenu(mainWindow) )
                        invoke_callback = lambda: mainWindow.invokeCallback(self.prepareMenuMoveTableToSchemaActionSlot)
                        QObject.connect( action.menu(), SIGNAL("aboutToShow()"), invoke_callback )
                        mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Table") )
Example #2
0
 def __init__(self, parent, isIsolated=True, doQuit=True):
     super(QDialogWithPrinting, self).__init__(parent)
     self.setModal(True)
     self.isIsolated = isIsolated
     self.initWidth = self.width()
     self.initHeight = self.height()
     self.sizeRatios = numpy.array([1.05**(-idx)
                                    for idx in range(1, 6)][::-1] + [
                                        1.0,
                                    ] + [1.05**idx for idx in range(1, 6)])
     self.currentSizeRatio = 5
     #
     ## timer to trigger on_start function on start of app
     QTimer.singleShot(0, self.on_start)
     #
     if isIsolated:
         printAction = QAction(self)
         printAction.setShortcuts(['Shift+Ctrl+P'])
         printAction.triggered.connect(self.screenGrab)
         self.addAction(printAction)
         #
         quitAction = QAction(self)
         quitAction.setShortcuts(['Ctrl+Q', 'Esc'])
         if not doQuit:
             quitAction.triggered.connect(self.hide)
         else:
             quitAction.triggered.connect(sys.exit)
         self.addAction(quitAction)
Example #3
0
class ViewActions(actioncollection.ActionCollection):
    name = "view"
    def createActions(self, parent=None):
        self.window_split_horizontal = QAction(parent)
        self.window_split_vertical = QAction(parent)
        self.window_close_view = QAction(parent)
        self.window_close_others = QAction(parent)
        self.window_next_view = QAction(parent)
        self.window_previous_view = QAction(parent)
        
        # icons
        self.window_split_horizontal.setIcon(icons.get('view-split-top-bottom'))
        self.window_split_vertical.setIcon(icons.get('view-split-left-right'))
        self.window_close_view.setIcon(icons.get('view-close'))
        self.window_next_view.setIcon(icons.get('go-next-view'))
        self.window_previous_view.setIcon(icons.get('go-previous-view'))
        
        # shortcuts
        self.window_close_view.setShortcut(Qt.CTRL + Qt.SHIFT + Qt.Key_W)
        self.window_next_view.setShortcuts(QKeySequence.NextChild)
        qutil.removeShortcut(self.window_next_view, "Ctrl+,")
        self.window_previous_view.setShortcuts(QKeySequence.PreviousChild)
        qutil.removeShortcut(self.window_previous_view, "Ctrl+.")

    def translateUI(self):
        self.window_split_horizontal.setText(_("Split &Horizontally"))
        self.window_split_vertical.setText(_("Split &Vertically"))
        self.window_close_view.setText(_("&Close Current View"))
        self.window_close_others.setText(_("Close &Other Views"))
        self.window_next_view.setText(_("&Next View"))
        self.window_previous_view.setText(_("&Previous View"))
Example #4
0
 def action(self, scheme):
     """Returns a new QAction that represents our item.
     
     The action contains the text, icon and current shortcut.
     
     """
     action = QAction(self.icon(0), self.text(0).replace('&', '&&'), None)
     action.setShortcuts(self._shortcuts[scheme][0])
     return action
Example #5
0
 def action(self, scheme):
     """Returns a new QAction that represents our item.
     
     The action contains the text, icon and current shortcut.
     
     """
     action = QAction(self.icon(0), self.text(0).replace('&', '&&'), None)
     action.setShortcuts(self._shortcuts[scheme][0])
     return action
Example #6
0
    def __init__(self, iface, db, parent=None):
        QDialog.__init__(self, parent)
        self.iface = iface
        self.db = db
        self.setupUi(self)
        self.setWindowTitle(
            u"%s - %s [%s]" %
            (self.windowTitle(), db.connection().connectionName(),
             db.connection().typeNameString()))

        self.defaultLayerName = 'QueryLayer'

        settings = QSettings()
        self.restoreGeometry(
            settings.value("/DB_Manager/sqlWindow/geometry",
                           QByteArray(),
                           type=QByteArray))

        self.editSql.setFocus()
        self.editSql.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.initCompleter()

        # allow to copy results
        copyAction = QAction("copy", self)
        self.viewResult.addAction(copyAction)
        copyAction.setShortcuts(QKeySequence.Copy)
        QObject.connect(copyAction, SIGNAL("triggered()"),
                        self.copySelectedResults)

        self.connect(self.btnExecute, SIGNAL("clicked()"), self.executeSql)
        self.connect(self.btnClear, SIGNAL("clicked()"), self.clearSql)
        self.connect(self.buttonBox.button(QDialogButtonBox.Close),
                     SIGNAL("clicked()"), self.close)

        self.connect(self.presetStore, SIGNAL("clicked()"), self.storePreset)
        self.connect(self.presetDelete, SIGNAL("clicked()"), self.deletePreset)
        self.connect(self.presetCombo, SIGNAL("activated(QString)"),
                     self.loadPreset)
        self.connect(self.presetCombo, SIGNAL("activated(QString)"),
                     self.presetName.setText)
        self.updatePresetsCombobox()

        # hide the load query as layer if feature is not supported
        self._loadAsLayerAvailable = self.db.connector.hasCustomQuerySupport()
        self.loadAsLayerGroup.setVisible(self._loadAsLayerAvailable)
        if self._loadAsLayerAvailable:
            self.layerTypeWidget.hide()  # show if load as raster is supported
            self.connect(self.loadLayerBtn, SIGNAL("clicked()"),
                         self.loadSqlLayer)
            self.connect(self.getColumnsBtn, SIGNAL("clicked()"),
                         self.fillColumnCombos)
            self.connect(self.loadAsLayerGroup, SIGNAL("toggled(bool)"),
                         self.loadAsLayerToggled)
            self.loadAsLayerToggled(False)
Example #7
0
    def __init__(self, iface, db, parent=None):
        QWidget.__init__(self, parent)
        self.iface = iface
        self.db = db
        self.setupUi(self)
        self.setWindowTitle(
            u"%s - %s [%s]" %
            (self.windowTitle(), db.connection().connectionName(),
             db.connection().typeNameString()))

        self.defaultLayerName = 'QueryLayer'

        self.editSql.setFocus()
        self.editSql.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.initCompleter()

        # allow to copy results
        copyAction = QAction("copy", self)
        self.viewResult.addAction(copyAction)
        copyAction.setShortcuts(QKeySequence.Copy)

        copyAction.triggered.connect(self.copySelectedResults)

        self.btnExecute.clicked.connect(self.executeSql)
        self.btnClear.clicked.connect(self.clearSql)

        self.presetStore.clicked.connect(self.storePreset)
        self.presetDelete.clicked.connect(self.deletePreset)
        self.presetCombo.activated[str].connect(self.loadPreset)
        self.presetCombo.activated[str].connect(self.presetName.setText)

        self.updatePresetsCombobox()

        # hide the load query as layer if feature is not supported
        self._loadAsLayerAvailable = self.db.connector.hasCustomQuerySupport()
        self.loadAsLayerGroup.setVisible(self._loadAsLayerAvailable)
        if self._loadAsLayerAvailable:
            self.layerTypeWidget.hide()  # show if load as raster is supported
            self.loadLayerBtn.clicked.connect(self.loadSqlLayer)
            self.getColumnsBtn.clicked.connect(self.fillColumnCombos)
            self.loadAsLayerGroup.toggled.connect(self.loadAsLayerToggled)
            self.loadAsLayerToggled(False)

        self._createViewAvailable = self.db.connector.hasCreateSpatialViewSupport(
        )
        self.btnCreateView.setVisible(self._createViewAvailable)
        if self._createViewAvailable:
            self.btnCreateView.clicked.connect(self.createView)

        self.queryBuilderFirst = True
        self.queryBuilderBtn.setIcon(QIcon(":/db_manager/icons/sql.gif"))
        self.queryBuilderBtn.clicked.connect(self.displayQueryBuilder)

        self.presetName.textChanged.connect(self.nameChanged)
Example #8
0
    def __init__(self, iface, db, parent=None):
        QWidget.__init__(self, parent)
        self.iface = iface
        self.db = db
        self.setupUi(self)
        self.setWindowTitle(
            u"%s - %s [%s]" % (self.windowTitle(), db.connection().connectionName(), db.connection().typeNameString()))

        self.defaultLayerName = 'QueryLayer'

        self.editSql.setFocus()
        self.editSql.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.initCompleter()

        # allow to copy results
        copyAction = QAction("copy", self)
        self.viewResult.addAction(copyAction)
        copyAction.setShortcuts(QKeySequence.Copy)

        copyAction.triggered.connect(self.copySelectedResults)

        self.btnExecute.clicked.connect(self.executeSql)
        self.btnClear.clicked.connect(self.clearSql)

        self.presetStore.clicked.connect(self.storePreset)
        self.presetDelete.clicked.connect(self.deletePreset)
        self.presetCombo.activated[str].connect(self.loadPreset)
        self.presetCombo.activated[str].connect(self.presetName.setText)

        self.updatePresetsCombobox()

        # hide the load query as layer if feature is not supported
        self._loadAsLayerAvailable = self.db.connector.hasCustomQuerySupport()
        self.loadAsLayerGroup.setVisible(self._loadAsLayerAvailable)
        if self._loadAsLayerAvailable:
            self.layerTypeWidget.hide()  # show if load as raster is supported
            self.loadLayerBtn.clicked.connect(self.loadSqlLayer)
            self.getColumnsBtn.clicked.connect(self.fillColumnCombos)
            self.loadAsLayerGroup.toggled.connect(self.loadAsLayerToggled)
            self.loadAsLayerToggled(False)

        self._createViewAvailable = self.db.connector.hasCreateSpatialViewSupport()
        self.btnCreateView.setVisible( self._createViewAvailable )
        if self._createViewAvailable:
            self.btnCreateView.clicked.connect(self.createView)

        self.queryBuilderFirst = True
        self.queryBuilderBtn.setIcon(QIcon(":/db_manager/icons/sql.gif"))
        self.queryBuilderBtn.clicked.connect(self.displayQueryBuilder)

        self.presetName.textChanged.connect(self.nameChanged)
Example #9
0
    def __init__(self, iface, db, parent=None):
        QDialog.__init__(self, parent)
        self.iface = iface
        self.db = db
        self.setupUi(self)
        self.setWindowTitle(
            u"%s - %s [%s]" % (self.windowTitle(), db.connection().connectionName(), db.connection().typeNameString()))

        self.defaultLayerName = 'QueryLayer'

        settings = QSettings()
        self.restoreGeometry(settings.value("/DB_Manager/sqlWindow/geometry", QByteArray(), type=QByteArray))

        self.editSql.setFocus()
        self.editSql.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.initCompleter()

        # allow to copy results
        copyAction = QAction("copy", self)
        self.viewResult.addAction(copyAction)
        copyAction.setShortcuts(QKeySequence.Copy)
        QObject.connect(copyAction, SIGNAL("triggered()"), self.copySelectedResults)

        self.connect(self.btnExecute, SIGNAL("clicked()"), self.executeSql)
        self.connect(self.btnClear, SIGNAL("clicked()"), self.clearSql)
        self.connect(self.buttonBox.button(QDialogButtonBox.Close), SIGNAL("clicked()"), self.close)

        self.connect(self.presetStore, SIGNAL("clicked()"), self.storePreset)
        self.connect(self.presetDelete, SIGNAL("clicked()"), self.deletePreset)
        self.connect(self.presetCombo, SIGNAL("activated(QString)"), self.loadPreset)
        self.connect(self.presetCombo, SIGNAL("activated(QString)"), self.presetName.setText)
        self.updatePresetsCombobox()

        # hide the load query as layer if feature is not supported
        self._loadAsLayerAvailable = self.db.connector.hasCustomQuerySupport()
        self.loadAsLayerGroup.setVisible(self._loadAsLayerAvailable)
        if self._loadAsLayerAvailable:
            self.layerTypeWidget.hide()  # show if load as raster is supported
            self.connect(self.loadLayerBtn, SIGNAL("clicked()"), self.loadSqlLayer)
            self.connect(self.getColumnsBtn, SIGNAL("clicked()"), self.fillColumnCombos)
            self.connect(self.loadAsLayerGroup, SIGNAL("toggled(bool)"), self.loadAsLayerToggled)
            self.loadAsLayerToggled(False)

        self._createViewAvailable = self.db.connector.hasCreateSpatialViewSupport()
        self.btnCreateView.setVisible( self._createViewAvailable )
        if self._createViewAvailable:
            self.connect( self.btnCreateView, SIGNAL("clicked()"), self.createView )

        self.queryBuilderFirst = True
        self.queryBuilderBtn.setIcon(QIcon(":/db_manager/icons/sql.gif"))
        self.connect( self.queryBuilderBtn, SIGNAL("clicked()"), self.displayQueryBuilder )
Example #10
0
 def editShortcut(self):
     """Edit our shortcut."""
     from widgets import shortcuteditdialog
     mainwindow = self.parent().mainwindow()
     action = QAction(self.defaultAction().icon(), self.defaultAction().text(), None)
     action.setShortcuts(self.actionCollection().shortcuts(self.objectName()) or [])
     default = self.actionCollection().defaults().get(self.objectName())
     mgr = actioncollectionmanager.manager(mainwindow)
     skip = (self.actionCollection(), self.objectName())
     cb = mgr.findShortcutConflict
     
     dlg = shortcuteditdialog.ShortcutEditDialog(self, cb, skip)
     if dlg.editAction(action, default):
         mgr.removeShortcuts(action.shortcuts())
         self.actionCollection().setShortcuts(self.objectName(), action.shortcuts())
Example #11
0
    def __init__(self, parent=None):
        QTableView.__init__(self, parent)
        self.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.setSelectionMode(QAbstractItemView.ExtendedSelection)

        self.item = None
        self.dirty = False

        # allow copying results
        copyAction = QAction(QApplication.translate("DBManagerPlugin", "Copy"), self)
        self.addAction(copyAction)
        copyAction.setShortcuts(QKeySequence.Copy)
        QObject.connect(copyAction, SIGNAL("triggered()"), self.copySelectedResults)

        self._clear()
Example #12
0
    def __init__(self, parent=None):
        QTableView.__init__(self, parent)
        self.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.setSelectionMode(QAbstractItemView.ExtendedSelection)

        self.item = None
        self.dirty = False

        # allow to copy results
        copyAction = QAction(QApplication.translate("DBManagerPlugin", "Copy"), self)
        self.addAction(copyAction)
        copyAction.setShortcuts(QKeySequence.Copy)
        QObject.connect(copyAction, SIGNAL("triggered()"), self.copySelectedResults)

        self._clear()
Example #13
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self._create_actions()
        self._create_toolbar()
        self._canvas = Canvas()
        self._canvas.scale(16, 16)
        self.setCentralWidget(self._canvas)

    def _create_actions(self):
        self._delete_action = QAction("Delete", None)
        self._delete_action.setShortcuts(QKeySequence.Delete)
        self._delete_action.triggered.connect(self._delete)

        self._select_action = QAction("Select", None)
        self._select_action.setCheckable(True)
        self._select_action.triggered.connect(self._use_select_tool)

        self._pen_action = QAction("Pen", None)
        self._pen_action.setCheckable(True)
        self._pen_action.setChecked(True)
        self._pen_action.triggered.connect(self._use_pen_tool)

        self._new_shape_action = QAction("New Shape", None)
        self._new_shape_action.triggered.connect(self._new_shape)

        self._tool_group = QActionGroup(None)
        self._tool_group.addAction(self._select_action)
        self._tool_group.addAction(self._pen_action)

    def _create_toolbar(self):
        toolbar = self.addToolBar("Tools")
        toolbar.addAction(self._delete_action)
        toolbar.addAction(self._select_action)
        toolbar.addAction(self._pen_action)
        toolbar.addAction(self._new_shape_action)

    def _use_select_tool(self):
        self._canvas.use_tool(SelectTool)

    def _use_pen_tool(self):
        self._canvas.use_tool(PenTool)

    def _new_shape(self):
        self._canvas.new_shape()

    def _delete(self):
        self._canvas.delete_selection()
Example #14
0
 def _create_action(self, action_name, icon_file, text, shortcuts):
     if action_name == "*separator*":
         action = QAction(self.window)
         action.setSeparator(True)
     else:
         if icon_file:
             action = QAction(QIcon(utils.resource_path(icon_file)), text, self.window)
         else:
             action = QAction(text, self.window)
     if shortcuts:
         sequences = [QKeySequence(s) for s in shortcuts]
         action.setShortcuts(sequences)
     if action_name.startswith("+"):
         action.setCheckable(True)
         if action_name.startswith("++"):
             action.setChecked(True)
     return action
Example #15
0
 def _create_action(self, action_name, icon_file, text, shortcuts):
     if action_name == '*separator*':
         action = QAction(self.window)
         action.setSeparator(True)
     else:
         if icon_file:
             action = QAction(QIcon(utils.resource_path(icon_file)), text,
                              self.window)
         else:
             action = QAction(text, self.window)
     if shortcuts:
         sequences = [QKeySequence(s) for s in shortcuts]
         action.setShortcuts(sequences)
     if action_name.startswith('+'):
         action.setCheckable(True)
         if action_name.startswith('++'):
             action.setChecked(True)
     return action
Example #16
0
 def editShortcuts(self):
     from widgets import shortcuteditdialog
     ac = self.parent().parent().snippetActions
     action = QAction(None)
     if self._name:
         action.setShortcuts(self.shortcuts())
         action.setIcon(snippets.icon(self._name) or QIcon())
         default = ac.defaults().get(self._name)
         text = snippets.title(self._name)
     else:
         default = None
         text = self.titleEntry.text() or _("Untitled")
     action.setText(text.replace('&', '&&'))
     
     cb = self.actionManager().findShortcutConflict
     skip = (self.parent().parent().snippetActions, self._name)
     dlg = shortcuteditdialog.ShortcutEditDialog(self, cb, skip)
     
     if dlg.editAction(action, default):
         self.setShortcuts(action.shortcuts())
Example #17
0
def action(name, parent=None, collection=None):
    """Returns a QAction with text and icon for the given snippet name.

    Returns None is no such snippet is available.
    If collection is provided, it is used to set shortcuts to the action.
    """
    title = snippets.title(name)
    if not title:
        return
    a = QAction(parent)
    a.setObjectName(name)
    a.setText(title.replace('&', '&&'))
    icon = snippets.icon(name)
    if icon:
        a.setIcon(icon)
    if collection:
        shortcuts = collection.shortcuts(name)
        if shortcuts:
            a.setShortcuts(shortcuts)
    return a
Example #18
0
def action(name, parent=None, collection=None):
    """Returns a QAction with text and icon for the given snippet name.

    Returns None is no such snippet is available.
    If collection is provided, it is used to set shortcuts to the action.
    """
    title = snippets.title(name)
    if not title:
        return
    a = QAction(parent)
    a.setObjectName(name)
    a.setText(title.replace('&', '&&'))
    icon = snippets.icon(name)
    if icon:
        a.setIcon(icon)
    if collection:
        shortcuts = collection.shortcuts(name)
        if shortcuts:
            a.setShortcuts(shortcuts)
    return a
Example #19
0
    def editShortcuts(self):
        from widgets import shortcuteditdialog
        ac = self.parent().parent().snippetActions
        action = QAction(None)
        if self._name:
            action.setShortcuts(self.shortcuts())
            action.setIcon(snippets.icon(self._name) or QIcon())
            default = ac.defaults().get(self._name)
            text = snippets.title(self._name)
        else:
            default = None
            text = self.titleEntry.text() or _("Untitled")
        action.setText(text.replace('&', '&&'))

        cb = self.actionManager().findShortcutConflict
        skip = (self.parent().parent().snippetActions, self._name)
        dlg = shortcuteditdialog.ShortcutEditDialog(self, cb, skip)

        if dlg.editAction(action, default):
            self.setShortcuts(action.shortcuts())
Example #20
0
    def registerDatabaseActions(self, mainWindow):
        action = QAction(QApplication.translate(
            "DBManagerPlugin", "&Re-connect"), self)
        mainWindow.registerAction(action, QApplication.translate(
            "DBManagerPlugin", "&Database"), self.reconnectActionSlot)

        if self.schemas():
            action = QAction(QApplication.translate(
                "DBManagerPlugin", "&Create schema"), self)
            mainWindow.registerAction(action, QApplication.translate(
                "DBManagerPlugin", "&Schema"), self.createSchemaActionSlot)
            action = QAction(QApplication.translate(
                "DBManagerPlugin", "&Delete (empty) schema"), self)
            mainWindow.registerAction(action, QApplication.translate(
                "DBManagerPlugin", "&Schema"), self.deleteSchemaActionSlot)

        action = QAction(QApplication.translate(
            "DBManagerPlugin", "Delete selected item"), self)
        mainWindow.registerAction(action, None, self.deleteActionSlot)
        action.setShortcuts(QKeySequence.Delete)

        action = QAction(QIcon(":/db_manager/actions/create_table"),
                         QApplication.translate(
                             "DBManagerPlugin", "&Create table"), self)
        mainWindow.registerAction(action, QApplication.translate(
            "DBManagerPlugin", "&Table"), self.createTableActionSlot)
        action = QAction(QIcon(":/db_manager/actions/edit_table"),
                         QApplication.translate(
                             "DBManagerPlugin", "&Edit table"), self)
        mainWindow.registerAction(action, QApplication.translate(
            "DBManagerPlugin", "&Table"), self.editTableActionSlot)
        action = QAction(QIcon(":/db_manager/actions/del_table"),
                         QApplication.translate(
                             "DBManagerPlugin", "&Delete table/view"), self)
        mainWindow.registerAction(action, QApplication.translate(
            "DBManagerPlugin", "&Table"), self.deleteTableActionSlot)
        action = QAction(QApplication.translate(
            "DBManagerPlugin", "&Empty table"), self)
        mainWindow.registerAction(action, QApplication.translate(
            "DBManagerPlugin", "&Table"), self.emptyTableActionSlot)
Example #21
0
class Actions(actioncollection.ActionCollection):
    name = "musicview"
    def createActions(self, panel):
        self.music_document_select = DocumentChooserAction(panel)
        self.music_print = QAction(panel)
        self.music_zoom_in = QAction(panel)
        self.music_zoom_out = QAction(panel)
        self.music_zoom_original = QAction(panel)
        self.music_zoom_combo = ZoomerAction(panel)
        self.music_fit_width = QAction(panel, checkable=True)
        self.music_fit_height = QAction(panel, checkable=True)
        self.music_fit_both = QAction(panel, checkable=True)
        self.music_maximize = QAction(panel)
        self.music_jump_to_cursor = QAction(panel)
        self.music_sync_cursor = QAction(panel, checkable=True)
        self.music_copy_image = QAction(panel)
        self.music_pager = PagerAction(panel)
        self.music_next_page = QAction(panel)
        self.music_prev_page = QAction(panel)

        self.music_print.setIcon(icons.get('document-print'))
        self.music_zoom_in.setIcon(icons.get('zoom-in'))
        self.music_zoom_out.setIcon(icons.get('zoom-out'))
        self.music_zoom_original.setIcon(icons.get('zoom-original'))
        self.music_fit_width.setIcon(icons.get('zoom-fit-width'))
        self.music_fit_height.setIcon(icons.get('zoom-fit-height'))
        self.music_fit_both.setIcon(icons.get('zoom-fit-best'))
        self.music_maximize.setIcon(icons.get('view-fullscreen'))
        self.music_jump_to_cursor.setIcon(icons.get('go-jump'))
        self.music_copy_image.setIcon(icons.get('edit-copy'))
        self.music_next_page.setIcon(icons.get('go-next'))
        self.music_prev_page.setIcon(icons.get('go-previous'))
        
        self.music_document_select.setShortcut(QKeySequence(Qt.SHIFT | Qt.CTRL | Qt.Key_O))
        self.music_print.setShortcuts(QKeySequence.Print)
        self.music_zoom_in.setShortcuts(QKeySequence.ZoomIn)
        self.music_zoom_out.setShortcuts(QKeySequence.ZoomOut)
        self.music_jump_to_cursor.setShortcut(QKeySequence(Qt.CTRL | Qt.Key_J))
        self.music_copy_image.setShortcut(QKeySequence(Qt.SHIFT | Qt.CTRL | Qt.Key_C))
        
    def translateUI(self):
        self.music_document_select.setText(_("Select Music View Document"))
        self.music_print.setText(_("&Print Music..."))
        self.music_zoom_in.setText(_("Zoom &In"))
        self.music_zoom_out.setText(_("Zoom &Out"))
        self.music_zoom_original.setText(_("Original &Size"))
        self.music_zoom_combo.setText(_("Zoom Music"))
        self.music_fit_width.setText(_("Fit &Width"))
        self.music_fit_height.setText(_("Fit &Height"))
        self.music_fit_both.setText(_("Fit &Page"))
        self.music_maximize.setText(_("&Maximize"))
        self.music_jump_to_cursor.setText(_("&Jump to Cursor Position"))
        self.music_sync_cursor.setText(_("S&ynchronize with Cursor Position"))
        self.music_copy_image.setText(_("Copy to &Image..."))
        self.music_next_page.setText(_("Next Page"))
        self.music_next_page.setIconText(_("Next"))
        self.music_prev_page.setText(_("Previous Page"))
        self.music_prev_page.setIconText(_("Previous"))
Example #22
0
    def __init__(self, iface, db, parent=None):
        QWidget.__init__(self, parent)
        self.iface = iface
        self.db = db
        self.filter = ""
        self.allowMultiColumnPk = isinstance(
            db, PGDatabase
        )  # at the moment only PostGIS allows a primary key to span multiple columns, spatialite doesn't
        self.setupUi(self)
        self.setWindowTitle(
            u"%s - %s [%s]" %
            (self.windowTitle(), db.connection().connectionName(),
             db.connection().typeNameString()))

        self.defaultLayerName = 'QueryLayer'

        if self.allowMultiColumnPk:
            self.uniqueColumnCheck.setText(
                self.trUtf8("Column(s) with unique values"))
        else:
            self.uniqueColumnCheck.setText(
                self.trUtf8("Column with unique values"))

        self.editSql.setFocus()
        self.editSql.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.initCompleter()

        # allow to copy results
        copyAction = QAction("copy", self)
        self.viewResult.addAction(copyAction)
        copyAction.setShortcuts(QKeySequence.Copy)

        copyAction.triggered.connect(self.copySelectedResults)

        self.btnExecute.clicked.connect(self.executeSql)
        self.btnSetFilter.clicked.connect(self.setFilter)
        self.btnClear.clicked.connect(self.clearSql)

        self.presetStore.clicked.connect(self.storePreset)
        self.presetDelete.clicked.connect(self.deletePreset)
        self.presetCombo.activated[str].connect(self.loadPreset)
        self.presetCombo.activated[str].connect(self.presetName.setText)

        self.updatePresetsCombobox()

        self.geomCombo.setEditable(True)
        self.geomCombo.lineEdit().setReadOnly(True)

        self.uniqueCombo.setEditable(True)
        self.uniqueCombo.lineEdit().setReadOnly(True)
        self.uniqueModel = QStandardItemModel(self.uniqueCombo)
        self.uniqueCombo.setModel(self.uniqueModel)
        if self.allowMultiColumnPk:
            self.uniqueCombo.setItemDelegate(QStyledItemDelegate())
            self.uniqueModel.itemChanged.connect(
                self.uniqueChanged)  # react to the (un)checking of an item
            self.uniqueCombo.lineEdit().textChanged.connect(
                self.uniqueTextChanged
            )  # there are other events that change the displayed text and some of them can not be caught directly

        # hide the load query as layer if feature is not supported
        self._loadAsLayerAvailable = self.db.connector.hasCustomQuerySupport()
        self.loadAsLayerGroup.setVisible(self._loadAsLayerAvailable)
        if self._loadAsLayerAvailable:
            self.layerTypeWidget.hide()  # show if load as raster is supported
            self.loadLayerBtn.clicked.connect(self.loadSqlLayer)
            self.getColumnsBtn.clicked.connect(self.fillColumnCombos)
            self.loadAsLayerGroup.toggled.connect(self.loadAsLayerToggled)
            self.loadAsLayerToggled(False)

        self._createViewAvailable = self.db.connector.hasCreateSpatialViewSupport(
        )
        self.btnCreateView.setVisible(self._createViewAvailable)
        if self._createViewAvailable:
            self.btnCreateView.clicked.connect(self.createView)

        self.queryBuilderFirst = True
        self.queryBuilderBtn.setIcon(QIcon(":/db_manager/icons/sql.gif"))
        self.queryBuilderBtn.clicked.connect(self.displayQueryBuilder)

        self.presetName.textChanged.connect(self.nameChanged)
Example #23
0
class SelectTool(DataTool):
    cursor = Qt.ArrowCursor

    def __init__(self, parent, plot):
        super().__init__(parent, plot)
        self._item = None
        self._start_pos = None
        self._selection_rect = None
        self._mouse_dragging = False
        self._delete_action = QAction(
            "Delete", self, shortcutContext=Qt.WindowShortcut
        )
        self._delete_action.setShortcuts([QtGui.QKeySequence.Delete,
                                          QtGui.QKeySequence("Backspace")])
        self._delete_action.triggered.connect(self.delete)

    def setSelectionRect(self, rect):
        if self._selection_rect != rect:
            self._selection_rect = QRectF(rect)
            self._item.setRect(self._selection_rect)

    def selectionRect(self):
        return self._item.rect()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            pos = self.mapToPlot(event.pos())
            if self._item.isVisible():
                if self.selectionRect().contains(pos):
                    # Allow the event to propagate to the item.
                    event.setAccepted(False)
                    self._item.setCursor(Qt.ClosedHandCursor)
                    return False

            self._mouse_dragging = True

            self._start_pos = pos
            self._item.setVisible(True)
            self._plot.addItem(self._item)

            self.setSelectionRect(QRectF(pos, pos))
            event.accept()
            return True
        else:
            return super().mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if event.buttons() & Qt.LeftButton:
            pos = self.mapToPlot(event.pos())
            self.setSelectionRect(QRectF(self._start_pos, pos).normalized())
            event.accept()
            return True
        else:
            return super().mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            pos = self.mapToPlot(event.pos())
            self.setSelectionRect(QRectF(self._start_pos, pos).normalized())
            event.accept()
            self.issueCommand.emit(SelectRegion(self.selectionRect()))
            self._item.setCursor(Qt.OpenHandCursor)
            self._mouse_dragging = False
            return True
        else:
            return super().mouseReleaseEvent(event)

    def activate(self):
        if self._item is None:
            self._item = _RectROI((0, 0), (0, 0), pen=(25, 25, 25))
            self._item.setAcceptedMouseButtons(Qt.LeftButton)
            self._item.setVisible(False)
            self._item.setCursor(Qt.OpenHandCursor)
            self._item.sigRegionChanged.connect(self._on_region_changed)
            self._item.sigRegionChangeStarted.connect(
                self._on_region_change_started)
            self._item.sigRegionChangeFinished.connect(
                self._on_region_change_finished)
            self._plot.addItem(self._item)
            self._mouse_dragging = False

        self._plot.addAction(self._delete_action)

    def deactivate(self):
        self._reset()
        self._plot.removeAction(self._delete_action)

    def _reset(self):
        self.setSelectionRect(QRectF())
        self._item.setVisible(False)
        self._mouse_dragging = False

    def delete(self):
        if not self._mouse_dragging and self._item.isVisible():
            self.issueCommand.emit(DeleteSelection())
            self._reset()

    def _on_region_changed(self):
        if not self._mouse_dragging:
            newrect = self._item.rect()
            delta = newrect.topLeft() - self._selection_rect.topLeft()
            self._selection_rect = newrect
            self.issueCommand.emit(MoveSelection(delta))

    def _on_region_change_started(self):
        if not self._mouse_dragging:
            self.editingStarted.emit()

    def _on_region_change_finished(self):
        if not self._mouse_dragging:
            self.editingFinished.emit()
Example #24
0
class SelectTool(DataTool):
    cursor = Qt.ArrowCursor

    def __init__(self, parent, plot):
        super().__init__(parent, plot)
        self._item = None
        self._start_pos = None
        self._selection_rect = None
        self._mouse_dragging = False
        self._delete_action = QAction("Delete",
                                      self,
                                      shortcutContext=Qt.WindowShortcut)
        self._delete_action.setShortcuts(
            [QtGui.QKeySequence.Delete,
             QtGui.QKeySequence("Backspace")])
        self._delete_action.triggered.connect(self.delete)

    def setSelectionRect(self, rect):
        if self._selection_rect != rect:
            self._selection_rect = QRectF(rect)
            self._item.setRect(self._selection_rect)

    def selectionRect(self):
        return self._item.rect()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            pos = self.mapToPlot(event.pos())
            if self._item.isVisible():
                if self.selectionRect().contains(pos):
                    # Allow the event to propagate to the item.
                    event.setAccepted(False)
                    self._item.setCursor(Qt.ClosedHandCursor)
                    return False

            self._mouse_dragging = True

            self._start_pos = pos
            self._item.setVisible(True)
            self._plot.addItem(self._item)

            self.setSelectionRect(QRectF(pos, pos))
            event.accept()
            return True
        else:
            return super().mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if event.buttons() & Qt.LeftButton:
            pos = self.mapToPlot(event.pos())
            self.setSelectionRect(QRectF(self._start_pos, pos).normalized())
            event.accept()
            return True
        else:
            return super().mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            pos = self.mapToPlot(event.pos())
            self.setSelectionRect(QRectF(self._start_pos, pos).normalized())
            event.accept()
            self.issueCommand.emit(SelectRegion(self.selectionRect()))
            self._item.setCursor(Qt.OpenHandCursor)
            self._mouse_dragging = False
            return True
        else:
            return super().mouseReleaseEvent(event)

    def activate(self):
        if self._item is None:
            self._item = _RectROI((0, 0), (0, 0), pen=(25, 25, 25))
            self._item.setAcceptedMouseButtons(Qt.LeftButton)
            self._item.setVisible(False)
            self._item.setCursor(Qt.OpenHandCursor)
            self._item.sigRegionChanged.connect(self._on_region_changed)
            self._item.sigRegionChangeStarted.connect(
                self._on_region_change_started)
            self._item.sigRegionChangeFinished.connect(
                self._on_region_change_finished)
            self._plot.addItem(self._item)
            self._mouse_dragging = False

        self._plot.addAction(self._delete_action)

    def deactivate(self):
        self._reset()
        self._plot.removeAction(self._delete_action)

    def _reset(self):
        self.setSelectionRect(QRectF())
        self._item.setVisible(False)
        self._mouse_dragging = False

    def delete(self):
        if not self._mouse_dragging and self._item.isVisible():
            self.issueCommand.emit(DeleteSelection())
            self._reset()

    def _on_region_changed(self):
        if not self._mouse_dragging:
            newrect = self._item.rect()
            delta = newrect.topLeft() - self._selection_rect.topLeft()
            self._selection_rect = newrect
            self.issueCommand.emit(MoveSelection(delta))

    def _on_region_change_started(self):
        if not self._mouse_dragging:
            self.editingStarted.emit()

    def _on_region_change_finished(self):
        if not self._mouse_dragging:
            self.editingFinished.emit()
Example #25
0
class ActionCollection(actioncollection.ActionCollection):
    name = "main"

    def createActions(self, parent=None):
        self.file_new = QAction(parent)
        self.file_open = QAction(parent)
        self.file_open_recent = QAction(parent)
        self.file_insert_file = QAction(parent)
        self.file_open_current_directory = QAction(parent)
        self.file_open_command_prompt = QAction(parent)
        self.file_save = QAction(parent)
        self.file_save_as = QAction(parent)
        self.file_save_copy_as = QAction(parent)
        self.file_save_all = QAction(parent)
        self.file_reload = QAction(parent)
        self.file_reload_all = QAction(parent)
        self.file_external_changes = QAction(parent)
        self.file_print_source = QAction(parent)
        self.file_close = QAction(parent)
        self.file_close_other = QAction(parent)
        self.file_close_all = QAction(parent)
        self.file_quit = QAction(parent)
        self.file_restart = QAction(parent)

        self.export_colored_html = QAction(parent)

        self.edit_undo = QAction(parent)
        self.edit_redo = QAction(parent)
        self.edit_cut = QAction(parent)
        self.edit_copy = QAction(parent)
        self.edit_copy_colored_html = QAction(parent)
        self.edit_paste = QAction(parent)
        self.edit_select_all = QAction(parent)
        self.edit_select_current_toplevel = QAction(parent)
        self.edit_select_none = QAction(parent)
        self.edit_select_full_lines_up = QAction(parent)
        self.edit_select_full_lines_down = QAction(parent)
        self.edit_find = QAction(parent)
        self.edit_find_next = QAction(parent)
        self.edit_find_previous = QAction(parent)
        self.edit_replace = QAction(parent)
        self.edit_preferences = QAction(parent)

        self.view_next_document = QAction(parent)
        self.view_previous_document = QAction(parent)
        self.view_wrap_lines = QAction(parent, checkable=True)
        self.view_scroll_up = QAction(parent)
        self.view_scroll_down = QAction(parent)

        self.window_new = QAction(parent)
        self.window_fullscreen = QAction(parent)
        self.window_fullscreen.setCheckable(True)

        self.help_manual = QAction(parent)
        self.help_whatsthis = QWhatsThis.createAction(parent)
        self.help_about = QAction(parent)
        self.help_bugreport = QAction(parent)

        # icons
        self.file_new.setIcon(icons.get('document-new'))
        self.file_open.setIcon(icons.get('document-open'))
        self.file_open_recent.setIcon(icons.get('document-open-recent'))
        self.file_open_current_directory.setIcon(icons.get('folder-open'))
        self.file_open_command_prompt.setIcon(icons.get('utilities-terminal'))
        self.file_save.setIcon(icons.get('document-save'))
        self.file_save_as.setIcon(icons.get('document-save-as'))
        self.file_save_copy_as.setIcon(icons.get('document-save-as'))
        self.file_save_all.setIcon(icons.get('document-save-all'))
        self.file_reload.setIcon(icons.get('reload'))
        self.file_reload_all.setIcon(icons.get('reload-all'))
        self.file_print_source.setIcon(icons.get('document-print'))
        self.file_close.setIcon(icons.get('document-close'))
        self.file_quit.setIcon(icons.get('application-exit'))

        self.edit_undo.setIcon(icons.get('edit-undo'))
        self.edit_redo.setIcon(icons.get('edit-redo'))
        self.edit_cut.setIcon(icons.get('edit-cut'))
        self.edit_copy.setIcon(icons.get('edit-copy'))
        self.edit_paste.setIcon(icons.get('edit-paste'))
        self.edit_select_all.setIcon(icons.get('edit-select-all'))
        self.edit_select_current_toplevel.setIcon(icons.get('edit-select'))
        self.edit_find.setIcon(icons.get('edit-find'))
        self.edit_find_next.setIcon(icons.get('go-down-search'))
        self.edit_find_previous.setIcon(icons.get('go-up-search'))
        self.edit_replace.setIcon(icons.get('edit-find-replace'))
        self.edit_preferences.setIcon(icons.get('preferences-system'))

        self.view_next_document.setIcon(icons.get('go-next'))
        self.view_previous_document.setIcon(icons.get('go-previous'))

        self.window_new.setIcon(icons.get('window-new'))
        self.window_fullscreen.setIcon(icons.get('view-fullscreen'))

        self.help_manual.setIcon(icons.get('help-contents'))
        self.help_whatsthis.setIcon(icons.get('help-contextual'))
        self.help_bugreport.setIcon(icons.get('tools-report-bug'))
        self.help_about.setIcon(icons.get('help-about'))

        # shortcuts
        self.file_new.setShortcuts(QKeySequence.New)
        self.file_open.setShortcuts(QKeySequence.Open)
        self.file_save.setShortcuts(QKeySequence.Save)
        self.file_save_as.setShortcuts(QKeySequence.SaveAs)
        self.file_close.setShortcuts(QKeySequence.Close)
        self.file_quit.setShortcuts(QKeySequence.Quit)

        self.edit_undo.setShortcuts(QKeySequence.Undo)
        self.edit_redo.setShortcuts(QKeySequence.Redo)
        self.edit_cut.setShortcuts(QKeySequence.Cut)
        self.edit_copy.setShortcuts(QKeySequence.Copy)
        self.edit_paste.setShortcuts(QKeySequence.Paste)
        self.edit_select_all.setShortcuts(QKeySequence.SelectAll)
        self.edit_select_current_toplevel.setShortcut(
            QKeySequence(Qt.SHIFT + Qt.CTRL + Qt.Key_B))
        self.edit_select_none.setShortcut(
            QKeySequence(Qt.SHIFT + Qt.CTRL + Qt.Key_A))
        self.edit_select_full_lines_up.setShortcut(
            QKeySequence(Qt.SHIFT + Qt.CTRL + Qt.Key_Up))
        self.edit_select_full_lines_down.setShortcut(
            QKeySequence(Qt.SHIFT + Qt.CTRL + Qt.Key_Down))
        self.edit_find.setShortcuts(QKeySequence.Find)
        self.edit_find_next.setShortcuts(QKeySequence.FindNext)
        self.edit_find_previous.setShortcuts(QKeySequence.FindPrevious)
        self.edit_replace.setShortcuts(QKeySequence.Replace)
        self.edit_preferences.setShortcuts(QKeySequence.Preferences)

        self.view_next_document.setShortcuts(QKeySequence.Forward)
        self.view_previous_document.setShortcuts(QKeySequence.Back)
        self.view_scroll_up.setShortcut(Qt.CTRL + Qt.Key_Up)
        self.view_scroll_down.setShortcut(Qt.CTRL + Qt.Key_Down)

        self.window_fullscreen.setShortcuts([
            QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_F),
            QKeySequence(Qt.Key_F11)
        ])

        self.help_manual.setShortcuts(QKeySequence.HelpContents)

        # Mac OS X-specific roles?
        if sys.platform.startswith('darwin'):
            import macosx
            if macosx.use_osx_menu_roles():
                self.file_quit.setMenuRole(QAction.QuitRole)
                self.edit_preferences.setMenuRole(QAction.PreferencesRole)
                self.help_about.setMenuRole(QAction.AboutRole)
            else:
                self.file_quit.setMenuRole(QAction.NoRole)
                self.edit_preferences.setMenuRole(QAction.NoRole)
                self.help_about.setMenuRole(QAction.NoRole)

    def translateUI(self):
        self.file_new.setText(_("action: new document", "&New"))
        self.file_open.setText(_("&Open..."))
        self.file_open_recent.setText(_("Open &Recent"))
        self.file_insert_file.setText(_("Insert from &File..."))
        self.file_open_current_directory.setText(_("Open Current Directory"))
        self.file_open_command_prompt.setText(_("Open Command Prompt"))
        self.file_save.setText(_("&Save"))
        self.file_save_as.setText(_("Save &As..."))
        self.file_save_copy_as.setText(_("Save Copy or Selection As..."))
        self.file_save_all.setText(_("Save All"))
        self.file_reload.setText(_("Re&load"))
        self.file_reload_all.setText(_("Reload All"))
        self.file_external_changes.setText(_("Check for External Changes..."))
        self.file_external_changes.setToolTip(
            _("Opens a window to check whether open documents were changed or "
              "deleted by other programs."))
        self.file_print_source.setText(_("Print Source..."))
        self.file_close.setText(_("&Close"))
        self.file_close_other.setText(_("Close Other Documents"))
        self.file_close_all.setText(_("Close All Documents and Session"))
        self.file_close_all.setToolTip(
            _("Closes all documents and leaves the current session."))
        self.file_quit.setText(_("&Quit"))
        self.file_restart.setText(
            _("Restart {appname}").format(appname=appinfo.appname))

        self.export_colored_html.setText(
            _("Export Source as Colored &HTML..."))

        self.edit_undo.setText(_("&Undo"))
        self.edit_redo.setText(_("Re&do"))
        self.edit_cut.setText(_("Cu&t"))
        self.edit_copy.setText(_("&Copy"))
        self.edit_copy_colored_html.setText(_("Copy as Colored &HTML"))
        self.edit_paste.setText(_("&Paste"))
        self.edit_select_all.setText(_("Select &All"))
        self.edit_select_current_toplevel.setText(_("Select &Block"))
        self.edit_select_none.setText(_("Select &None"))
        self.edit_select_full_lines_up.setText(_("Select Whole Lines Up"))
        self.edit_select_full_lines_down.setText(_("Select Whole Lines Down"))
        self.edit_find.setText(_("&Find..."))
        self.edit_find_next.setText(_("Find Ne&xt"))
        self.edit_find_previous.setText(_("Find Pre&vious"))
        self.edit_replace.setText(_("&Replace..."))
        self.edit_preferences.setText(_("Pr&eferences..."))

        self.view_next_document.setText(_("&Next Document"))
        self.view_previous_document.setText(_("&Previous Document"))
        self.view_wrap_lines.setText(_("Wrap &Lines"))
        self.view_scroll_up.setText(_("Scroll Up"))
        self.view_scroll_down.setText(_("Scroll Down"))

        self.window_new.setText(_("New &Window"))
        self.window_fullscreen.setText(_("&Fullscreen"))

        self.help_manual.setText(_("&User Guide"))
        self.help_whatsthis.setText(_("&What's This?"))
        self.help_bugreport.setText(_("Report a &Bug..."))
        self.help_about.setText(
            _("&About {appname}...").format(appname=appinfo.appname))
Example #26
0
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, app = None):
        QMainWindow.__init__(self, None)
        self.setupUi(self)

        self.app = app
        self.iface = backend.pm.Iface()

        self.busy = QProgressIndicator(self)
        self.busy.setFixedSize(QSize(20, 20))

        self.setWindowIcon(QIcon(":/data/package-manager.png"))

        self.setCentralWidget(MainWidget(self))
        self.cw = self.centralWidget()

        self.settingsDialog = SettingsDialog(self)

        self.initializeActions()
        self.initializeStatusBar()
        self.initializeTray()
        self.connectMainSignals()

        self.pdsMessageBox = PMessageBox(self)

    def connectMainSignals(self):
        self.cw.connectMainSignals()
        self.connect(QShortcut(QKeySequence(Qt.CTRL + Qt.Key_Tab),self),
                SIGNAL("activated()"), lambda: self.moveTab('next'))
        self.connect(QShortcut(QKeySequence(Qt.SHIFT + Qt.CTRL + Qt.Key_Tab),self),
                SIGNAL("activated()"), lambda: self.moveTab('prev'))
        self.connect(QShortcut(QKeySequence(Qt.CTRL + Qt.Key_F),self),
                SIGNAL("activated()"), self.cw.searchLine.setFocus)
        self.connect(QShortcut(QKeySequence(Qt.Key_F3),self),
                SIGNAL("activated()"), self.cw.searchLine.setFocus)

        self.connect(self.settingsDialog, SIGNAL("packagesChanged()"), self.cw.initialize)
        self.connect(self.settingsDialog, SIGNAL("packageViewChanged()"), self.cw.updateSettings)
        self.connect(self.settingsDialog, SIGNAL("traySettingChanged()"), self.tray.settingsChanged)
        self.connect(self.cw.state, SIGNAL("repositoriesChanged()"), self.tray.populateRepositoryMenu)
        self.connect(self.cw, SIGNAL("repositoriesUpdated()"), self.tray.updateTrayUnread)
        self.connect(qApp, SIGNAL("shutDown()"), self.slotQuit)

    def moveTab(self, direction):
        new_index = self.cw.stateTab.currentIndex() - 1
        if direction == 'next':
            new_index = self.cw.stateTab.currentIndex() + 1
        if new_index not in range(self.cw.stateTab.count()):
            new_index = 0
        self.cw.stateTab.setCurrentIndex(new_index)

    def initializeTray(self):
        self.tray = Tray(self, self.iface)
        self.connect(self.cw.operation, SIGNAL("finished(QString)"), self.trayAction)
        self.connect(self.cw.operation, SIGNAL("finished(QString)"), self.tray.stop)
        self.connect(self.cw.operation, SIGNAL("operationCancelled()"), self.tray.stop)
        self.connect(self.cw.operation, SIGNAL("started(QString)"), self.tray.animate)
        self.connect(self.tray, SIGNAL("showUpdatesSelected()"), self.trayShowUpdates)

    def trayShowUpdates(self):
        self.showUpgradeAction.setChecked(True)

        self.cw.switchState(StateManager.UPGRADE)

        KApplication.kApplication().updateUserTimestamp()

        self.show()
        self.raise_()

    def trayAction(self, operation):
        if not self.isVisible() and operation in ["System.Manager.updateRepository", "System.Manager.updateAllRepositories"]:
            self.tray.showPopup()
        if self.tray.isVisible() and operation in ["System.Manager.updatePackage",
                                                   "System.Manager.installPackage",
                                                   "System.Manager.removePackage"]:
            self.tray.updateTrayUnread()

    def initializeStatusBar(self):
        self.cw.mainLayout.insertWidget(0, self.busy)
        self.statusBar().addPermanentWidget(self.cw.actions, 1)
        self.statusBar().show()

        self.updateStatusBar('')

        self.connect(self.cw, SIGNAL("selectionStatusChanged(QString)"), self.updateStatusBar)
        self.connect(self.cw, SIGNAL("updatingStatus()"), self.statusWaiting)

    def initializeActions(self):
        self.initializeOperationActions()

    def initializeOperationActions(self):

        self.showAllAction = QAction(KIcon(("applications-other", "package_applications")), i18n("All Packages"), self)
        self.connect(self.showAllAction, SIGNAL("triggered()"), lambda:self.cw.switchState(StateManager.ALL))
        self.cw.stateTab.addTab(QWidget(), KIcon(("applications-other", "package_applications")), i18n("All Packages"))

        self.showInstallAction = QAction(KIcon(("list-add", "add")), i18n("Installable Packages"), self)
        self.connect(self.showInstallAction, SIGNAL("triggered()"), lambda:self.cw.switchState(StateManager.INSTALL))
        self.cw.stateTab.addTab(QWidget(), KIcon(("list-add", "add")), i18n("Installable Packages"))

        self.showRemoveAction = QAction(KIcon(("list-remove", "remove")), i18n("Installed Packages"), self)
        self.connect(self.showRemoveAction, SIGNAL("triggered()"), lambda:self.cw.switchState(StateManager.REMOVE))
        self.cw.stateTab.addTab(QWidget(), KIcon(("list-remove", "remove")), i18n("Installed Packages"))

        self.showUpgradeAction = QAction(KIcon(("system-software-update", "gear")), i18n("Updates"), self)
        self.connect(self.showUpgradeAction, SIGNAL("triggered()"), lambda:self.cw.switchState(StateManager.UPGRADE))
        self.cw.stateTab.addTab(QWidget(), KIcon(("system-software-update", "gear")), i18n("Updates"))

        self.showPreferences = QAction(KIcon(("preferences-system", "package_settings")), i18n("Settings"), self)
        self.connect(self.showPreferences, SIGNAL("triggered()"), self.settingsDialog.show)

        self.actionHelp = QAction(KIcon("help"), i18n("Help"), self)
        self.actionHelp.setShortcuts(QKeySequence.HelpContents)
        self.connect(self.actionHelp, SIGNAL("triggered()"), self.showHelp)

        self.actionQuit = QAction(KIcon("exit"), i18n("Quit"), self)
        self.actionQuit.setShortcuts(QKeySequence.Quit)
        self.connect(self.actionQuit, SIGNAL("triggered()"), qApp.exit)

        self.cw.menuButton.setMenu(QMenu('MainMenu', self.cw.menuButton))
        self.cw.menuButton.setIcon(KIcon(("preferences-system", "package_settings")))
        self.cw.menuButton.menu().clear()

        self.cw.contentHistory.hide()

        self.cw.menuButton.menu().addAction(self.showPreferences)
        self.cw.menuButton.menu().addSeparator()
        self.cw.menuButton.menu().addAction(self.actionHelp)
        self.cw.menuButton.menu().addAction(self.actionQuit)

        self.cw._states = {self.cw.state.ALL    :(0, self.showAllAction),
                           self.cw.state.INSTALL:(1, self.showInstallAction),
                           self.cw.state.REMOVE :(2, self.showRemoveAction),
                           self.cw.state.UPGRADE:(3, self.showUpgradeAction)}

        self.showAllAction.setChecked(True)
        self.cw.checkUpdatesButton.hide()
        self.cw.checkUpdatesButton.setIcon(KIcon(("view-refresh", "reload")))
        self.cw.showBasketButton.clicked.connect(self.cw.showBasket)

        # Little time left for the new ui
        self.menuBar().setVisible(False)
        self.cw.switchState(self.cw.state.ALL)

    def statusWaiting(self):
        self.updateStatusBar(i18n('Calculating dependencies...'), busy = True)

    def showHelp(self):
        self.Pds = pds.Pds()
        self.lang = localedata.setSystemLocale(justGet = True)

        if self.lang in os.listdir("/usr/share/package-manager/help"):
            pass
        else:
            self.lang = "en"

        if self.Pds.session == pds.Kde3 :
            os.popen("khelpcenter /usr/share/package-manager/help/%s/main_help.html" %(self.lang))
        else:
            helpdialog.HelpDialog(self,helpdialog.MAINAPP)


    def updateStatusBar(self, text, busy = False):
        if text == '':
            text = i18n("Currently your basket is empty.")
            self.busy.hide()
            self.cw.showBasketButton.hide()
        else:
            self.cw.showBasketButton.show()

        if busy:
            self.busy.busy()
            self.cw.showBasketButton.hide()
        else:
            self.busy.hide()

        self.cw.statusLabel.setText(text)
        self.cw.statusLabel.setToolTip(text)

    def queryClose(self):
        if config.PMConfig().systemTray():
            self.hide()
            return False
        return True

    def queryExit(self):
        if not self.iface.operationInProgress():
            if self.tray:
                del self.tray.notification
            return True
        return False

    def slotQuit(self):
        if self.iface.operationInProgress():
            return
Example #27
0
class ActionCollection(actioncollection.ActionCollection):
    name = "main"
    def createActions(self, parent=None):
        self.file_new = QAction(parent)
        self.file_open = QAction(parent)
        self.file_open_recent = QAction(parent)
        self.file_insert_file = QAction(parent)
        self.file_open_current_directory = QAction(parent)
        self.file_open_command_prompt = QAction(parent)
        self.file_save = QAction(parent)
        self.file_save_as = QAction(parent)
        self.file_save_copy_as = QAction(parent)
        self.file_save_all = QAction(parent)
        self.file_reload = QAction(parent)
        self.file_reload_all = QAction(parent)
        self.file_external_changes = QAction(parent)
        self.file_print_source = QAction(parent)
        self.file_close = QAction(parent)
        self.file_close_other = QAction(parent)
        self.file_close_all = QAction(parent)
        self.file_quit = QAction(parent)
        self.file_restart = QAction(parent)

        self.export_colored_html = QAction(parent)

        self.edit_undo = QAction(parent)
        self.edit_redo = QAction(parent)
        self.edit_cut = QAction(parent)
        self.edit_copy = QAction(parent)
        self.edit_copy_colored_html = QAction(parent)
        self.edit_paste = QAction(parent)
        self.edit_select_all = QAction(parent)
        self.edit_select_current_toplevel = QAction(parent)
        self.edit_select_none = QAction(parent)
        self.edit_select_full_lines_up = QAction(parent)
        self.edit_select_full_lines_down = QAction(parent)
        self.edit_find = QAction(parent)
        self.edit_find_next = QAction(parent)
        self.edit_find_previous = QAction(parent)
        self.edit_replace = QAction(parent)
        self.edit_preferences = QAction(parent)

        self.view_next_document = QAction(parent)
        self.view_previous_document = QAction(parent)
        self.view_wrap_lines = QAction(parent, checkable=True)
        self.view_scroll_up = QAction(parent)
        self.view_scroll_down = QAction(parent)

        self.window_new = QAction(parent)
        self.window_fullscreen = QAction(parent)
        self.window_fullscreen.setCheckable(True)

        self.help_manual = QAction(parent)
        self.help_whatsthis = QWhatsThis.createAction(parent)
        self.help_about = QAction(parent)
        self.help_bugreport = QAction(parent)

        # icons
        self.file_new.setIcon(icons.get('document-new'))
        self.file_open.setIcon(icons.get('document-open'))
        self.file_open_recent.setIcon(icons.get('document-open-recent'))
        self.file_open_current_directory.setIcon(icons.get('folder-open'))
        self.file_open_command_prompt.setIcon(icons.get('utilities-terminal'))
        self.file_save.setIcon(icons.get('document-save'))
        self.file_save_as.setIcon(icons.get('document-save-as'))
        self.file_save_copy_as.setIcon(icons.get('document-save-as'))
        self.file_save_all.setIcon(icons.get('document-save-all'))
        self.file_reload.setIcon(icons.get('reload'))
        self.file_reload_all.setIcon(icons.get('reload-all'))
        self.file_print_source.setIcon(icons.get('document-print'))
        self.file_close.setIcon(icons.get('document-close'))
        self.file_quit.setIcon(icons.get('application-exit'))

        self.edit_undo.setIcon(icons.get('edit-undo'))
        self.edit_redo.setIcon(icons.get('edit-redo'))
        self.edit_cut.setIcon(icons.get('edit-cut'))
        self.edit_copy.setIcon(icons.get('edit-copy'))
        self.edit_paste.setIcon(icons.get('edit-paste'))
        self.edit_select_all.setIcon(icons.get('edit-select-all'))
        self.edit_select_current_toplevel.setIcon(icons.get('edit-select'))
        self.edit_find.setIcon(icons.get('edit-find'))
        self.edit_find_next.setIcon(icons.get('go-down-search'))
        self.edit_find_previous.setIcon(icons.get('go-up-search'))
        self.edit_replace.setIcon(icons.get('edit-find-replace'))
        self.edit_preferences.setIcon(icons.get('preferences-system'))

        self.view_next_document.setIcon(icons.get('go-next'))
        self.view_previous_document.setIcon(icons.get('go-previous'))

        self.window_new.setIcon(icons.get('window-new'))
        self.window_fullscreen.setIcon(icons.get('view-fullscreen'))

        self.help_manual.setIcon(icons.get('help-contents'))
        self.help_whatsthis.setIcon(icons.get('help-contextual'))
        self.help_bugreport.setIcon(icons.get('tools-report-bug'))
        self.help_about.setIcon(icons.get('help-about'))

        # shortcuts
        self.file_new.setShortcuts(QKeySequence.New)
        self.file_open.setShortcuts(QKeySequence.Open)
        self.file_save.setShortcuts(QKeySequence.Save)
        self.file_save_as.setShortcuts(QKeySequence.SaveAs)
        self.file_close.setShortcuts(QKeySequence.Close)
        self.file_quit.setShortcuts(QKeySequence.Quit)

        self.edit_undo.setShortcuts(QKeySequence.Undo)
        self.edit_redo.setShortcuts(QKeySequence.Redo)
        self.edit_cut.setShortcuts(QKeySequence.Cut)
        self.edit_copy.setShortcuts(QKeySequence.Copy)
        self.edit_paste.setShortcuts(QKeySequence.Paste)
        self.edit_select_all.setShortcuts(QKeySequence.SelectAll)
        self.edit_select_current_toplevel.setShortcut(QKeySequence(Qt.SHIFT+Qt.CTRL+Qt.Key_B))
        self.edit_select_none.setShortcut(QKeySequence(Qt.SHIFT + Qt.CTRL + Qt.Key_A))
        self.edit_select_full_lines_up.setShortcut(QKeySequence(Qt.SHIFT + Qt.CTRL + Qt.Key_Up))
        self.edit_select_full_lines_down.setShortcut(QKeySequence(Qt.SHIFT + Qt.CTRL + Qt.Key_Down))
        self.edit_find.setShortcuts(QKeySequence.Find)
        self.edit_find_next.setShortcuts(QKeySequence.FindNext)
        self.edit_find_previous.setShortcuts(QKeySequence.FindPrevious)
        self.edit_replace.setShortcuts(QKeySequence.Replace)
        self.edit_preferences.setShortcuts(QKeySequence.Preferences)

        self.view_next_document.setShortcuts(QKeySequence.Forward)
        self.view_previous_document.setShortcuts(QKeySequence.Back)
        self.view_scroll_up.setShortcut(Qt.CTRL + Qt.Key_Up)
        self.view_scroll_down.setShortcut(Qt.CTRL + Qt.Key_Down)

        self.window_fullscreen.setShortcuts([QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_F), QKeySequence(Qt.Key_F11)])

        self.help_manual.setShortcuts(QKeySequence.HelpContents)

        # Mac OS X-specific roles?
        if sys.platform.startswith('darwin'):
            import macosx
            if macosx.use_osx_menu_roles():
                self.file_quit.setMenuRole(QAction.QuitRole)
                self.edit_preferences.setMenuRole(QAction.PreferencesRole)
                self.help_about.setMenuRole(QAction.AboutRole)
            else:
                self.file_quit.setMenuRole(QAction.NoRole)
                self.edit_preferences.setMenuRole(QAction.NoRole)
                self.help_about.setMenuRole(QAction.NoRole)

    def translateUI(self):
        self.file_new.setText(_("action: new document", "&New"))
        self.file_open.setText(_("&Open..."))
        self.file_open_recent.setText(_("Open &Recent"))
        self.file_insert_file.setText(_("Insert from &File..."))
        self.file_open_current_directory.setText(_("Open Current Directory"))
        self.file_open_command_prompt.setText(_("Open Command Prompt"))
        self.file_save.setText(_("&Save"))
        self.file_save_as.setText(_("Save &As..."))
        self.file_save_copy_as.setText(_("Save Copy or Selection As..."))
        self.file_save_all.setText(_("Save All"))
        self.file_reload.setText(_("Re&load"))
        self.file_reload_all.setText(_("Reload All"))
        self.file_external_changes.setText(_("Check for External Changes..."))
        self.file_external_changes.setToolTip(_(
            "Opens a window to check whether open documents were changed or "
            "deleted by other programs."))
        self.file_print_source.setText(_("Print Source..."))
        self.file_close.setText(_("&Close"))
        self.file_close_other.setText(_("Close Other Documents"))
        self.file_close_all.setText(_("Close All Documents and Session"))
        self.file_close_all.setToolTip(_("Closes all documents and leaves the current session."))
        self.file_quit.setText(_("&Quit"))
        self.file_restart.setText(_("Restart {appname}").format(appname=appinfo.appname))

        self.export_colored_html.setText(_("Export Source as Colored &HTML..."))

        self.edit_undo.setText(_("&Undo"))
        self.edit_redo.setText(_("Re&do"))
        self.edit_cut.setText(_("Cu&t"))
        self.edit_copy.setText(_("&Copy"))
        self.edit_copy_colored_html.setText(_("Copy as Colored &HTML"))
        self.edit_paste.setText(_("&Paste"))
        self.edit_select_all.setText(_("Select &All"))
        self.edit_select_current_toplevel.setText(_("Select &Block"))
        self.edit_select_none.setText(_("Select &None"))
        self.edit_select_full_lines_up.setText(_("Select Whole Lines Up"))
        self.edit_select_full_lines_down.setText(_("Select Whole Lines Down"))
        self.edit_find.setText(_("&Find..."))
        self.edit_find_next.setText(_("Find Ne&xt"))
        self.edit_find_previous.setText(_("Find Pre&vious"))
        self.edit_replace.setText(_("&Replace..."))
        self.edit_preferences.setText(_("Pr&eferences..."))

        self.view_next_document.setText(_("&Next Document"))
        self.view_previous_document.setText(_("&Previous Document"))
        self.view_wrap_lines.setText(_("Wrap &Lines"))
        self.view_scroll_up.setText(_("Scroll Up"))
        self.view_scroll_down.setText(_("Scroll Down"))

        self.window_new.setText(_("New &Window"))
        self.window_fullscreen.setText(_("&Fullscreen"))

        self.help_manual.setText(_("&User Guide"))
        self.help_whatsthis.setText(_("&What's This?"))
        self.help_bugreport.setText(_("Report a &Bug..."))
        self.help_about.setText(_("&About {appname}...").format(appname=appinfo.appname))
class MainWindow(QMainWindow):
    subWindows = []
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        self.setWindowTitle("Seabiscuit2")

        self.menuBar = QMenuBar()
        self.setMenuBar(self.menuBar)

        self.fileMenu = QMenu("&File")
        self.menuBar.addMenu(self.fileMenu)

        self.newWindowAction = QAction("&New Window", self)
        self.newWindowAction.setShortcut("Ctrl+N")
        self.newWindowAction.triggered.connect(self.newWindow)
        self.fileMenu.addAction(self.newWindowAction)

        self.editMenu = QMenu("&Edit")
        self.menuBar.addMenu(self.editMenu)

        self.toolsMenu = QMenu("&Tools")
        self.menuBar.addMenu(self.toolsMenu)

        self.historyAction = QAction("View &History", self)
        self.historyAction.setShortcut("Ctrl+H")
        self.historyAction.triggered.connect(self.loadHistory)
        self.toolsMenu.addAction(self.historyAction)

        self.clearHistoryAction = QAction("&Clear History", self)
        self.clearHistoryAction.setShortcut("Ctrl+Shift+Del")
        self.clearHistoryAction.triggered.connect(self.clearHistory)
        self.toolsMenu.addAction(self.clearHistoryAction)

        self.helpMenu = QMenu("&Help")
        self.menuBar.addMenu(self.helpMenu)

        self.readmeAction = QAction("View &README", self)
        self.readmeAction.setShortcut("F1")
        self.readmeAction.triggered.connect(self.loadReadme)
        self.helpMenu.addAction(self.readmeAction)

        self.aboutAction = QAction("&About Seabiscuit2", self)
        self.aboutAction.setShortcut("F2")
        self.aboutAction.triggered.connect(lambda: self.render("Seabiscuit version " + version + " (running on " + platform + ")"))
        self.helpMenu.addAction(self.aboutAction)

        self.toolBar = QToolBar()
        self.toolBar.setMovable(False)
        self.toolBar.setContextMenuPolicy(Qt.CustomContextMenu)
        self.addToolBar(self.toolBar)

        self.wv = QWebView()

        self.backAction = self.wv.pageAction(QWebPage.Back)
        self.backAction.setEnabled(True)
        self.backAction.setShortcut("Alt+Left")
        self.backAction.triggered.connect(lambda: self.mdiArea.currentSubWindow().widget().back())
        self.toolBar.addAction(self.backAction)

        self.forwardAction = self.wv.pageAction(QWebPage.Forward)
        self.forwardAction.setEnabled(True)
        self.forwardAction.setShortcut("Alt+Right")
        self.forwardAction.triggered.connect(lambda: self.mdiArea.currentSubWindow().widget().forward())
        self.toolBar.addAction(self.forwardAction)

        self.reloadAction = self.wv.pageAction(QWebPage.Reload)
        self.reloadAction.setShortcuts(["F5", "Ctrl+R"])
        self.reloadAction.triggered.connect(lambda: self.mdiArea.currentSubWindow().widget().reload())
        self.toolBar.addAction(self.reloadAction)

        self.locationBar = QLineEdit()
        self.locationBar.returnPressed.connect(self.loadCommand)
        self.toolBar.addWidget(self.locationBar)

        self.focusLocationBarAction = QAction(self)
        self.focusLocationBarAction.setShortcuts(["Ctrl+L", "Alt+D"])
        self.focusLocationBarAction.triggered.connect(self.locationBar.setFocus)
        self.focusLocationBarAction.triggered.connect(self.locationBar.selectAll)
        self.addAction(self.focusLocationBarAction)

        self.mdiArea = QMdiArea()
        self.setCentralWidget(self.mdiArea)

    def newWindow(self):
        s = SWebView(self)
        self.subWindows.append(s)
        self.mdiArea.addSubWindow(s)
        s.activateWindow()
        s.show()
        return s

    def loadHistory(self):
        self.newWindow()
        self.updateWeb(os.path.join(seabiscuit_home, "history.html"))

    def loadReadme(self):
        self.newWindow()
        self.updateWeb("file://" + os.path.join(sys.path[0], "README.html"))

    def closeEvent(self, ev):
        confirm = yes_no_question("Query", "Are you sure you want to quit?")
        if confirm:
            ev.accept()
            sys.exit()
        else:
            ev.ignore()

    def render(self, text):
        QMessageBox.question(None, "Seabiscuit2 says...", text.replace("\n", "<br>"))

    def updateWeb(self, url=None):
        if url != None:
            self.mdiArea.currentSubWindow().widget().load(QUrl.fromUserInput(url))

    def clearHistory(self):
        confirm = yes_no_question("Query", "Are you sure you want to clear the browser history?")
        if confirm:
            historyfile = open(os.path.join(seabiscuit_home, "history.html"), "w")
            historyfile.write("<html><head><script type='text/javascript'>function breakPage(url) {top.location = url}</script></head><body style=\"color: black; background: white;\"><h2>Browsing History</h2>\n")
            historyfile.close()

    def loadCommand(self):
        command = unicode(self.locationBar.text())
        if command.lower().startswith("browser:"):
            command = command.replace("browser:", "")
            webbrowser.open(command)
            self.render("The page has been loaded in your default Web browser.")
        elif command.lower().startswith("download:"):
            command = command.replace("download:", "")
            location = ""
            while not os.path.exists(location):
                location = unicode(QInputDialog.getText("Query", "Enter a valid folder to save your file under."))
                if not os.path.exists(location):
                    render("Invalid path!")
            os.chdir(location)
            os.system("wget '" + command + "'")
            os.chdir(path[0])
        else:
            self.updateWeb(command)
Example #29
0
    def createMenuBar(self):
        quitAction = QAction(self.tr("&Quit"), self)
        aboutAction = QAction(self.tr("&About"), self)
        aboutTatoebaAction = QAction(self.tr("About Tatoeba"), self)
        preferenceAction = QAction(self.tr("&Preference"), self)
        preferenceAction.triggered.connect(self.preference)

        quitAction.setShortcuts(QtGui.QKeySequence.Quit)

        listMenu = self.ui.menubar.addMenu(self.tr("&Lists"))

        addListAction = QAction(self.tr("&Add List"), self)
        listMenu.addAction(addListAction)
        addListAction.triggered.connect(self.addList)

        deleteListAction = QAction(self.tr("&Delete List"), self)
        listMenu.addAction(deleteListAction)
        deleteListAction.triggered.connect(self.deleteList)

        clearListAction = QAction(self.tr("C&lear List"), self)
        listMenu.addAction(clearListAction)
        clearListAction.setShortcut(self.tr("Ctrl+L"))
        clearListAction.triggered.connect(self.deleteAllSentence)

        insertAllTrAction = QAction(self.tr("Insert All Tranlastions"), self)
        listMenu.addAction(insertAllTrAction)
        insertAllTrAction.triggered.connect(self.insertAllTrById)

        exportAction = QAction(self.tr("Export For Anki"), self)
        listMenu.addAction(exportAction)
        exportAction.triggered.connect(self.exportForAnki)

        downloadListAction = QAction(self.tr("Download List"), self)
        listMenu.addAction(downloadListAction)
        downloadListAction.triggered.connect(self.startDownloadList)

        listMenu.addSeparator()
        listMenu.addAction(preferenceAction)
        listMenu.addSeparator()
        listMenu.addAction(quitAction)

        stMenu = self.ui.menubar.addMenu(self.tr("&Sentences"))
        getTrAction = QAction(self.tr("Get &Translations"), self)
        stMenu.addAction(getTrAction)

        gotoTatoebaAction = QAction(self.tr("&Go to Tatoeba"), self)
        stMenu.addAction(gotoTatoebaAction)
        gotoTatoebaAction.triggered.connect(self.gotoTatoeba)

        deleteAction = QAction(self.tr("&Delete Sentence..."), self)
        stMenu.addAction(deleteAction)
        deleteAction.triggered.connect(self.deleteSentence)

        deleteAction.setShortcut(self.tr("Ctrl+D"))
        gotoTatoebaAction.setShortcut(self.tr("Ctrl+G"))
        getTrAction.setShortcut(self.tr("Ctrl+T"))

        helpMenu = self.ui.menubar.addMenu(self.tr("&Help"))
        helpMenu.addAction(aboutAction)
        helpMenu.addAction(aboutTatoebaAction)

        getTrAction.triggered.connect(self.insertTrById)
        aboutTatoebaAction.triggered.connect(self.aboutTatoeba)
Example #30
0
    def create_actions(self):
        new_tab_action = QAction('&New Tab', self)
        new_tab_action.setShortcuts(QKeySequence.AddTab)
        self.connect(new_tab_action, SIGNAL('triggered()'), self.new_tab)
        self.new_tab_action = new_tab_action

        close_tab_action = QAction('&Close Tab', self)
        close_tab_action.setShortcuts(QKeySequence.Close)
        self.connect(close_tab_action, SIGNAL('triggered()'), self.close_tab)
        self.close_tab_action = close_tab_action

        open_action = QAction('&Open...', self)
        open_action.setShortcuts(QKeySequence.Open)
        self.connect(open_action, SIGNAL('triggered()'), self.open_file)
        self.open_action = open_action

        save_as_action = QAction('Save &As...', self)
        save_as_action.setShortcuts(QKeySequence.SaveAs)
        self.connect(save_as_action, SIGNAL('triggered()'), self.save_as_file)
        self.save_as_action = save_as_action

        exit_action = QAction('E&xit', self)
        exit_action.setMenuRole(QAction.QuitRole)
        self.connect(exit_action, SIGNAL('triggered()'),
                     self, SLOT('close()'))
        self.exit_action = exit_action

        next_tab_action = QAction('Next Tab', self)
        bindings = QKeySequence.keyBindings(QKeySequence.NextChild)
        if sys.platform == 'darwin':
            bindings.append('Meta+PgDown')
            bindings.append('Meta+Tab')
        else:
            bindings.append('Ctrl+PgDown')
        next_tab_action.setShortcuts(bindings)
        self.connect(next_tab_action, SIGNAL('triggered()'), self.focus_next_tab);
        self.addAction(next_tab_action)

        previous_tab_action = QAction('Previous Tab', self)
        bindings = QKeySequence.keyBindings(QKeySequence.PreviousChild)
        if sys.platform == 'darwin':
            bindings.append('Meta+PgUp')
            bindings.append('Meta+Shift+Tab')
        else:
            bindings.append('Ctrl+PgUp')
        previous_tab_action.setShortcuts(bindings)
        self.connect(previous_tab_action, SIGNAL('triggered()'), self.focus_previous_tab);
        self.addAction(previous_tab_action)
Example #31
0
class Actions(actioncollection.ActionCollection):
    name = "musicview"

    def createActions(self, panel):
        self.music_document_select = DocumentChooserAction(panel)
        self.music_print = QAction(panel)
        self.music_zoom_in = QAction(panel)
        self.music_zoom_out = QAction(panel)
        self.music_zoom_original = QAction(panel)
        self.music_zoom_combo = ZoomerAction(panel)
        self.music_fit_width = QAction(panel, checkable=True)
        self.music_fit_height = QAction(panel, checkable=True)
        self.music_fit_both = QAction(panel, checkable=True)
        self.music_maximize = QAction(panel)
        self.music_jump_to_cursor = QAction(panel)
        self.music_sync_cursor = QAction(panel, checkable=True)
        self.music_copy_image = QAction(panel)
        self.music_pager = PagerAction(panel)
        self.music_next_page = QAction(panel)
        self.music_prev_page = QAction(panel)
        self.music_reload = QAction(panel)

        self.music_print.setIcon(icons.get('document-print'))
        self.music_zoom_in.setIcon(icons.get('zoom-in'))
        self.music_zoom_out.setIcon(icons.get('zoom-out'))
        self.music_zoom_original.setIcon(icons.get('zoom-original'))
        self.music_fit_width.setIcon(icons.get('zoom-fit-width'))
        self.music_fit_height.setIcon(icons.get('zoom-fit-height'))
        self.music_fit_both.setIcon(icons.get('zoom-fit-best'))
        self.music_maximize.setIcon(icons.get('view-fullscreen'))
        self.music_jump_to_cursor.setIcon(icons.get('go-jump'))
        self.music_copy_image.setIcon(icons.get('edit-copy'))
        self.music_next_page.setIcon(icons.get('go-next'))
        self.music_prev_page.setIcon(icons.get('go-previous'))

        self.music_document_select.setShortcut(
            QKeySequence(Qt.SHIFT | Qt.CTRL | Qt.Key_O))
        self.music_print.setShortcuts(QKeySequence.Print)
        self.music_zoom_in.setShortcuts(QKeySequence.ZoomIn)
        self.music_zoom_out.setShortcuts(QKeySequence.ZoomOut)
        self.music_jump_to_cursor.setShortcut(QKeySequence(Qt.CTRL | Qt.Key_J))
        self.music_copy_image.setShortcut(
            QKeySequence(Qt.SHIFT | Qt.CTRL | Qt.Key_C))
        self.music_reload.setShortcut(QKeySequence(Qt.Key_F5))

    def translateUI(self):
        self.music_document_select.setText(_("Select Music View Document"))
        self.music_print.setText(_("&Print Music..."))
        self.music_zoom_in.setText(_("Zoom &In"))
        self.music_zoom_out.setText(_("Zoom &Out"))
        self.music_zoom_original.setText(_("Original &Size"))
        self.music_zoom_combo.setText(_("Zoom Music"))
        self.music_fit_width.setText(_("Fit &Width"))
        self.music_fit_height.setText(_("Fit &Height"))
        self.music_fit_both.setText(_("Fit &Page"))
        self.music_maximize.setText(_("&Maximize"))
        self.music_jump_to_cursor.setText(_("&Jump to Cursor Position"))
        self.music_sync_cursor.setText(_("S&ynchronize with Cursor Position"))
        self.music_copy_image.setText(_("Copy to &Image..."))
        self.music_next_page.setText(_("Next Page"))
        self.music_next_page.setIconText(_("Next"))
        self.music_prev_page.setText(_("Previous Page"))
        self.music_prev_page.setIconText(_("Previous"))
        self.music_reload.setText(_("&Reload"))
Example #32
0
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, app=None):
        QMainWindow.__init__(self, None)
        self.setupUi(self)

        self.app = app
        self.iface = backend.pm.Iface()

        self.busy = QProgressIndicator(self)
        self.busy.setFixedSize(QSize(20, 20))

        self.setWindowIcon(QIcon(":/data/package-manager.png"))

        self.setCentralWidget(MainWidget(self))
        self.cw = self.centralWidget()

        self.settingsDialog = SettingsDialog(self)

        self.initializeActions()
        self.initializeStatusBar()
        self.initializeTray()
        self.connectMainSignals()

        self.pdsMessageBox = PMessageBox(self)

    def connectMainSignals(self):
        self.cw.connectMainSignals()
        self.connect(QShortcut(QKeySequence(Qt.CTRL + Qt.Key_Tab), self),
                     SIGNAL("activated()"), lambda: self.moveTab('next'))
        self.connect(
            QShortcut(QKeySequence(Qt.SHIFT + Qt.CTRL + Qt.Key_Tab), self),
            SIGNAL("activated()"), lambda: self.moveTab('prev'))
        self.connect(QShortcut(QKeySequence(Qt.CTRL + Qt.Key_F), self),
                     SIGNAL("activated()"), self.cw.searchLine.setFocus)
        self.connect(QShortcut(QKeySequence(Qt.Key_F3), self),
                     SIGNAL("activated()"), self.cw.searchLine.setFocus)

        self.connect(self.settingsDialog, SIGNAL("packagesChanged()"),
                     self.cw.initialize)
        self.connect(self.settingsDialog, SIGNAL("packageViewChanged()"),
                     self.cw.updateSettings)
        self.connect(self.settingsDialog, SIGNAL("traySettingChanged()"),
                     self.tray.settingsChanged)
        self.connect(self.cw.state, SIGNAL("repositoriesChanged()"),
                     self.tray.populateRepositoryMenu)
        self.connect(self.cw, SIGNAL("repositoriesUpdated()"),
                     self.tray.updateTrayUnread)
        self.connect(qApp, SIGNAL("shutDown()"), self.slotQuit)

    def moveTab(self, direction):
        new_index = self.cw.stateTab.currentIndex() - 1
        if direction == 'next':
            new_index = self.cw.stateTab.currentIndex() + 1
        if new_index not in range(self.cw.stateTab.count()):
            new_index = 0
        self.cw.stateTab.setCurrentIndex(new_index)

    def initializeTray(self):
        self.tray = Tray(self, self.iface)
        self.connect(self.cw.operation, SIGNAL("finished(QString)"),
                     self.trayAction)
        self.connect(self.cw.operation, SIGNAL("finished(QString)"),
                     self.tray.stop)
        self.connect(self.cw.operation, SIGNAL("operationCancelled()"),
                     self.tray.stop)
        self.connect(self.cw.operation, SIGNAL("started(QString)"),
                     self.tray.animate)
        self.connect(self.tray, SIGNAL("showUpdatesSelected()"),
                     self.trayShowUpdates)

    def trayShowUpdates(self):
        self.showUpgradeAction.setChecked(True)

        self.cw.switchState(StateManager.UPGRADE)

        KApplication.kApplication().updateUserTimestamp()

        self.show()
        self.raise_()

    def trayAction(self, operation):
        if not self.isVisible() and operation in [
                "System.Manager.updateRepository",
                "System.Manager.updateAllRepositories"
        ]:
            self.tray.showPopup()
        if self.tray.isVisible() and operation in [
                "System.Manager.updatePackage",
                "System.Manager.installPackage", "System.Manager.removePackage"
        ]:
            self.tray.updateTrayUnread()

    def initializeStatusBar(self):
        self.cw.mainLayout.insertWidget(0, self.busy)
        self.statusBar().addPermanentWidget(self.cw.actions, 1)
        self.statusBar().show()

        self.updateStatusBar('')

        self.connect(self.cw, SIGNAL("selectionStatusChanged(QString)"),
                     self.updateStatusBar)
        self.connect(self.cw, SIGNAL("updatingStatus()"), self.statusWaiting)

    def initializeActions(self):
        self.initializeOperationActions()

    def initializeOperationActions(self):

        self.showAllAction = QAction(
            KIcon(("applications-other", "package_applications")),
            i18n("All Packages"), self)
        self.connect(self.showAllAction, SIGNAL("triggered()"),
                     lambda: self.cw.switchState(StateManager.ALL))
        self.cw.stateTab.addTab(
            QWidget(), KIcon(("applications-other", "package_applications")),
            i18n("All Packages"))

        self.showInstallAction = QAction(KIcon(("list-add", "add")),
                                         i18n("Installable Packages"), self)
        self.connect(self.showInstallAction, SIGNAL("triggered()"),
                     lambda: self.cw.switchState(StateManager.INSTALL))
        self.cw.stateTab.addTab(QWidget(), KIcon(("list-add", "add")),
                                i18n("Installable Packages"))

        self.showRemoveAction = QAction(KIcon(("list-remove", "remove")),
                                        i18n("Installed Packages"), self)
        self.connect(self.showRemoveAction, SIGNAL("triggered()"),
                     lambda: self.cw.switchState(StateManager.REMOVE))
        self.cw.stateTab.addTab(QWidget(), KIcon(("list-remove", "remove")),
                                i18n("Installed Packages"))

        self.showUpgradeAction = QAction(
            KIcon(("system-software-update", "gear")), i18n("Updates"), self)
        self.connect(self.showUpgradeAction, SIGNAL("triggered()"),
                     lambda: self.cw.switchState(StateManager.UPGRADE))
        self.cw.stateTab.addTab(QWidget(),
                                KIcon(("system-software-update", "gear")),
                                i18n("Updates"))

        self.showPreferences = QAction(
            KIcon(("preferences-system", "package_settings")),
            i18n("Settings"), self)
        self.connect(self.showPreferences, SIGNAL("triggered()"),
                     self.settingsDialog.show)

        self.actionHelp = QAction(KIcon("help"), i18n("Help"), self)
        self.actionHelp.setShortcuts(QKeySequence.HelpContents)
        self.connect(self.actionHelp, SIGNAL("triggered()"), self.showHelp)

        self.actionQuit = QAction(KIcon("exit"), i18n("Quit"), self)
        self.actionQuit.setShortcuts(QKeySequence.Quit)
        self.connect(self.actionQuit, SIGNAL("triggered()"), qApp.exit)

        self.cw.menuButton.setMenu(QMenu('MainMenu', self.cw.menuButton))
        self.cw.menuButton.setIcon(
            KIcon(("preferences-system", "package_settings")))
        self.cw.menuButton.menu().clear()

        self.cw.contentHistory.hide()

        self.cw.menuButton.menu().addAction(self.showPreferences)
        self.cw.menuButton.menu().addSeparator()
        self.cw.menuButton.menu().addAction(self.actionHelp)
        self.cw.menuButton.menu().addAction(self.actionQuit)

        self.cw._states = {
            self.cw.state.ALL: (0, self.showAllAction),
            self.cw.state.INSTALL: (1, self.showInstallAction),
            self.cw.state.REMOVE: (2, self.showRemoveAction),
            self.cw.state.UPGRADE: (3, self.showUpgradeAction)
        }

        self.showAllAction.setChecked(True)
        self.cw.checkUpdatesButton.hide()
        self.cw.checkUpdatesButton.setIcon(KIcon(("view-refresh", "reload")))
        self.cw.showBasketButton.clicked.connect(self.cw.showBasket)

        # Little time left for the new ui
        self.menuBar().setVisible(False)
        self.cw.switchState(self.cw.state.ALL)

    def statusWaiting(self):
        self.updateStatusBar(i18n('Calculating dependencies...'), busy=True)

    def showHelp(self):
        self.Pds = pds.Pds()
        self.lang = localedata.setSystemLocale(justGet=True)

        if self.lang in os.listdir("/usr/share/package-manager/help"):
            pass
        else:
            self.lang = "en"

        if self.Pds.session == pds.Kde3:
            os.popen(
                "khelpcenter /usr/share/package-manager/help/%s/main_help.html"
                % (self.lang))
        else:
            helpdialog.HelpDialog(self, helpdialog.MAINAPP)

    def updateStatusBar(self, text, busy=False):
        if text == '':
            text = i18n("Currently your basket is empty.")
            self.busy.hide()
            self.cw.showBasketButton.hide()
        else:
            self.cw.showBasketButton.show()

        if busy:
            self.busy.busy()
            self.cw.showBasketButton.hide()
        else:
            self.busy.hide()

        self.cw.statusLabel.setText(text)
        self.cw.statusLabel.setToolTip(text)

    def queryClose(self):
        if config.PMConfig().systemTray():
            self.hide()
            return False
        return True

    def queryExit(self):
        if not self.iface.operationInProgress():
            if self.tray:
                del self.tray.notification
            return True
        return False

    def slotQuit(self):
        if self.iface.operationInProgress():
            return
    def __init__(self, iface, layer, parent=None):
        QWidget.__init__(self, parent)
        self.iface = iface
        self.layer = layer

        uri = QgsDataSourceURI(layer.source())
        dbplugin = None
        db = None
        if layer.dataProvider().name() == 'postgres':
            dbplugin = createDbPlugin('postgis', 'postgres')
        elif layer.dataProvider().name() == 'spatialite':
            dbplugin = createDbPlugin('spatialite', 'spatialite')
        elif layer.dataProvider().name() == 'oracle':
            dbplugin = createDbPlugin('oracle', 'oracle')
        elif layer.dataProvider().name() == 'virtual':
            dbplugin = createDbPlugin('vlayers', 'virtual')
        elif layer.dataProvider().name() == 'ogr':
            dbplugin = createDbPlugin('gpkg', 'gpkg')
        if dbplugin:
            dbplugin.connectToUri(uri)
            db = dbplugin.db

        self.dbplugin = dbplugin
        self.db = db
        self.filter = ""
        self.allowMultiColumnPk = isinstance(db, PGDatabase) # at the moment only PostgreSQL allows a primary key to span multiple columns, spatialite doesn't
        self.aliasSubQuery = isinstance(db, PGDatabase) # only PostgreSQL requires subqueries to be aliases
        self.setupUi(self)
        self.setWindowTitle(
            u"%s - %s [%s]" % (self.windowTitle(), db.connection().connectionName(), db.connection().typeNameString()))

        self.defaultLayerName = 'QueryLayer'

        if self.allowMultiColumnPk:
            self.uniqueColumnCheck.setText(self.trUtf8("Column(s) with unique values"))
        else:
            self.uniqueColumnCheck.setText(self.trUtf8("Column with unique values"))

        self.editSql.setFocus()
        self.editSql.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.editSql.setMarginVisible(True)
        self.initCompleter()

        # allow copying results
        copyAction = QAction("copy", self)
        self.viewResult.addAction(copyAction)
        copyAction.setShortcuts(QKeySequence.Copy)

        copyAction.triggered.connect(self.copySelectedResults)

        self.btnExecute.clicked.connect(self.executeSql)
        self.btnSetFilter.clicked.connect(self.setFilter)
        self.btnClear.clicked.connect(self.clearSql)

        self.presetStore.clicked.connect(self.storePreset)
        self.presetDelete.clicked.connect(self.deletePreset)
        self.presetCombo.activated[str].connect(self.loadPreset)
        self.presetCombo.activated[str].connect(self.presetName.setText)

        self.updatePresetsCombobox()

        self.geomCombo.setEditable(True)
        self.geomCombo.lineEdit().setReadOnly(True)

        self.uniqueCombo.setEditable(True)
        self.uniqueCombo.lineEdit().setReadOnly(True)
        self.uniqueModel = QStandardItemModel(self.uniqueCombo)
        self.uniqueCombo.setModel(self.uniqueModel)
        if self.allowMultiColumnPk:
            self.uniqueCombo.setItemDelegate(QStyledItemDelegate())
            self.uniqueModel.itemChanged.connect(self.uniqueChanged)                # react to the (un)checking of an item
            self.uniqueCombo.lineEdit().textChanged.connect(self.uniqueTextChanged) # there are other events that change the displayed text and some of them can not be caught directly

        self.layerTypeWidget.hide()  # show if load as raster is supported
        #self.loadLayerBtn.clicked.connect(self.loadSqlLayer)
        self.updateLayerBtn.clicked.connect(self.updateSqlLayer)
        self.getColumnsBtn.clicked.connect(self.fillColumnCombos)

        self.queryBuilderFirst = True
        self.queryBuilderBtn.setIcon(QIcon(":/db_manager/icons/sql.gif"))
        self.queryBuilderBtn.clicked.connect(self.displayQueryBuilder)

        self.presetName.textChanged.connect(self.nameChanged)

        # Update from layer
        # Fisrtly the SQL from QgsDataSourceURI table
        sql = uri.table()
        if uri.keyColumn() == '_uid_':
            match = re.search('^\(SELECT .+ AS _uid_,\* FROM \((.*)\) AS _subq_.+_\s*\)$', sql, re.S)
            if match:
                sql = match.group(1)
        else:
            match = re.search('^\((SELECT .+ FROM .+)\)$', sql, re.S)
            if match:
                sql = match.group(1)
        self.editSql.setText(sql)
        self.executeSql()

        # Then the columns
        self.geomCombo.setCurrentIndex(self.geomCombo.findText(uri.geometryColumn(), Qt.MatchExactly))
        if uri.keyColumn() != '_uid_':
            self.uniqueColumnCheck.setCheckState(Qt.Checked)
            if self.allowMultiColumnPk:
                itemsData = uri.keyColumn().split(',')
                for item in self.uniqueModel.findItems("*", Qt.MatchWildcard):
                    if item.data() in itemsData:
                        item.setCheckState(Qt.Checked)
            else:
                keyColumn = uri.keyColumn()
                if self.uniqueModel.findItems(keyColumn):
                    self.uniqueCombo.setEditText(keyColumn)

        # Finally layer name, filter and selectAtId
        self.layerNameEdit.setText(layer.name())
        self.filter = uri.sql()
        if uri.selectAtIdDisabled():
            self.avoidSelectById.setCheckState(Qt.Checked)
Example #34
0
class Web_Page( QWebPage ):

    # =======================================================================
    def __init__(self, parent, parentMain, UID):

        # -------------------------------------------------------------------
        QWebPage.__init__(self, parent);

        # -------------------------------------------------------------------
        self.PARENT                                 = parentMain;
        self.UID                                    = UID;
        self.PARENT_TAB                             = parent;
        self.DEBUG                                  = False;
        self.LOG_TAG                                = str(self.__class__.__name__).upper();

        # -------------------------------------------------------------------
        self.L_BTN_CLICK                            = False;
        self.M_BTN_CLICK                            = False;
        self.R_BTN_CLICK                            = False;

        # -------------------------------------------------------------------
        self.PROGRESS_BAR                           = None;

        self.PROGRESS_BAR_PR                        = float( self.PARENT.WIDTH / 100);
        self.PROGRESS_BAR_W                         = 0;

        # -------------------------------------------------------------------

        # SEARCH_INPUT
        self.SEARCH_INPUT                           =  QLineEdit("", self.PARENT);
        self.SEARCH_INPUT.setGeometry(0, 615, 400, 30);
        self.SEARCH_INPUT.setStyleSheet("QLineEdit{ background-color: rgba(0,0,0, 180); font-size: 12px; font-family: monospace; color: #fff; padding-left: 10px; border-style: none;}");
        self.connect( self.SEARCH_INPUT, SIGNAL('textChanged(const QString)') , self.FIND_ON_PAGE );
        self.connect( self.SEARCH_INPUT, SIGNAL('returnPressed()') , self.FIND_ON_PAGE );
        #self.SEARCH_INPUT.setReadOnly( True );
        self.SEARCH_INPUT_IS_OPEN                   = False;
        self.SEARCH_INPUT.hide();

        # -------------------------------------------------------------------
        self.AGENTS                                 = [

            # Chrome 41.0.2228.0
            "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36",
            # Chrome 41.0.2227.1
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36",
            # Chrome 41.0.2227.0
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36",
            # Chrome 41.0.2226.0
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2226.0 Safari/537.36",
            # Chrome 41.0.2225.0
            "Mozilla/5.0 (Windows NT 6.4; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2225.0 Safari/537.36",
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2225.0 Safari/537.36",
            # Chrome 41.0.2224.3
            "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2224.3 Safari/537.36",
            # Chrome 40.0.2214.93
            "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36",
            # Chrome 37.0.2062.124
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36",
            # Chrome 37.0.2049.0
            "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36",
            "Mozilla/5.0 (Windows NT 4.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36",
            # Chrome 36.0.1985.67
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.67 Safari/537.36",
            "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.67 Safari/537.36",
            # Chrome 36.0.1985.125
            "Mozilla/5.0 (X11; OpenBSD i386) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36",
            # Chrome 36.0.1944.0
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1944.0 Safari/537.36",
            # Chrome 35.0.3319.102
            "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.3319.102 Safari/537.36",
            # Chrome 35.0.2309.372
            "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.2309.372 Safari/537.36",
            # Chrome 35.0.2117.157
            "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.2117.157 Safari/537.36",
            # Chrome 35.0.1916.47
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36",
            # Chrome 34.0.1866.237
            "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1866.237 Safari/537.36",
            # Chrome 34.0.1847.137
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/4E423F",
            # Chrome 34.0.1847.116
            "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36",
            "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10",
            

        ];


        # -------------------------------------------------------------------
        self.USER_AGENT                             = self.AGENTS[0];

        self.HEADERS                                = {
            "User-Agent"        : "[USER-AGENT]",
            "Accept"            : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",

            #"Accept-Language"   : "en-US,en;q=0.5",
            #"Referer"           : "https://btc-e.com/",
            #"Connection"        : "keep-alive",
            #"Cache-Control"     : "max-age=0",
            #"Cookie"            : ""

        }

        # -------------------------------------------------------------------
        #self.setContentEditable( True );
        self.setLinkDelegationPolicy( QWebPage.DelegateAllLinks );
        self.setForwardUnsupportedContent( True );
        self.setNetworkAccessManager( self.PARENT.NET_MANAGER );

        self.linkClicked.connect( self.ON_LINK_CLICKED );
        self.linkHovered.connect( self.ON_LINK_HOVERED );
        self.loadProgress.connect( self.ON_PAGE_LOAD_PROGRESS );

        self.downloadRequested.connect( self.PARENT.DOWNLOAD_MANAGER.REQUEST );
        self.unsupportedContent.connect( self.PARENT.DOWNLOAD_MANAGER.REQUEST );

        # -------------------------------------------------------------------
        self.PRINT_ACTION = QAction( self );
        self.PRINT_ACTION.setShortcuts( QKeySequence.Print );
        self.PRINT_ACTION.triggered.connect( self.PRINT );
        self.PARENT.addAction( self.PRINT_ACTION );

        # -------------------------------------------------------------------
        # SETTINGS
       
        self.SETTINGS                               = self.settings();
        self.SETTINGS.setDefaultTextEncoding("utf-8"); # <= [TO-CONFIG.FILE] + ALL FROM BELOW

        #self.SETTINGS.clearIconDatabase();
        #self.SETTINGS.clearMemoryCaches();

        self.SETTINGS.setAttribute( QWebSettings.AutoLoadImages, True );
        self.SETTINGS.setAttribute( QWebSettings.DnsPrefetchEnabled, True );
        self.SETTINGS.setAttribute( QWebSettings.JavascriptEnabled, True );
        self.SETTINGS.setAttribute( QWebSettings.JavaEnabled, False );
        self.SETTINGS.setAttribute( QWebSettings.PluginsEnabled, True );
        self.SETTINGS.setAttribute( QWebSettings.PrivateBrowsingEnabled, False );
        self.SETTINGS.setAttribute( QWebSettings.JavascriptCanOpenWindows, True ); #
        self.SETTINGS.setAttribute( QWebSettings.JavascriptCanCloseWindows, False ); #
        self.SETTINGS.setAttribute( QWebSettings.JavascriptCanAccessClipboard, True ); #
        self.SETTINGS.setAttribute( QWebSettings.DeveloperExtrasEnabled, True ); #
        self.SETTINGS.setAttribute( QWebSettings.SpatialNavigationEnabled, False );
        self.SETTINGS.setAttribute( QWebSettings.LinksIncludedInFocusChain, True );
        self.SETTINGS.setAttribute( QWebSettings.ZoomTextOnly, False );
        self.SETTINGS.setAttribute( QWebSettings.PrintElementBackgrounds, False );
        self.SETTINGS.setAttribute( QWebSettings.OfflineStorageDatabaseEnabled, True );
        self.SETTINGS.setAttribute( QWebSettings.OfflineWebApplicationCacheEnabled, True );
        self.SETTINGS.setAttribute( QWebSettings.LocalStorageEnabled, True );
        self.SETTINGS.setAttribute( QWebSettings.LocalStorageDatabaseEnabled, True );
        self.SETTINGS.setAttribute( QWebSettings.LocalContentCanAccessRemoteUrls, True );
        self.SETTINGS.setAttribute( QWebSettings.LocalContentCanAccessFileUrls, True );
        self.SETTINGS.setAttribute( QWebSettings.XSSAuditingEnabled, True );
        self.SETTINGS.setAttribute( QWebSettings.AcceleratedCompositingEnabled, True );
        self.SETTINGS.setAttribute( QWebSettings.TiledBackingStoreEnabled, False );
        self.SETTINGS.setAttribute( QWebSettings.FrameFlatteningEnabled, False );
        self.SETTINGS.setAttribute( QWebSettings.SiteSpecificQuirksEnabled, True );

        # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

        self.SETTINGS.enablePersistentStorage( self.PARENT.STORAGE_ROOT );
        self.SETTINGS.setLocalStoragePath( self.PARENT.STORAGE_ROOT+"local_storage/" );
        self.SETTINGS.setIconDatabasePath ( self.PARENT.STORAGE_ROOT+"icons_path/" )
        self.SETTINGS.setMaximumPagesInCache ( 10 );

        # FIXME: Create settings config file [TO-CONFIG.FILE]

        self.SETTINGS.setOfflineWebApplicationCachePath( self.PARENT.STORAGE_ROOT+"/cache/" );
        self.SETTINGS.setOfflineWebApplicationCacheQuota ( 25 * 1024 *1024 );

        self.SETTINGS.setOfflineStoragePath( self.PARENT.STORAGE_ROOT );
        self.SETTINGS.setOfflineStorageDefaultQuota ( 25 * 1024 *1024 );
        #self.SETTINGS.setObjectCacheCapacities (int cacheMinDeadCapacity, int cacheMaxDead, int totalCapacity)

        # -------------------------------------------------------------------
        self.INSPECTOR    = QWebInspector( None );

        """
        __init__ (self, QWidget parent = None)
        closeEvent (self, QCloseEvent event)
        bool event (self, QEvent)
        hideEvent (self, QHideEvent event)
        QWebPage page (self)
        resizeEvent (self, QResizeEvent event)
        setPage (self, QWebPage page)
        showEvent (self, QShowEvent event)
        QSize sizeHint (self)
        """

        # -------------------------------------------------------------------
        self.INIT();
        # -------------------------------------------------------------------

    # =======================================================================
    def INIT( self ):

        # -------------------------------------------------------------------
        self.HEADERS["User-Agent"] = self.USER_AGENT;

        # -------------------------------------------------------------------

    # =======================================================================
    def POST_INIT( self ):

        # -------------------------------------------------------------------
        self.PROGRESS_BAR = QFrame( self.PARENT.WEB_VIEWS[ self.UID ]["WEB_VIEW"] );
        self.PROGRESS_BAR.setStyleSheet( "QFrame{ background-color: #F00; }" );
        self.PROGRESS_BAR.setGeometry( 0, 0, 0, 5 );
        # -------------------------------------------------------------------

    # =======================================================================
    def EXEC_JS( self, _JS ):

        # -------------------------------------------------------------------
        #frame = self.PARENT.WEB_VIEW.page().mainFrame();
        #frame = self.mainFrame();
        #frame.evaluateJavaScript( _JS );
        
        self.mainFrame().evaluateJavaScript( _JS.encode("utf-8") );
        
        # -------------------------------------------------------------------

    # =======================================================================
    def GET_EXTENTIONS( self ):

        # -------------------------------------------------------------------
        #supportsExtension();
        pass;
        # -------------------------------------------------------------------

    # =======================================================================
    def GET_META_DATA( self ):

        # -------------------------------------------------------------------
        print( "GET_META_DATA:" );

        frame = self.mainFrame();

        meta_data =frame.metaData(); #dict-of-QString-list-of-QString metaData

        for meta in meta_data:
            print(meta);

        # -------------------------------------------------------------------

    # =======================================================================
    def GET_PAGE_HTML( self ):

        # -------------------------------------------------------------------
        frame = self.mainFrame();
        return unicode(frame.toHtml()).encode('utf-8');

        # -------------------------------------------------------------------

    # =======================================================================
    def GET_PAGE_TITLE( self ):

        # -------------------------------------------------------------------
        return str(self.mainFrame().title());

        # -------------------------------------------------------------------

    # =======================================================================
    def CMD( self, _CMD ):

        # -------------------------------------------------------------------
        #__exec:page:exec:js:function_name

        # -------------------------------------------------------------------
        try:
    
            # -----------------------------------------------
            if _CMD[0] == "exec":
                if _CMD[1] == "js":

                    self.EXEC_JS( "".join(_CMD[2:]) );
                    self.LOCAL_INFO_LOG( str(_CMD) );
                    return True;

            # -----------------------------------------------
            elif _CMD[0] == "set":
                if _CMD[1] == "user-agent":

                    self.USER_AGENT = "".join(_CMD[2:]).replace('\"', '\\"').replace("\'", "\\'");
                    self.EXEC_JS( "alert('set:user-agent:"+self.USER_AGENT+"');" );
                    self.LOCAL_INFO_LOG( str(_CMD) );
                    return True;

            # -----------------------------------------------
            elif _CMD[0] == "get":
                if _CMD[1] == "user-agent":

                    self.EXEC_JS( "alert('get:user-agent:"+self.USER_AGENT+"');" );
                    self.LOCAL_INFO_LOG( str(_CMD) );
                    return True;

            # -----------------------------------------------

            self.LOCAL_ERROR_LOG( "UNKNOWN: "+str(_CMD)+" CMD" );                    
            return False;

            # -----------------------------------------------

        except Exception as _err:
            self.LOCAL_ERROR_LOG( str(_CMD)+": "+str(_err) );
            return False;
    
        # -------------------------------------------------------------------

    # =======================================================================
    def AAA_user_BBB_AgentForUrl( self, _url ):

        # -------------------------------------------------------------------
        # Chrome Win/NT 32 Doc-Browser');

        #print("-------------------------------------------------------------")
        #_ByteArray = QUrl.toPercentEncoding( _url.toString(), "{}", " ");
       
        #encoded_url = str( _url.encodedQuery() )
        #print( encoded_url );


        """
        print( "authority(): "+str( _url.authority() ) );
        print( "encodedHost(): "+str( _url.encodedHost() ) );
        print( "encodedPath(): "+str( _url.encodedPath() ) );
        print( "encodedQuery(): "+str( _url.encodedQuery() ) );
        
        print( "encodedUserName(): "+str( _url.encodedUserName() ) );
        print( "host(): "+str( _url.host() ) );
        print( "isLocalFile(): "+str( _url.isLocalFile() ) );
        print( "path(): "+str( _url.path() ) );
        print( "port(): "+str( _url.port() ) );
        print( "userInfo(): "+str( _url.userInfo() ) );
        print( "userName(): "+str( _url.userName() ) );
        print( "topLevelDomain(): "+str( _url.topLevelDomain() ) );
        print( "toString(): "+str( _url.toString() ) );
        """


        #print("-------------------------------------------------------------")
        return self.USER_AGENT;
        # -------------------------------------------------------------------

    # =======================================================================
    def REPAINT_REQUESTED ( self, _QRect ): #repaintRequested (const QRect&)

        # -------------------------------------------------------------------
        print("NOT-IMPLEMENTED: repaintRequested (const QRect&):");
        # -------------------------------------------------------------------
    
    # =======================================================================
    def SHOW_INSPECTOR( self ):

        # -------------------------------------------------------------------
        self.INSPECTOR.setPage( self );


        self.INSPECTOR.setGeometry( 0,0, 800, 450 );
        self.INSPECTOR.show( );
        #self.INSPECTOR.showMaximized( );

        toolbar_items = [
            ".elements", ".resources", ".network", ".scripts", 
            ".timeline", ".profiles", ".audits", ".console"
        ];

        self.mainFrame().evaluateJavaScript("""
            document.addEventListener('DOMContentLoaded',function(){
                setTimeout(function(){
                    document.querySelector('.toolbar-item.network').click()
                }, 2000);
            });
        """);

        # -------------------------------------------------------------------

    # =======================================================================
    def ON_LINK_HOVERED(self, _url_A, _url_B, _url_C ): # (const QString&,const QString&,const QString&)

        # -------------------------------------------------------------------
        #print( "ON_LINK_HOVERED: "+self.UID+": ["+str(_url_A)+"]" );
        
        self.PARENT.STATUS_BAR.setText( unicode(str(_url_A)) );
        # -------------------------------------------------------------------

    # =======================================================================
    def ON_LINK_CLICKED(self, _url):

        # -------------------------------------------------------------------
        _url = unicode( str(_url.toString()).replace("file://", "") );

        # -------------------------------------------------------------------
        #print("ON_LINK_CLICKED: "+self.UID );

        if self.M_BTN_CLICK:
            self.PARENT.CREATE_TAB( _url );
            self.PARENT.URL_BAR.SET_TEXT( _url );

        else:
            self.PARENT.URL_BAR.SET_TEXT( _url );
            self.PARENT.GO_TO_URL();


        self.PARENT.HISTORY_HANDLER.hide();
        # -------------------------------------------------------------------
        #toAscii();
        #toUtf8();
        #toLatin1();
        #toLocal8Bit();
        self.L_BTN_CLICK = False;
        self.M_BTN_CLICK = False;
        self.R_BTN_CLICK = False;
        # -------------------------------------------------------------------

    # =======================================================================
    def ON_PAGE_LOAD_PROGRESS(self, _int_pr):

        # -------------------------------------------------------------------
        if _int_pr >= 100:

            if self.PARENT.CURRENT_TAB_BAR_UID == self.UID:
                self.PARENT.LOADING_BAR.setText( "Loading: Done." );
            self.PROGRESS_BAR_W = 0;


        else:

            if self.PARENT.CURRENT_TAB_BAR_UID == self.UID:
                self.PARENT.LOADING_BAR.setText( "Loading: ["+str(_int_pr)+"]" );

            self.PROGRESS_BAR_W = self.PROGRESS_BAR_PR * _int_pr;

        self.PROGRESS_BAR.setGeometry( 0, 0, self.PROGRESS_BAR_W, 5 );
        # -------------------------------------------------------------------

    # =======================================================================
    def SEARCH_INPUT_CTRL( self, _action ):

        # -------------------------------------------------------------------
        if _action == "show":
            self.SEARCH_INPUT_IS_OPEN = True;
            self.SEARCH_INPUT.setFocus();
            self.SEARCH_INPUT.show();

        else:
            self.SEARCH_INPUT_IS_OPEN = False;
            self.SEARCH_INPUT.clearFocus();
            self.SEARCH_INPUT.hide();
        # -------------------------------------------------------------------

    # =======================================================================
    def FIND_ON_PAGE(self):

        # -------------------------------------------------------------------
        #print("FIND_ON_PAGE: "+self.UID );

        try:

            self.SEARCH_INPUT.setFocus();
            self.SEARCH_INPUT_CTRL("show");

            _value = unicode( str(self.SEARCH_INPUT.text()).strip() );

            #findText (self, QString subString, FindFlags options = 0)
            self.findText (_value, QWebPage.FindWrapsAroundDocument);

            # QWebPage.HighlightAllOccurrences

        except Exception as _err:
            self.LOCAL_ERROR_LOG( str(_err) );

        # -------------------------------------------------------------------

    # =======================================================================
    def PRINT( self ):

        # -------------------------------------------------------------------
        try: 

            pdf_name = self.GET_PAGE_TITLE()+"_"+str(self.PARENT.GET_TIME(True))+"_";
            pdf_name = pdf_name.replace( " ", "-" ).replace( ":", "-" )+".pdf";

            self.PRINTER = QPrinter( QPrinter.ScreenResolution );
            self.PRINTER.setFontEmbeddingEnabled( False );
            self.PRINTER.setFullPage( True );
            #self.PRINTER.setPrinterName ("name of printer");
            #self.PRINTER.setPrintProgram ( "print program");

            self.PRINTER.setOutputFileName ( self.PARENT.DOWNLOAD_DIR+pdf_name );

            # ------ >
            #self.PRINTER.setOutputFormat( QPrinter.NativeFormat ); # <= IMAGE
            self.PRINTER.setOutputFormat( QPrinter.PdfFormat ); # <= TEXT
            #self.PRINTER.setOutputFormat( QPrinter.PostScriptFormat ); # ???

            #QPrinter will print output using a method defined by the platform it is running on. 
            # This mode is the default when printing directly to a printer.
            #QPrinter.NativeFormat [0]   
            
            #QPrinter will generate its output as a searchable PDF file. This mode is the default when printing to a file.
            #QPrinter.PdfFormat [1]   

            #QPrinter will generate its output as in the PostScript format. (This feature was introduced in Qt 4.2.)
            #QPrinter.PostScriptFormat [2]

            self.mainFrame().print_( self.PRINTER );

            self.LOCAL_INFO_LOG( "PDF: Saved ["+str(self.PARENT.DOWNLOAD_DIR+pdf_name)+"]" );


        except Exception as _err:
            self.LOCAL_ERROR_LOG( str(_err) );

        # -------------------------------------------------------------------

    # =======================================================================
    def SEND_ESC( self ):

        # -------------------------------------------------------------------
        #print("SEND_ESC: START");
        js = '''
                
            try{

                var e = document.createEvent('KeyboardEvent');
                e.initKeyboardEvent("keyup", true, true, window, 0,0,0,0,0, 27,0 );
                document.dispatchEvent(e);

                var e = document.createEvent('KeyboardEvent');
                e.initKeyboardEvent("keydown", true, true, window, 0,0,0,0,0, 27,0 );
                document.dispatchEvent(e);

                var e = document.createEvent('KeyboardEvent');
                e.initKeyboardEvent("keypress", true, true, window, 0,0,0,0,0, 27,0 );
                document.dispatchEvent(e);



            }catch(e){
                alert(e);
            }

        '''


        # -------------------------------------------------------------------
        self.mainFrame().evaluateJavaScript( js );
        #print("SEND_ESC: DONE");
        # -------------------------------------------------------------------

    # =======================================================================
    def event( self, _evt ):

        # -------------------------------------------------------------------
        #self.L_BTN_CLICK = False;
        #self.M_BTN_CLICK = False;
        #self.R_BTN_CLICK = False;

        # -------------------------------------------------------------------
        # http://pyqt.sourceforge.net/Docs/PyQt4/qevent.html#Type-enum
        #print( _evt.type() );
        # -------------------------------------------------------------------
        #if _evt.type() == QEvent.FocusOut:      # (QFocusEvent) == 9 == focus OUT BY CLICK
        #elif _evt.type() == QEvent.FocusIn:     # (QFocusEvent) == 8 == focus IN BY CLICK

        # -------------------------------------------------------------------
        #if _evt.type() == QEvent.ContextMenu:   # (QContextMenuEvent) == 82

        # -------------------------------------------------------------------
        #QEvent.MouseButtonDblClick  4   Mouse press again (QMouseEvent).
        #QEvent.MouseButtonRelease   3   Mouse release (QMouseEvent).
        #QPoint _evt.globalPos(); | int _evt.global[X|Y](); | QPoint _evt.pos(); | QPointF _evt.posF(); | int _evt.[x|y]()
        #_evt.button() == ( Qt.LeftButton | Qt.RightButton | Qt.MidButton )
        if _evt.type() == QEvent.MouseButtonPress: # 2   Mouse press (QMouseEvent).

            #print( "WEB_PAGE["+str(self.UID)+"].event:" );
            if _evt.button() == Qt.LeftButton:
                #print("Qt.LeftButton: "+str(Qt.LeftButton))
                self.L_BTN_CLICK = True;

            elif _evt.button() == Qt.MidButton:
                #print("Qt.MidButton: "+str(Qt.MidButton))
                self.M_BTN_CLICK = True;
            
            elif _evt.button() == Qt.RightButton:
                #print("Qt.RightButton: "+str(Qt.RightButton))
                self.R_BTN_CLICK = True;

        # -------------------------------------------------------------------
        """
        #QEvent.KeyPress 6   Key press (QKeyEvent).
        #QEvent.KeyRelease   7   Key release (QKeyEvent).
        if _evt.type() == QEvent.KeyRelease:
            print("KeyRelease: ["+str(_evt.text())+", "+str(_evt.nativeScanCode())+", "+str(_evt.key())+"]");

        int count (self)
        bool isAutoRepeat (self)
        int key (self)
        bool matches (self, QKeySequence.StandardKey key)
        Qt.KeyboardModifiers modifiers (self)
        int nativeModifiers (self)
        int nativeScanCode (self)
        int nativeVirtualKey (self)
        QString text (self)
        """

        # -------------------------------------------------------------------

        """
        if _evt.type() == QEvent.Enter:         # 10

            self.setStyleSheet( self.STL["hovered"] );
            self.HAS_FOCUS = True;

        elif _evt.type() == QEvent.Leave:       # 11 

            self.setStyleSheet( self.STL["default"] );
            self.HAS_FOCUS = False;
        """

        # -------------------------------------------------------------------
        return QWebPage.event(self, _evt);
        # -------------------------------------------------------------------

    # =======================================================================
    def LOCAL_INFO_LOG( self, _msg, METHOD=None ):

        # -------------------------------------------------------------------
        if METHOD is None:
            self.PARENT.LOCAL_INFO_LOG( "['"+self.LOG_TAG+"']: ["+_msg+"]" );
        else:
            self.PARENT.LOCAL_INFO_LOG( "['"+self.LOG_TAG+"."+METHOD+"']: ["+_msg+"]" );
        # -------------------------------------------------------------------

    # =======================================================================
    def LOCAL_ERROR_LOG( self, _msg, METHOD=None ):

        # -------------------------------------------------------------------
        if self.DEBUG or self.PARENT.DEBUG_GLOBAL: self.PARENT.DEBUGGER.DEBUG();
        # -------------------------------------------------------------------
        if METHOD is None:
            self.PARENT.LOCAL_ERROR_LOG( "['"+self.LOG_TAG+"']: ["+_msg+"]" );
        else:
            self.PARENT.LOCAL_ERROR_LOG( "['"+self.LOG_TAG+"."+METHOD+"']: ["+_msg+"]" );
        # -------------------------------------------------------------------

    # =======================================================================
    def LOCAL_WARNING_LOG( self, _msg, METHOD=None ):

        # -------------------------------------------------------------------
        if METHOD is None:
            self.PARENT.LOCAL_WARNING_LOG( "['"+self.LOG_TAG+"']: ["+_msg+"]" );
        else:
            self.PARENT.LOCAL_WARNING_LOG( "['"+self.LOG_TAG+"."+METHOD+"']: ["+_msg+"]" );
Example #35
0
    def __init__(self, iface, db, parent=None):
        QWidget.__init__(self, parent)
        self.iface = iface
        self.db = db
        self.allowMultiColumnPk = isinstance(db, PGDatabase) # at the moment only PostGIS allows a primary key to span multiple columns, spatialite doesn't
        self.setupUi(self)
        self.setWindowTitle(
            u"%s - %s [%s]" % (self.windowTitle(), db.connection().connectionName(), db.connection().typeNameString()))

        self.defaultLayerName = 'QueryLayer'

        if self.allowMultiColumnPk:
            self.uniqueColumnCheck.setText(self.trUtf8("Column(s) with unique values"))
        else:
            self.uniqueColumnCheck.setText(self.trUtf8("Column with unique values"))

        self.editSql.setFocus()
        self.editSql.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.initCompleter()

        # allow to copy results
        copyAction = QAction("copy", self)
        self.viewResult.addAction(copyAction)
        copyAction.setShortcuts(QKeySequence.Copy)

        copyAction.triggered.connect(self.copySelectedResults)

        self.btnExecute.clicked.connect(self.executeSql)
        self.btnClear.clicked.connect(self.clearSql)

        self.presetStore.clicked.connect(self.storePreset)
        self.presetDelete.clicked.connect(self.deletePreset)
        self.presetCombo.activated[str].connect(self.loadPreset)
        self.presetCombo.activated[str].connect(self.presetName.setText)

        self.updatePresetsCombobox()

        self.geomCombo.setEditable(True)
        self.geomCombo.lineEdit().setReadOnly(True)

        self.uniqueCombo.setEditable(True)
        self.uniqueCombo.lineEdit().setReadOnly(True)
        self.uniqueModel = QStandardItemModel(self.uniqueCombo)
        self.uniqueCombo.setModel(self.uniqueModel)
        if self.allowMultiColumnPk:
            self.uniqueCombo.setItemDelegate(QStyledItemDelegate())
            self.uniqueModel.itemChanged.connect(self.uniqueChanged)                # react to the (un)checking of an item
            self.uniqueCombo.lineEdit().textChanged.connect(self.uniqueTextChanged) # there are other events that change the displayed text and some of them can not be caught directly

        # hide the load query as layer if feature is not supported
        self._loadAsLayerAvailable = self.db.connector.hasCustomQuerySupport()
        self.loadAsLayerGroup.setVisible(self._loadAsLayerAvailable)
        if self._loadAsLayerAvailable:
            self.layerTypeWidget.hide()  # show if load as raster is supported
            self.loadLayerBtn.clicked.connect(self.loadSqlLayer)
            self.getColumnsBtn.clicked.connect(self.fillColumnCombos)
            self.loadAsLayerGroup.toggled.connect(self.loadAsLayerToggled)
            self.loadAsLayerToggled(False)

        self._createViewAvailable = self.db.connector.hasCreateSpatialViewSupport()
        self.btnCreateView.setVisible(self._createViewAvailable)
        if self._createViewAvailable:
            self.btnCreateView.clicked.connect(self.createView)

        self.queryBuilderFirst = True
        self.queryBuilderBtn.setIcon(QIcon(":/db_manager/icons/sql.gif"))
        self.queryBuilderBtn.clicked.connect(self.displayQueryBuilder)

        self.presetName.textChanged.connect(self.nameChanged)
Example #36
0
    def __init__(self, iface, layer, parent=None):
        QWidget.__init__(self, parent)
        self.iface = iface
        self.layer = layer

        uri = QgsDataSourceUri(layer.source())
        dbplugin = None
        db = None
        if layer.dataProvider().name() == 'postgres':
            dbplugin = createDbPlugin('postgis', 'postgres')
        elif layer.dataProvider().name() == 'spatialite':
            dbplugin = createDbPlugin('spatialite', 'spatialite')
        elif layer.dataProvider().name() == 'oracle':
            dbplugin = createDbPlugin('oracle', 'oracle')
        elif layer.dataProvider().name() == 'virtual':
            dbplugin = createDbPlugin('vlayers', 'virtual')
        if dbplugin:
            dbplugin.connectToUri(uri)
            db = dbplugin.db

        self.dbplugin = dbplugin
        self.db = db
        self.filter = ""
        self.allowMultiColumnPk = isinstance(db, PGDatabase) # at the moment only PostgreSQL allows a primary key to span multiple columns, spatialite doesn't
        self.aliasSubQuery = isinstance(db, PGDatabase) # only PostgreSQL requires subqueries to be aliases
        self.setupUi(self)
        self.setWindowTitle(
            u"%s - %s [%s]" % (self.windowTitle(), db.connection().connectionName(), db.connection().typeNameString()))

        self.defaultLayerName = 'QueryLayer'

        if self.allowMultiColumnPk:
            self.uniqueColumnCheck.setText(self.trUtf8("Column(s) with unique values"))
        else:
            self.uniqueColumnCheck.setText(self.trUtf8("Column with unique values"))

        self.editSql.setFocus()
        self.editSql.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.editSql.setMarginVisible(True)
        self.initCompleter()

        # allow copying results
        copyAction = QAction("copy", self)
        self.viewResult.addAction(copyAction)
        copyAction.setShortcuts(QKeySequence.Copy)

        copyAction.triggered.connect(self.copySelectedResults)

        self.btnExecute.clicked.connect(self.executeSql)
        self.btnSetFilter.clicked.connect(self.setFilter)
        self.btnClear.clicked.connect(self.clearSql)

        self.presetStore.clicked.connect(self.storePreset)
        self.presetDelete.clicked.connect(self.deletePreset)
        self.presetCombo.activated[str].connect(self.loadPreset)
        self.presetCombo.activated[str].connect(self.presetName.setText)

        self.updatePresetsCombobox()

        self.geomCombo.setEditable(True)
        self.geomCombo.lineEdit().setReadOnly(True)

        self.uniqueCombo.setEditable(True)
        self.uniqueCombo.lineEdit().setReadOnly(True)
        self.uniqueModel = QStandardItemModel(self.uniqueCombo)
        self.uniqueCombo.setModel(self.uniqueModel)
        if self.allowMultiColumnPk:
            self.uniqueCombo.setItemDelegate(QStyledItemDelegate())
            self.uniqueModel.itemChanged.connect(self.uniqueChanged)                # react to the (un)checking of an item
            self.uniqueCombo.lineEdit().textChanged.connect(self.uniqueTextChanged) # there are other events that change the displayed text and some of them can not be caught directly

        self.layerTypeWidget.hide()  # show if load as raster is supported
        #self.loadLayerBtn.clicked.connect(self.loadSqlLayer)
        self.updateLayerBtn.clicked.connect(self.updateSqlLayer)
        self.getColumnsBtn.clicked.connect(self.fillColumnCombos)

        self.queryBuilderFirst = True
        self.queryBuilderBtn.setIcon(QIcon(":/db_manager/icons/sql.gif"))
        self.queryBuilderBtn.clicked.connect(self.displayQueryBuilder)

        self.presetName.textChanged.connect(self.nameChanged)

        # Update from layer
        # Fisrtly the SQL from QgsDataSourceUri table
        sql = uri.table()
        if uri.keyColumn() == '_uid_':
            match = re.search('^\(SELECT .+ AS _uid_,\* FROM \((.*)\) AS _subq_.+_\s*\)$', sql, re.S)
            if match:
                sql = match.group(1)
        else:
            match = re.search('^\((SELECT .+ FROM .+)\)$', sql, re.S)
            if match:
                sql = match.group(1)
        self.editSql.setText(sql)
        self.executeSql()

        # Then the columns
        self.geomCombo.setCurrentIndex(self.geomCombo.findText(uri.geometryColumn(), Qt.MatchExactly))
        if uri.keyColumn() != '_uid_':
            self.uniqueColumnCheck.setCheckState(Qt.Checked)
            if self.allowMultiColumnPk:
                itemsData = uri.keyColumn().split(',')
                for item in self.uniqueModel.findItems("*", Qt.MatchWildcard):
                    if item.data() in itemsData:
                        item.setCheckState(Qt.Checked)
            else:
                keyColumn = uri.keyColumn()
                for item in self.uniqueModel.findItems("*", Qt.MatchWildcard):
                    if item.data() == keyColumn:
                        self.uniqueCombo.setCurrentIndex(self.uniqueModel.indexFromItem(item).row())

        # Finally layer name, filter and selectAtId
        self.layerNameEdit.setText(layer.name())
        self.filter = uri.sql()
        if uri.selectAtIdDisabled():
            self.avoidSelectById.setCheckState(Qt.Checked)