def __init__(self, iface):
    """Constructor for the dialog.

    Args:
      iface: QgsInterface instance.
    """
    QDialog.__init__(self, iface.mainWindow())
    self.setupUi(self)

    # Settings Tab
    # Show the current value of client_id and client_secret
    client_id = settings.read('gmeconnector/CLIENT_ID')
    client_secret = settings.read('gmeconnector/CLIENT_SECRET')
    if client_id is None:
      client_id = ''
    if client_secret is None:
      client_secret = ''
    self.lineEdit1.setText(client_id)
    self.lineEdit2.setText(client_secret)

    # Other settings
    self.comboBoxProjects.setEnabled(False)
    self.checkBoxDefault.stateChanged.connect(self.comboBoxProjects.setEnabled)
    self.comboBoxFormat.addItem('JPEG', 'image/jpeg')
    self.comboBoxFormat.addItem('PNG', 'image/png')
    defaultFormat = settings.read('gmeconnector/WMS_IMAGE_FORMAT')

    if defaultFormat:
      defaultIndex = self.comboBoxFormat.findText(defaultFormat)
      if defaultIndex != -1:
        self.comboBoxFormat.setCurrentIndex(defaultIndex)
    self.comboBoxFormat.currentIndexChanged.connect(self.handleFormatChanged)

    # OAuth help
    oAuthPage = QWebPage()
    oAuthPage.setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
    self.webViewOAuth.setPage(oAuthPage)

    # Load the oauth_help file
    helpFile = QFile(':/plugins/googlemapsengineconnector/oauth_help.html')
    helpFile.open(QIODevice.ReadOnly | QIODevice.Text)
    helpStr = QTextStream(helpFile)
    helpText = helpStr.readAll()
    self.webViewOAuth.setHtml(helpText)
    self.webViewOAuth.linkClicked.connect(self.handleWebLink)

    # About Tab
    aboutPage = QWebPage()
    aboutPage.setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
    self.webViewAbout.setPage(aboutPage)
    # Load the about.html file and add current version info.
    aboutFile = QFile(':/plugins/googlemapsengineconnector/about.html')
    aboutFile.open(QIODevice.ReadOnly | QIODevice.Text)
    aboutStr = QTextStream(aboutFile)
    aboutText = aboutStr.readAll()
    newText = aboutText.format(version='1.0')
    self.webViewAbout.setHtml(newText)
    self.webViewAbout.linkClicked.connect(self.handleWebLink)
Пример #2
0
def style_rc():
    # Smart import of the rc file
    import qdarkstyle.pyqt5_style_rc

    # Load the stylesheet content from resources
    from PyQt5.QtCore import QFile, QTextStream

    f = QFile(":qdarkstyle/style.qss")
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #31363b;
                text-align: center;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet
Пример #3
0
    def __init__(self,parent=None):
        QDialog.__init__(self, parent)
        self.setupUi(self)

        #Connect signals
        self.btnContactUs.clicked.connect(self.onContactUs)
        self.btnSTDMHome.clicked.connect(self.onSTDMHome)

        #Load about HTML file
        aboutLocation = PLUGIN_DIR + "/html/about.htm"
        if QFile.exists(aboutLocation):
            aboutFile = QFile(aboutLocation)
            if not aboutFile.open(QIODevice.ReadOnly):
                QMessageBox.critical(self,
                                     QApplication.translate("AboutSTDMDialog","Open Operation Error"),
                                     QApplication.translate("AboutSTDMDialog","Cannot read 'About STDM' source file."))
                self.reject()

            reader = QTextStream(aboutFile)
            aboutSTDM = reader.readAll()
            self.txtAbout.setHtml(aboutSTDM)

        else:
            QMessageBox.critical(self,
                                 QApplication.translate("AboutSTDMDialog","File Does Not Exist"),
                                 QApplication.translate("AboutSTDMDialog","'About STDM' source file does not exist."))
            self.reject()
Пример #4
0
def main(argv):
    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon(QPixmap(":/logo_small")))
    app.setOrganizationName('Hardcoded Software')
    app.setApplicationName('moneyGuru')
    settings = QSettings()
    LOGGING_LEVEL = logging.DEBUG if adjust_after_deserialization(settings.value('DebugMode')) else logging.WARNING
    setupQtLogging(level=LOGGING_LEVEL)
    logging.debug('started in debug mode')
    if ISLINUX:
        stylesheetFile = QFile(':/stylesheet_lnx')
    else:
        stylesheetFile = QFile(':/stylesheet_win')
    stylesheetFile.open(QFile.ReadOnly)
    textStream = QTextStream(stylesheetFile)
    style = textStream.readAll()
    stylesheetFile.close()
    app.setStyleSheet(style)
    lang = settings.value('Language')
    locale_folder = op.join(BASE_PATH, 'locale')
    hscommon.trans.install_gettext_trans_under_qt(locale_folder, lang)
    # Many strings are translated at import time, so this is why we only import after the translator
    # has been installed
    from qt.app import MoneyGuru
    app.setApplicationVersion(MoneyGuru.VERSION)
    mgapp =  MoneyGuru()
    install_excepthook()
    exec_result = app.exec_()
    del mgapp
    # Since PyQt 4.7.2, I had crashes on exit, and from reading the mailing list, it seems to be
    # caused by some weird crap about C++ instance being deleted with python instance still living.
    # The worst part is that Phil seems to say this is expected behavior. So, whatever, this
    # gc.collect() below is required to avoid a crash.
    gc.collect()
    return exec_result
Пример #5
0
def load_stylesheet_pyqt5():
    """
    Loads the stylesheet for use in a pyqt5 application.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    # Smart import of the rc file
    import qdarkstyle.pyqt5_style_rc

    # Load the stylesheet content from resources
    from PyQt5.QtCore import QFile, QTextStream

    f = QFile(":qdarkstyle/style.qss")
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #353434;
                text-align: center;
            }
            '''
            stylesheet += mac_fix
        return stylesheet
Пример #6
0
 def _replace_results(self):
     result = QMessageBox.question(self, self.tr("Replace Files Contents"),
         self.tr("Are you sure you want to replace the content in "
                 "this files?\n(The change is not reversible)"),
         buttons=QMessageBox.Yes | QMessageBox.No)
     if result == QMessageBox.Yes:
         for index in xrange(self._result_widget.topLevelItemCount()):
             parent = self._result_widget.topLevelItem(index)
             root_dir_name = unicode(parent.dir_name_root)
             file_name = unicode(parent.text(0))
             file_path = file_manager.create_path(root_dir_name, file_name)
             file_object = QFile(file_path)
             if not file_object.open(QFile.ReadOnly):
                 return
             stream = QTextStream(file_object)
             content = stream.readAll()
             file_object.close()
             pattern = self._find_widget.pattern_line_edit.text()
             case_sensitive = self._find_widget.case_checkbox.isChecked()
             type_ = QRegExp.RegExp if \
                 self._find_widget.type_checkbox.isChecked() else \
                 QRegExp.FixedString
             target = QRegExp(pattern, case_sensitive, type_)
             content.replace(target, self._find_widget.replace_line.text())
             file_manager.store_file_content(file_path, content, False)
Пример #7
0
def load_stylesheet_pyqt5():
    """
    Loads the stylesheet for use in a pyqt5 application.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    # Smart import of the rc file
    import vnTrader.qdarkstyle.pyqt5_style_rc

    # Load the stylesheet content from resources
    from PyQt5.QtCore import QFile, QTextStream

    f = QFile(":qdarkstyle/style.qss")
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #31363b;
                text-align: center;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet
Пример #8
0
def load_stylesheet(pyside=True):
    """
    Loads the stylesheet. Takes care of importing the rc module.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    # Smart import of the rc file
    if pyside:
        import qdarkstyle.pyside_style_rc
    else:
        import qdarkstyle.pyqt_style_rc

    # Load the stylesheet content from resources
    if not pyside:
        from PyQt4.QtCore import QFile, QTextStream
    else:
        from PySide.QtCore import QFile, QTextStream

    f = QFile(":qdarkstyle/style.qss")
    if not f.exists():
        print("Unable to set stylesheet, file not found\n")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        return ts.readAll()
Пример #9
0
def load_stylesheet():
    """
    Loads the stylesheet. Takes care of importing the rc module.
    :return the stylesheet string
    """
    import DarkStyle.pyqt_style_rc
    # Load the stylesheet content from resources
    from PyQt4.QtCore import QFile, QTextStream
    f = QFile(":DarkStyle/style.qss")
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #31363b;
                text-align: center;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet
Пример #10
0
 def _replace_results(self):
     result = QMessageBox.question(
         self,
         self.tr("Replace Files Contents"),
         self.tr("Are you sure you want to replace the content in "
                 "this files?\n(The change is not reversible)"),
         buttons=QMessageBox.Yes | QMessageBox.No)
     if result == QMessageBox.Yes:
         for index in range(self._result_widget.topLevelItemCount()):
             parent = self._result_widget.topLevelItem(index)
             root_dir_name = parent.dir_name_root
             file_name = parent.text(0)
             file_path = file_manager.create_path(root_dir_name, file_name)
             file_object = QFile(file_path)
             if not file_object.open(QFile.ReadOnly):
                 return
             stream = QTextStream(file_object)
             content = stream.readAll()
             file_object.close()
             pattern = self._find_widget.pattern_line_edit.text()
             case_sensitive = self._find_widget.case_checkbox.isChecked()
             type_ = QRegExp.RegExp if \
                 self._find_widget.type_checkbox.isChecked() else \
                 QRegExp.FixedString
             target = QRegExp(pattern, case_sensitive, type_)
             content.replace(target, self._find_widget.replace_line.text())
             file_manager.store_file_content(file_path, content, False)
Пример #11
0
def load_stylesheet_pyqt5():
    """
    Loads the stylesheet for use in a pyqt5 application.
    :return the stylesheet string
    """
    # Validate that rc files is updated
    compile_qrc.compile_all()

    # Smart import of the rc file
    import qdarkgraystyle.pyqt5_style_rc

    # Load the stylesheet content from resources
    from PyQt5.QtCore import QFile, QTextStream

    f = QFile(':qdarkgraystyle/style.qss')
    if not f.exists():
        _logger().error('Unable to load stylesheet, file not found in '
                        'resources')
        return ''
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #31363b;
                text-align: center;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet
Пример #12
0
 def readyRead(self):       #  可以读数据了
     local = self.sender()  #  取得是哪个localsocket可以读数据了
     if (local == None):
         return
     _in = QTextStream(local)
     readMsg = _in.readAll()
     print "recv Msg:",readMsg
     self.emit(SIGNAL("newMessage(QString)"), QString(readMsg))
Пример #13
0
 def readyRead(self):  #  可以读数据了
     local = self.sender()  #  取得是哪个localsocket可以读数据了
     if (local == None):
         return
     _in = QTextStream(local)
     readMsg = _in.readAll()
     print "recv Msg:", readMsg
     self.emit(SIGNAL("newMessage(QString)"), QString(readMsg))
Пример #14
0
def table_view_dependencies(table_name, column_name=None):
    """
    Find database views that are dependent on the given table and
    optionally the column.
    :param table_name: Table name
    :type table_name: str
    :param column_name: Name of the column whose dependent views are to be
    extracted.
    :type column_name: str
    :return: A list of views which are dependent on the given table name and
    column respectively.
    :rtype: list(str)
    """
    views = []

    # Load the SQL file depending on whether its table or table/column
    if column_name is None:
        script_path = PLUGIN_DIR + '/scripts/table_related_views.sql'
    else:
        script_path = PLUGIN_DIR + '/scripts/table_column_related_views.sql'

    script_file = QFile(script_path)

    if not script_file.exists():
        raise IOError('SQL file for retrieving view dependencies could '
                      'not be found.')

    else:
        if not script_file.open(QIODevice.ReadOnly):
            raise IOError('Failed to read the SQL file for retrieving view '
                          'dependencies.')

        reader = QTextStream(script_file)
        sql = reader.readAll()
        if sql:
            t = text(sql)
            if column_name is None:
                result = _execute(
                    t,
                    table_name=table_name
                )

            else:
                result = _execute(
                    t,
                    table_name=table_name,
                    column_name=column_name
                )

            # Get view names
            for r in result:
                view_name = r['view_name']
                views.append(view_name)

    return views
Пример #15
0
def load_stylesheet_pyqt5(**kwargs):
    """
    Loads the stylesheet for use in a pyqt5 application.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    # Smart import of the rc file

    if kwargs["style"] == "style_Dark":
        import eslearn.stylesheets.PyQt5_stylesheets.pyqt5_style_Dark_rc
    if kwargs["style"] == "style_DarkOrange":
        import eslearn.stylesheets.PyQt5_stylesheets.pyqt5_style_DarkOrange_rc
    if kwargs["style"] == "style_Classic":
        import eslearn.stylesheets.PyQt5_stylesheets.pyqt5_style_Classic_rc

    if kwargs["style"] == "style_navy":
        import eslearn.stylesheets.PyQt5_stylesheets.pyqt5_style_navy_rc

    if kwargs["style"] == "style_gray":
        import eslearn.stylesheets.PyQt5_stylesheets.pyqt5_style_gray_rc

    if kwargs["style"] == "style_blue":
        import eslearn.stylesheets.PyQt5_stylesheets.pyqt5_style_blue_rc

    if kwargs["style"] == "style_black":
        import eslearn.stylesheets.PyQt5_stylesheets.pyqt5_style_black_rc
    # Load the stylesheet content from resources
    from PyQt5.QtCore import QFile, QTextStream

    f = QFile(":PyQt5_stylesheets/%s.qss" % kwargs["style"])
    if not f.exists():
        f = QFile(":PyQt5_stylesheets/%s.css" % kwargs["style"])
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #31363b;
                text-align: center;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet
Пример #16
0
 def load(self):
     exception = None
     fh = None
     try:
         fh = QFile(self.filename)
         if not fh.open(QIODevice.ReadOnly):
             raise IOError, unicode(fh.errorString())
         stream = QTextStream(fh)
         stream.setCodec("UTF-8")
         self.setPlainText(stream.readAll())
         self.document().setModified(False)
     except (IOError, OSError), e:
         exception = e
Пример #17
0
 def load(self):
     exception = None
     fh = None
     try:
         fh = QFile(self.filename)
         if not fh.open(QIODevice.ReadOnly):
             raise IOError, unicode(fh.errorString())
         stream = QTextStream(fh)
         stream.setCodec("UTF-8")
         self.setPlainText(stream.readAll())
         self.document().setModified(False)
     except (IOError, OSError), e:
         exception = e
Пример #18
0
def main():
    print_process_id()

    app = QtGui.QApplication([])
    #app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt())

    file = QFile(os.path.join(CURR_DIRECTORY, "qdarkstyle.qss"))
    file.open(QFile.ReadOnly | QFile.Text)
    stream = QTextStream(file)
    app.setStyleSheet(stream.readAll())

    widget = ExampleWidget()

    widget.show()

    app.exec_()
Пример #19
0
def get_style(style_sheet):
    try:
        mod = importlib.import_module("." + style_sheet, __name__)
        hasattr(mod, "qt_resource_name")
        f = QFile(":/%s/style.qss" % style_sheet)                                
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()    
    except ImportError as e:
        print "Style sheet not available. Use available_styles() to check for valid styles"
        return u""
    except Exception as e:
        print "Style sheet available, but an error occured..."
        traceback.print_exc()
        return u""
        
    return stylesheet
    def __init__(self, species=None, parent=None):
        super(CharacterSheetDocument, self).__init__(parent)

        self.__species = species

        ## Lade Datei mit Stylesheet-Informationen
        cssFile = QFile(":stylesheets/sheet.css")
        if not cssFile.open(QIODevice.ReadOnly):
            raise ErrFileNotOpened(
                "Wile opening file \"{}\", the error \"{}\" occured.".format(
                    item, cssFile.errorString()),
                filename=item)
        cssStream = QTextStream(cssFile)
        cssContent = cssStream.readAll()
        cssFile.close()

        self.setDefaultStyleSheet(cssContent)
	def __init__(self, species=None, parent=None):
		super(CharacterSheetDocument, self).__init__( parent)

		self.__species = species

		## Lade Datei mit Stylesheet-Informationen
		cssFile = QFile(":stylesheets/sheet.css")
		if not cssFile.open(QIODevice.ReadOnly):
			raise ErrFileNotOpened( "Wile opening file \"{}\", the error \"{}\" occured.".format(
				item,
				cssFile.errorString()
			), filename=item )
		cssStream = QTextStream(cssFile)
		cssContent = cssStream.readAll()
		cssFile.close()

		self.setDefaultStyleSheet(cssContent)
Пример #22
0
def get_style(style_sheet):
    try:
        mod = importlib.import_module("." + style_sheet, __name__)
        hasattr(mod, "qt_resource_name")
        f = QFile(":/%s/style.qss" % style_sheet)
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
    except ImportError as e:
        print "Style sheet not available. Use available_styles() to check for valid styles"
        return u""
    except Exception as e:
        print "Style sheet available, but an error occured..."
        traceback.print_exc()
        return u""

    return stylesheet
Пример #23
0
def load_stylesheet(pyside=True):
    """
    Load the stylesheet. Takes care of importing the rc module.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    warnings.warn(
        "load_stylesheet() will not receive pyside parameter in version 3. "
        "Set QtPy environment variable to specify the Qt binding insteady.",
        FutureWarning
    )
    # Smart import of the rc file
    if pyside:
        import qdarkstyle.pyside_style_rc
    else:
        import qdarkstyle.pyqt_style_rc

    # Load the stylesheet content from resources
    if not pyside:
        from PyQt4.QtCore import QFile, QTextStream
    else:
        from PySide.QtCore import QFile, QTextStream

    f = QFile(":qdarkstyle/style.qss")
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #31363b;
                text-align: center;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet
Пример #24
0
 def load(self):
     exception = None
     fh = None
     try:
         fh = QFile(self.filename)
         if not fh.open(QIODevice.ReadOnly):
             raise IOError(str(fh.errorString()))
         stream = QTextStream(fh)
         stream.setCodec("UTF-8")
         self.setPlainText(stream.readAll())
         self.document().setModified(False)
     except EnvironmentError as e:
         exception = e
     finally:
         if fh is not None:
             fh.close()
         if exception is not None:
             raise exception
Пример #25
0
def load_stylesheet(pyside=True):
    """
    Loads the stylesheet. Takes care of importing the rc module.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc 
    file

    :return the stylesheet string
    """
    # Validate that rc files is updated
    compile_qrc.compile_all()

    # Smart import of the rc file
    if pyside:
        import qdarkgraystyle.pyside_style_rc
    else:
        import qdarkgraystyle.pyqt_style_rc

    # Load the stylesheet content from resources
    if not pyside:
        from PyQt4.QtCore import QFile, QTextStream
    else:
        from PySide.QtCore import QFile, QTextStream

    f = QFile(':qdarkgraystyle/style.qss')
    if not f.exists():
        _logger().error('Unable to load stylesheet, file not found in '
                        'resources')
        return ''
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #31363b;
                text-align: center;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet
Пример #26
0
def load_stylesheet(pyside=True):
    """
    Loads the stylesheet. Takes care of importing the rc module.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    # Smart import of the rc file
    if pyside:
        import vnTrader.qdarkstyle.pyside_style_rc
    else:
        import vnTrader.qdarkstyle.pyqt_style_rc

    # Load the stylesheet content from resources
    if not pyside:
        # PyQt 4/5 compatibility
        try:
            from PyQt4.QtCore import QFile, QTextStream
        except ImportError:
            from PyQt5.QtCore import QFile, QTextStream
    else:
        from PySide.QtCore import QFile, QTextStream

    f = QFile(":qdarkstyle/style.qss")
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #31363b;
                text-align: center;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet
Пример #27
0
def foreign_key_parent_tables(table_name):
    """
    Functions that searches for foreign key references in the specified table.
    :param table_name: Name of the database table.
    :type table_name: str
    :return: A list of tuples containing the local column name, foreign table
    name and corresponding foreign column name.
    :rtype: list
    """
    #Check if the view for listing foreign key references exists
    fk_ref_view = pg_table_exists("foreign_key_references")

    #Create if it does not exist
    if not fk_ref_view:
        script_path = PLUGIN_DIR + "/scripts/foreign_key_references.sql"

        script_file = QFile(script_path)
        if script_file.exists():
            if not script_file.open(QIODevice.ReadOnly):
                return None

            reader = QTextStream(script_file)
            sql = reader.readAll()
            if sql:
                t = text(sql)
                _execute(t)

        else:
            return None

    #Fetch foreign key references
    sql = "SELECT column_name,foreign_table_name,foreign_column_name FROM " \
          "foreign_key_references where table_name=:tb_name"
    t = text(sql)
    result = _execute(t, tb_name=table_name)

    fk_refs = []

    for r in result:
        fk_ref = r["column_name"], r["foreign_table_name"],\
                 r["foreign_column_name"]
        fk_refs.append(fk_ref)

    return fk_refs
Пример #28
0
    def __init__(self, parent=None ):
        super(helpDisplay, self).__init__(parent)
        # make page unmodifiable
        self.page().setContentEditable(False)
        # initialize settings
        # Find out the nearest font to Palatino
        qf = QFont()
        qf.setStyleStrategy(QFont.PreferAntialias+QFont.PreferMatch)
        qf.setStyleHint(QFont.Serif)
        qf.setFamily(QString(u'Palatino'))
        qfi = QFontInfo(qf)
        # set the default font to that serif font
        self.settings().setFontFamily(QWebSettings.StandardFont, qfi.family())
        self.settings().setFontSize(QWebSettings.DefaultFontSize, 16)
        self.settings().setFontSize(QWebSettings.MinimumFontSize, 6)
        self.settings().setFontSize(QWebSettings.MinimumLogicalFontSize, 6)
        self.textZoomFactor = 1.0
        self.setTextSizeMultiplier(self.textZoomFactor)
        self.settings().setAttribute(QWebSettings.JavascriptEnabled, False)
        self.settings().setAttribute(QWebSettings.JavaEnabled, False)
        self.settings().setAttribute(QWebSettings.PluginsEnabled, False)
        self.settings().setAttribute(QWebSettings.ZoomTextOnly, True)
        #self.settings().setAttribute(QWebSettings.SiteSpecificQuirksEnabled, False)
        self.userFindText = QString()
        # Look for pqHelp.html in the app folder and copy its text into
        # a local buffer. If it isn't found, put a message there instead.
        # We need to keep it in order to implement the "back" function.
        helpPath = os.path.join(IMC.appBasePath,u'pqHelp.html')
        helpFile = QFile(helpPath)
        if not helpFile.exists():
            self.HTMLstring = QString('''<p>Unable to locate pqHelp.html.</p>
	    <p>Looking in {0}'''.format(helpPath)
                                )
        elif not helpFile.open(QIODevice.ReadOnly) :
            self.HTMLstring = QString('''<p>Unable to open pqHelp.html.</p>
	    <p>Looking in {0}</p><p>Error code {1}</p>'''.format(helpPath,
                                                                 helpFile.error())
                                                         )
        else:
            helpStream = QTextStream(helpFile)
            helpStream.setCodec('ISO8859-1')
            self.HTMLstring = helpStream.readAll()
        self.setHtml(self.HTMLstring)
Пример #29
0
 def __init__(self, parent=None):
     """ Инициализируем интерфейс и задаём начальные значения внутренних переменных """
     QMainWindow.__init__(self, parent)
     self._alreadyShown = False
     self.setupUi()
     self._feedName = 'feed/http://habrahabr.ru/rss/'
     self._filters = { 'Все' : '.*' }
     self._categorizer = self.categorizeByDate
     file = QFile(':/templates/content.html')
     if file.open(QIODevice.ReadOnly | QIODevice.Text):
         s = QTextStream(file)
         self._entryTemplate = Template(s.readAll())
     else:
         self._entryTemplate = Template('')
     self._curCategory = None
     self._curEntryId = -1
     self._loadingData = False
     self._reader = libgreader.GoogleReader(None)
     self._loggedIn = False
Пример #30
0
def load_stylesheet(pyside=True):
    """
    Loads the stylesheet. Takes care of importing the rc module.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    # Smart import of the rc file
    if pyside:
        #import qdarkstyle.pyside_style_rc
        import petfactoryStyle.pyside_style_rc
    else:
        import petfactoryStyle.pyqt_style_rc

    # Load the stylesheet content from resources
    if not pyside:
        from PyQt4.QtCore import QFile, QTextStream
    else:
        from PySide.QtCore import QFile, QTextStream

    #f = QFile(":qdarkstyle/style.qss")
    f = QFile(":petfactoryStyle/style.qss")
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #353434;
                text-align: center;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet
Пример #31
0
    def load(self):
        """Load ?"""
        exception = None
        filehandle = None
        try:
            filehandle =  QFile(self.filename)
            if not filehandle.open( QIODevice.ReadOnly):
                raise IOError, unicode(filehandle.errorString())
            stream =  QTextStream(filehandle)
            stream.setCodec("UTF-8")
            QApplication.processEvents()
            self.setPlainText(stream.readAll())
            self.document().setModified(False)
            self.setWindowTitle( QFileInfo(self.filename).fileName())
            self.loadHighlighter(self.filename)
            for plugin in filter_plugins_by_capability('afterFileOpen',self.enabled_plugins):
                plugin.do_afterFileOpen(self)

        except (IOError, OSError), error:
            exception = error
Пример #32
0
 def loadEntries(self):
     """" Загрузка записей из БД """
     connection = sqlite3.connect(settings.entriesDb())
     self._feed = libgreader.Feed(self._reader, 'Хабрахабр', 'feed/http://habrahabr.ru/rss/')
     self._reader.feedsById['feed/http://habrahabr.ru/rss/'] = self._feed
     self._categories = {}
     try:
         cursor = connection.cursor()
         file = QFile(':/sql/DbScheme.sql')
         if file.open(QIODevice.ReadOnly | QIODevice.Text):
             s = QTextStream(file)
             cursor.executescript(s.readAll())
         cursor.execute('SELECT Data, IsInteresting FROM Entries WHERE IsRead=?', (False,))
         for (data, interesting) in cursor.fetchall():
             item = libgreader.Item(self._reader, json.loads(data), self._feed)
             item.interesting = interesting
     finally:
         connection.close()
     self.splitItemsIntoCategories()
     self._updateWindowTitle()
Пример #33
0
def load_stylesheet_pyqt5():
    """
    Load the stylesheet for use in a pyqt5 application.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    warnings.warn(
        "load_stylesheet_pyqt5() will be deprecated in version 3,"
        "set QtPy environment variable to specify the Qt binding and "
        "use load_stylesheet()",
        PendingDeprecationWarning
    )
    # Compiles SCSS/SASS files to QSS
    from qdarkstyle.utils.scss import create_qss
    create_qss()

    # Smart import of the rc file
    import qdarkstyle.pyqt5_style_rc

    # Load the stylesheet content from resources
    from PyQt5.QtCore import QCoreApplication, QFile, QTextStream
    from PyQt5.QtGui import QColor, QPalette

    # Apply palette fix. See issue #139
    _apply_palette_fix(QCoreApplication, QPalette, QColor)

    f = QFile(":qdarkstyle/style.qss")
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()

        # Apply OS specific patches
        # stylesheet = _apply_stylesheet_patches(stylesheet)
        return stylesheet
Пример #34
0
    def __init__(self, parent=None, metadata=None):
        QDialog.__init__(self, parent)
        self.setupUi(self)

        self._metadata = metadata

        #Connect signals
        self.btnContactUs.clicked.connect(self.onContactUs)
        self.btnSTDMHome.clicked.connect(self.onSTDMHome)

        #Load about HTML file
        aboutLocation = PLUGIN_DIR + "/html/about.htm"
        if QFile.exists(aboutLocation):
            aboutFile = QFile(aboutLocation)

            if not aboutFile.open(QIODevice.ReadOnly):

                QMessageBox.critical(
                    self,
                    QApplication.translate("AboutSTDMDialog",
                                           "Open Operation Error"),
                    QApplication.translate(
                        "AboutSTDMDialog",
                        "Cannot read 'About STDM' source file."))
                self.reject()

            reader = QTextStream(aboutFile)
            aboutSTDM = reader.readAll()
            self.txtAbout.setHtml(aboutSTDM)
            #Insert plugin info
            self._insert_metadata_info()

        else:
            QMessageBox.critical(
                self,
                QApplication.translate("AboutSTDMDialog",
                                       "File Does Not Exist"),
                QApplication.translate(
                    "AboutSTDMDialog",
                    "'About STDM' source file does not exist."))
            self.reject()
Пример #35
0
    def __init__(self, parent=None):
        super(helpDisplay, self).__init__(parent)
        # make page unmodifiable
        self.page().setContentEditable(False)
        # initialize settings
        # Find out the nearest font to Palatino
        qf = QFont()
        qf.setStyleStrategy(QFont.PreferAntialias + QFont.PreferMatch)
        qf.setStyleHint(QFont.Serif)
        qf.setFamily(QString(u'Palatino'))
        qfi = QFontInfo(qf)
        # set the default font to that serif font
        self.settings().setFontFamily(QWebSettings.StandardFont, qfi.family())
        self.settings().setFontSize(QWebSettings.DefaultFontSize, 16)
        self.settings().setFontSize(QWebSettings.MinimumFontSize, 6)
        self.settings().setFontSize(QWebSettings.MinimumLogicalFontSize, 6)
        self.textZoomFactor = 1.0
        self.setTextSizeMultiplier(self.textZoomFactor)
        self.settings().setAttribute(QWebSettings.JavascriptEnabled, False)
        self.settings().setAttribute(QWebSettings.JavaEnabled, False)
        self.settings().setAttribute(QWebSettings.PluginsEnabled, False)
        self.settings().setAttribute(QWebSettings.ZoomTextOnly, True)
        #self.settings().setAttribute(QWebSettings.SiteSpecificQuirksEnabled, False)
        self.userFindText = QString()
        # Look for pqHelp.html in the app folder and copy its text into
        # a local buffer. If it isn't found, put a message there instead.
        # We need to keep it in order to implement the "back" function.
        helpPath = os.path.join(IMC.appBasePath, u'pqHelp.html')
        helpFile = QFile(helpPath)
        if not helpFile.exists():
            self.HTMLstring = QString('''<p>Unable to locate pqHelp.html.</p>
	    <p>Looking in {0}'''.format(helpPath))
        elif not helpFile.open(QIODevice.ReadOnly):
            self.HTMLstring = QString('''<p>Unable to open pqHelp.html.</p>
	    <p>Looking in {0}</p><p>Error code {1}</p>'''.format(
                helpPath, helpFile.error()))
        else:
            helpStream = QTextStream(helpFile)
            helpStream.setCodec('ISO8859-1')
            self.HTMLstring = helpStream.readAll()
        self.setHtml(self.HTMLstring)
Пример #36
0
    def load(self):
        """Load ?"""
        exception = None
        filehandle = None
        try:
            filehandle = QFile(self.filename)
            if not filehandle.open(QIODevice.ReadOnly):
                raise IOError, unicode(filehandle.errorString())
            stream = QTextStream(filehandle)
            stream.setCodec("UTF-8")
            QApplication.processEvents()
            self.setPlainText(stream.readAll())
            self.document().setModified(False)
            self.setWindowTitle(QFileInfo(self.filename).fileName())
            self.loadHighlighter(self.filename)
            for plugin in filter_plugins_by_capability('afterFileOpen',
                                                       self.enabled_plugins):
                plugin.do_afterFileOpen(self)

        except (IOError, OSError), error:
            exception = error
Пример #37
0
    def replaceFirstMenuName(self):
#         pass
        grub_file = QFile("/boot/grub/grub.conf")
        if not grub_file.open(QIODevice.ReadOnly):
            grub_file.close()
            return
     
        fs = QTextStream(grub_file)
        fileContent = fs.readAll()
        grub_file.close()
        if QString(fileContent).contains("MCOS cDesktop Client Start"):
            return
     
        cmd =  "sed -i \"s/CentOS (2.6.32-431.el6.i686)/MCOS cDesktop Client Start/g\" /boot/grub/grub.conf";
     
        ok = os.system(cmd)
        if ok != 0:
            LogRecord.instance().logger(u"替换grub.cfg中的'CentOS (2.6.32-431.el6.i686)'失败")
     
        if QString(fileContent).contains("hiddenmenu"):
            os.system("sed -i \"/hiddenmenu/d\" /boot/grub/grub.conf")
Пример #38
0
def load_stylesheet_pyqt5():
    """
    Load the stylesheet for use in a pyqt5 application.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    warnings.warn(
        "load_stylesheet_pyqt5() will be deprecated in version 3,"
        "set QtPy environment variable to specify the Qt binding and "
        "use load_stylesheet()",
        PendingDeprecationWarning
    )
    # Smart import of the rc file
    import qdarkstyle.pyqt5_style_rc

    # Load the stylesheet content from resources
    from PyQt5.QtCore import QFile, QTextStream

    f = QFile(":qdarkstyle/style.qss")
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #32414B;
                text-align: center;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet
Пример #39
0
def load_stylesheet_pyqt5():
    """
    Load the stylesheet for use in a pyqt5 application.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    warnings.warn(
        "load_stylesheet_pyqt5() will be deprecated in version 3,"
        "set QtPy environment variable to specify the Qt binding and "
        "use load_stylesheet()", PendingDeprecationWarning)
    # Compiles SCSS/SASS files to QSS
    from qdarkstyle.utils.scss import create_qss
    create_qss()

    # Smart import of the rc file
    import qdarkstyle.pyqt5_style_rc

    # Load the stylesheet content from resources
    from PyQt5.QtCore import QCoreApplication, QFile, QTextStream
    from PyQt5.QtGui import QColor, QPalette

    # Apply palette fix. See issue #139
    _apply_palette_fix(QCoreApplication, QPalette, QColor)

    f = QFile(":qdarkstyle/style.qss")
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()

        # Apply OS specific patches
        # stylesheet = _apply_stylesheet_patches(stylesheet)
        return stylesheet
Пример #40
0
 def load_file(self):
     """
     Loading a text file to the self.textEdit
     """
     self.ready_to_go()
     fileobject = None
     self.path = QFileDialog.getOpenFileName(self, "TextEditor", "")
     try:
         fileobject = QFile(self.path)
         if not fileobject.open(QIODevice.ReadOnly):
             raise IOError, unicode(fileobject.errorString())
         textstream = QTextStream(fileobject)
         textstream.setCodec("UTF-8")
         self.textEdit.setPlainText(textstream.readAll())
         self.textEdit.document().setModified(False)
         print self.textEdit.document().isModified()
         self.setWindowTitle("%s - TextEditor" %
                             QFileInfo(self.path).fileName())
     except (IOError, OSError), error:
         QMessageBox.warning(
             self, self.tr("TextEditor - Load Error"),
             self.tr("Unable to load {0} : {1}".format(self.path, error)))
         self.path = ""
Пример #41
0
def load_stylesheet(file_qss):
    """
    """
    from PyQt4.QtCore import QFile, QTextStream
    f = QFile("{}.css".format(os.path.join(ROOT_DIR, file_qss)))
    if not f.exists():
        print("Unable to load stylesheet, file not found in "
              "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #353434;
                text-align: center;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet
Пример #42
0
 def load_file(self):
     """
     Loading a text file to the self.textEdit
     """
     self.ready_to_go()
     fileobject = None
     self.path = QFileDialog.getOpenFileName(self, "TextEditor","")
     try:
         fileobject = QFile(self.path)
         if not fileobject.open(QIODevice.ReadOnly):
             raise IOError, unicode(fileobject.errorString())
         textstream = QTextStream(fileobject)
         textstream.setCodec("UTF-8")
         self.textEdit.setPlainText(textstream.readAll())
         self.textEdit.document().setModified(False)
         print self.textEdit.document().isModified()
         self.setWindowTitle("%s - TextEditor" % 
                             QFileInfo(self.path).fileName())
     except(IOError, OSError), error:
         QMessageBox.warning(self, 
                             self.tr("TextEditor - Load Error"),
                             self.tr("Unable to load {0} : {1}".format(self.path,
                                                                     error)))
         self.path = ""
Пример #43
0
class LogsReadThread(QThread):
    MAX_INITIAL_SIZE = 2*1024*1024 # 2Mb

    def __init__(self, parent):
        QThread.__init__(self, parent)

        self.fCloseNow   = False
        self.fPurgeLogs  = False
        self.fRealParent = parent

        # -------------------------------------------------------------
        # Take some values from Logs Window

        self.LOG_FILE_JACK   = LogsW.LOG_FILE_JACK
        self.LOG_FILE_A2J    = LogsW.LOG_FILE_A2J
        self.LOG_FILE_LASH   = LogsW.LOG_FILE_LASH
        self.LOG_FILE_LADISH = LogsW.LOG_FILE_LADISH

        # -------------------------------------------------------------
        # Init logs

        if self.LOG_FILE_JACK is not None:
            self.fLogFileJACK = QFile(self.LOG_FILE_JACK)
            self.fLogFileJACK.open(QIODevice.ReadOnly)
            self.fLogStreamJACK = QTextStream(self.fLogFileJACK)
            self.fLogStreamJACK.setCodec("UTF-8")

            if self.fLogFileJACK.size() > self.MAX_INITIAL_SIZE:
                self.fLogStreamJACK.seek(self.fLogFileJACK.size() - self.MAX_INITIAL_SIZE)

        if self.LOG_FILE_A2J is not None:
            self.fLogFileA2J = QFile(self.LOG_FILE_A2J)
            self.fLogFileA2J.open(QIODevice.ReadOnly)
            self.fLogStreamA2J = QTextStream(self.fLogFileA2J)
            self.fLogStreamA2J.setCodec("UTF-8")

            if self.fLogFileA2J.size() > self.MAX_INITIAL_SIZE:
                self.fLogStreamA2J.seek(self.fLogFileA2J.size() - self.MAX_INITIAL_SIZE)

        if self.LOG_FILE_LASH is not None:
            self.fLogFileLASH = QFile(self.LOG_FILE_LASH)
            self.fLogFileLASH.open(QIODevice.ReadOnly)
            self.fLogStreamLASH = QTextStream(self.fLogFileLASH)
            self.fLogStreamLASH.setCodec("UTF-8")

            if self.fLogFileLASH.size() > self.MAX_INITIAL_SIZE:
                self.fLogStreamLASH.seek(self.fLogFileLASH.size() - self.MAX_INITIAL_SIZE)

        if self.LOG_FILE_LADISH is not None:
            self.fLogFileLADISH = QFile(self.LOG_FILE_LADISH)
            self.fLogFileLADISH.open(QIODevice.ReadOnly)
            self.fLogStreamLADISH = QTextStream(self.fLogFileLADISH)
            self.fLogStreamLADISH.setCodec("UTF-8")

            if self.fLogFileLADISH.size() > self.MAX_INITIAL_SIZE:
                self.fLogStreamLADISH.seek(self.fLogFileLADISH.size() - self.MAX_INITIAL_SIZE)

    def closeNow(self):
        self.fCloseNow = True

    def purgeLogs(self):
        self.fPurgeLogs = True

    def run(self):
        # -------------------------------------------------------------
        # Read logs and set text in main thread

        while not self.fCloseNow:
            if self.fPurgeLogs:
                if self.LOG_FILE_JACK:
                    self.fLogStreamJACK.flush()
                    self.fLogFileJACK.close()
                    self.fLogFileJACK.open(QIODevice.WriteOnly)
                    self.fLogFileJACK.close()
                    self.fLogFileJACK.open(QIODevice.ReadOnly)

                if self.LOG_FILE_A2J:
                    self.fLogStreamA2J.flush()
                    self.fLogFileA2J.close()
                    self.fLogFileA2J.open(QIODevice.WriteOnly)
                    self.fLogFileA2J.close()
                    self.fLogFileA2J.open(QIODevice.ReadOnly)

                if self.LOG_FILE_LASH:
                    self.fLogStreamLASH.flush()
                    self.fLogFileLASH.close()
                    self.fLogFileLASH.open(QIODevice.WriteOnly)
                    self.fLogFileLASH.close()
                    self.fLogFileLASH.open(QIODevice.ReadOnly)

                if self.LOG_FILE_LADISH:
                    self.fLogStreamLADISH.flush()
                    self.fLogFileLADISH.close()
                    self.fLogFileLADISH.open(QIODevice.WriteOnly)
                    self.fLogFileLADISH.close()
                    self.fLogFileLADISH.open(QIODevice.ReadOnly)

                self.fPurgeLogs = False

            else:
                if self.LOG_FILE_JACK:
                    textJACK = fixLogText(self.fLogStreamJACK.readAll()).strip()
                else:
                    textJACK = ""

                if self.LOG_FILE_A2J:
                    textA2J = fixLogText(self.fLogStreamA2J.readAll()).strip()
                else:
                    textA2J = ""

                if self.LOG_FILE_LASH:
                    textLASH = fixLogText(self.fLogStreamLASH.readAll()).strip()
                else:
                    textLASH = ""

                if self.LOG_FILE_LADISH:
                    textLADISH = fixLogText(self.fLogStreamLADISH.readAll()).strip()
                else:
                    textLADISH = ""

                self.fRealParent.setLogsText(textJACK, textA2J, textLASH, textLADISH)
                self.emit(SIGNAL("updateLogs()"))

            if not self.fCloseNow:
                self.sleep(1)

        # -------------------------------------------------------------
        # Close logs before closing thread

        if self.LOG_FILE_JACK:
            self.fLogFileJACK.close()

        if self.LOG_FILE_A2J:
            self.fLogFileA2J.close()

        if self.LOG_FILE_LASH:
            self.fLogFileLASH.close()

        if self.LOG_FILE_LADISH:
            self.fLogFileLADISH.close()
Пример #44
0
#!/usr/bin/env python
# -*- coding: utf-8
from PyQt4.QtGui import QApplication
from login import Login
from Main import MainWindow
from PyQt4.QtGui import QDialog
if __name__ == '__main__':
    import sys
    from PyQt4.QtCore import QFile, QIODevice, QTextStream, QTextCodec
    import myfile
    cssfile = QFile(':/main.css')
    if not cssfile.open(QIODevice.ReadOnly):
        sys.exit(u'未读取到资源文件')
    stream = QTextStream(cssfile)
    stream.setCodec(QTextCodec.codecForName('UTF-8'))
    cssdata = stream.readAll()
    cssfile.close()
    del stream
    app = QApplication(sys.argv)
    app.setStyle('Fusion')
    # with open('main.css', 'r') as css:
    #     StyleSheet = css.read()
    app.setStyleSheet(cssdata)
    if Login().exec_() == QDialog.Accepted:
        window = MainWindow()
        window.show()
        sys.exit(app.exec_())
Пример #45
0
def foreign_key_parent_tables(table_name, search_parent=True, filter_exp=None):
    """
    Functions that searches for foreign key references in the specified table.
    :param table_name: Name of the database table.
    :type table_name: str
    :param search_parent: Select True if table_name is the child and
    parent tables are to be retrieved, else child tables will be
    returned.
    :type search_parent: bool
    :param filter_exp: A regex expression to filter related table names.
    :type filter_exp: QRegExp
    :return: A list of tuples containing the local column name, foreign table
    name and corresponding foreign column name.
    :rtype: list
    """
    #Check if the view for listing foreign key references exists
    fk_ref_view = pg_table_exists("foreign_key_references")

    #Create if it does not exist
    if not fk_ref_view:
        script_path = PLUGIN_DIR + "/scripts/foreign_key_references.sql"

        script_file = QFile(script_path)
        if script_file.exists():
            if not script_file.open(QIODevice.ReadOnly):
                return None

            reader = QTextStream(script_file)
            sql = reader.readAll()
            if sql:
                t = text(sql)
                _execute(t)

        else:
            return None

    if search_parent:
        ref_table = "foreign_table_name"
        search_table = "table_name"
    else:
        ref_table = "table_name"
        search_table = "foreign_table_name"

    #Fetch foreign key references
    sql = u"SELECT column_name,{0},foreign_column_name FROM " \
          u"foreign_key_references where {1} =:tb_name".format(ref_table,
                                                               search_table)
    t = text(sql)
    result = _execute(t, tb_name=table_name)

    fk_refs = []

    for r in result:
        rel_table = r[ref_table]

        fk_ref = r["column_name"], rel_table,\
                 r["foreign_column_name"]

        if not filter_exp is None:
            if filter_exp.indexIn(rel_table) >= 0:
                fk_refs.append(fk_ref)

                continue

        fk_refs.append(fk_ref)

    return fk_refs
Пример #46
0
def foreign_key_parent_tables(table_name, search_parent=True, filter_exp=None):
    """
    Functions that searches for foreign key references in the specified table.
    :param table_name: Name of the database table.
    :type table_name: str
    :param search_parent: Select True if table_name is the child and
    parent tables are to be retrieved, else child tables will be
    returned.
    :type search_parent: bool
    :param filter_exp: A regex expression to filter related table names.
    :type filter_exp: QRegExp
    :return: A list of tuples containing the local column name, foreign table
    name and corresponding foreign column name.
    :rtype: list
    """
    #Check if the view for listing foreign key references exists
    fk_ref_view = pg_table_exists("foreign_key_references")

    #Create if it does not exist
    if not fk_ref_view:
        script_path = PLUGIN_DIR + "/scripts/foreign_key_references.sql"

        script_file = QFile(script_path)
        if script_file.exists():
            if not script_file.open(QIODevice.ReadOnly):
                return None

            reader = QTextStream(script_file)
            sql = reader.readAll()
            if sql:
                t = text(sql)
                _execute(t)

        else:
            return None

    if search_parent:
        ref_table = "foreign_table_name"
        search_table = "table_name"
    else:
        ref_table = "table_name"
        search_table = "foreign_table_name"

    #Fetch foreign key references
    sql = u"SELECT column_name,{0},foreign_column_name FROM " \
          u"foreign_key_references where {1} =:tb_name".format(ref_table,
                                                               search_table)
    t = text(sql)
    result = _execute(t, tb_name=table_name)

    fk_refs = []

    for r in result:
        rel_table = r[ref_table]

        fk_ref = r["column_name"], rel_table,\
                 r["foreign_column_name"]

        if not filter_exp is None:
            if filter_exp.indexIn(rel_table) >= 0:
                fk_refs.append(fk_ref)

                continue

        fk_refs.append(fk_ref)

    return fk_refs
Пример #47
0
    from PyQt4.QtGui import (QApplication,QPlainTextEdit,QFileDialog,QMainWindow)
    import pqIMC
    app = QApplication(sys.argv) # create an app
    IMC = pqIMC.tricorder() # create inter-module communicator
    pqMsgs.IMC = IMC
    IMC.bookType = QString(u"html")
    M = QMainWindow()
    pqMsgs.makeBarIn(M.statusBar())
    utname = QFileDialog.getOpenFileName(M,
                                         "UNIT TEST DATA FOR FLOW", ".")
    utfile = QFile(utname)
    if not utfile.open(QIODevice.ReadOnly):
        raise IOError, unicode(utfile.errorString())
    utinfo = QFileInfo(utfile)
    IMC.bookDirPath = utinfo.absolutePath()
    utstream = QTextStream(utfile)
    utstream.setCodec("UTF-8")
    utqs = utstream.readAll()
    IMC.editWidget = QPlainTextEdit()
    IMC.editWidget.setPlainText(utqs)
    IMC.editWidget.show()
    W = htmlPreview()
    M.setCentralWidget(W)
    M.show()
    W.docWillChange()
    W.docHasChanged()
    #t = unicode(W.getSimpleText())
    #print(t)
    #W.doneWithText()
    app.exec_()
Пример #48
0
    from PyQt4.QtGui import (QApplication, QFileDialog, QMainWindow)
    import pqIMC
    IMC = pqIMC.tricorder()  # create inter-module communicator
    app = QApplication(sys.argv)  # create an app
    import pqMsgs
    pqMsgs.IMC = IMC
    import pqLists
    IMC.charCensus = pqLists.vocabList()
    CP = charsPanel()  # create the widget with the table view and model
    MW = QMainWindow()
    MW.setCentralWidget(CP)
    IMC.statusBar = MW.statusBar()
    MW.show()
    utname = QFileDialog.getOpenFileName(MW, "UNIT TEST DATA FOR CHARS", ".")
    utfile = QFile(utname)
    if not utfile.open(QIODevice.ReadOnly):
        raise IOError, unicode(utfile.errorString())

    CP.docWillChange()

    utstream = QTextStream(utfile)
    utstream.setCodec("UTF-8")
    utqs = utstream.readAll()
    for i in range(utqs.count()):
        qc = utqs.at(i)
        cat = qc.category()
        IMC.charCensus.count(QString(qc), cat)

    CP.docHasChanged()
    app.exec_()
Пример #49
0
 IMC.editWidget = QPlainTextEdit()
 IMC.pageTable = pagedb()
 widj = pagesPanel()
 MW = QMainWindow()
 IMC.mainWindow = MW
 MW.setCentralWidget(widj)
 MW.setWinModStatus = setWinModStatus
 MW.show()
 fn = QFileDialog.getOpenFileName(None,"Select a Test Book")
 print(fn)
 fh = QFile(fn)
 if not fh.open(QFile.ReadOnly):
     raise IOError, unicode(fh.errorString())
 stream = QTextStream(fh)
 stream.setCodec("UTF-8")
 IMC.editWidget.setPlainText(stream.readAll()) # load the editor doc
 widj.docWillChange()
 # Code from pqEdit to parse a doc by lines and extract page seps.
 reLineSep = QRegExp(u'-----File: ([^\\.]+)\\.png---((\\\\[^\\\\]*)+)\\\\-*',Qt.CaseSensitive)
 qtb = IMC.editWidget.document().begin() # first text block
 IMC.pageTable.clear()
 while qtb != IMC.editWidget.document().end(): # up to end of document
     qsLine = qtb.text() # text of line as qstring
     if reLineSep.exactMatch(qsLine): # a page separator
         qsfilenum = reLineSep.capturedTexts()[1]
         qsproofers = reLineSep.capturedTexts()[2]
         # proofer names can contain spaces, replace with en-space char
         qsproofers.replace(QChar(" "),QChar(0x2002))
         tcursor = QTextCursor(IMC.editWidget.document())
         tcursor.setPosition(qtb.position())
         IMC.pageTable.loadPsep(tcursor, qsfilenum, qsproofers)
Пример #50
0
def load_stylesheet(pyside=True):
    """
    Load the stylesheet. Takes care of importing the rc module.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    warnings.warn(
        "load_stylesheet() will not receive pyside parameter in version 3. "
        "Set QtPy environment variable to specify the Qt binding insteady.",
        PendingDeprecationWarning)

    # Smart import of the rc file
    pyside_ver = None

    if pyside:

        # Detect the PySide version available
        try:
            import PySide
        except ImportError:  # Compatible with py27
            import PySide2
            pyside_ver = 2
        else:
            pyside_ver = 1

        if pyside_ver == 1:
            import qdarkstyle.pyside_style_rc
        else:
            import qdarkstyle.pyside2_style_rc
    else:
        import qdarkstyle.pyqt_style_rc

    # Load the stylesheet content from resources
    if not pyside:
        from PyQt4.QtCore import QCoreApplication, QFile, QTextStream
        from PyQt4.QtGui import QColor, QPalette
    else:
        if pyside_ver == 1:
            from PySide.QtCore import QCoreApplication, QFile, QTextStream
            from PySide.QtGui import QColor, QPalette
        else:
            from PySide2.QtCore import QCoreApplication, QFile, QTextStream
            from PySide2.QtGui import QColor, QPalette

    # Apply palette fix. See issue #139
    _apply_palette_fix(QCoreApplication, QPalette, QColor)

    f = QFile(":qdarkstyle/style.qss")
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()

        # Apply OS specific patches
        stylesheet = _apply_stylesheet_patches(stylesheet)

        return stylesheet
Пример #51
0
def load_stylesheet(pyside=True):
    """
    Load the stylesheet. Takes care of importing the rc module.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    warnings.warn(
        "load_stylesheet() will not receive pyside parameter in version 3. "
        "Set QtPy environment variable to specify the Qt binding insteady.",
        PendingDeprecationWarning
    )

    # Compiles SCSS/SASS files to QSS
    from qdarkstyle.utils.scss import create_qss
    create_qss()

    # Smart import of the rc file

    pyside_ver = None

    if pyside:

        # Detect the PySide version available
        try:
            import PySide
        except ImportError:  # Compatible with py27
            import PySide2
            pyside_ver = 2
        else:
            pyside_ver = 1

        if pyside_ver == 1:
            import qdarkstyle.pyside_style_rc
        else:
            import qdarkstyle.pyside2_style_rc
    else:
        import qdarkstyle.pyqt_style_rc

    # Load the stylesheet content from resources
    if not pyside:
        from PyQt4.QtCore import QCoreApplication, QFile, QTextStream
        from PyQt4.QtGui import QColor, QPalette
    else:
        if pyside_ver == 1:
            from PySide.QtCore import QCoreApplication, QFile, QTextStream
            from PySide.QtGui import QColor, QPalette
        else:
            from PySide2.QtCore import QCoreApplication, QFile, QTextStream
            from PySide2.QtGui import QColor, QPalette

    # Apply palette fix. See issue #139
    _apply_palette_fix(QCoreApplication, QPalette, QColor)

    f = QFile(":qdarkstyle/style.qss")
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()

        # Apply OS specific patches
        stylesheet = _apply_stylesheet_patches(stylesheet)

        return stylesheet
Пример #52
0
 IMC.editWidget = QPlainTextEdit()
 IMC.pageTable = pagedb()
 widj = pagesPanel()
 MW = QMainWindow()
 IMC.mainWindow = MW
 MW.setCentralWidget(widj)
 MW.setWinModStatus = setWinModStatus
 MW.show()
 fn = QFileDialog.getOpenFileName(None, "Select a Test Book")
 print(fn)
 fh = QFile(fn)
 if not fh.open(QFile.ReadOnly):
     raise IOError, unicode(fh.errorString())
 stream = QTextStream(fh)
 stream.setCodec("UTF-8")
 IMC.editWidget.setPlainText(stream.readAll())  # load the editor doc
 widj.docWillChange()
 # Code from pqEdit to parse a doc by lines and extract page seps.
 reLineSep = QRegExp(
     u'-----File: ([^\\.]+)\\.png---((\\\\[^\\\\]*)+)\\\\-*',
     Qt.CaseSensitive)
 qtb = IMC.editWidget.document().begin()  # first text block
 IMC.pageTable.clear()
 while qtb != IMC.editWidget.document().end():  # up to end of document
     qsLine = qtb.text()  # text of line as qstring
     if reLineSep.exactMatch(qsLine):  # a page separator
         qsfilenum = reLineSep.capturedTexts()[1]
         qsproofers = reLineSep.capturedTexts()[2]
         # proofer names can contain spaces, replace with en-space char
         qsproofers.replace(QChar(" "), QChar(0x2002))
         tcursor = QTextCursor(IMC.editWidget.document())