def add_definition(self, text, number):
     dictionary = text.split("\n")[0]
     definitions = text.split("\n")[1:]
     page = KTextEdit("<br>".join(definitions), self)
     page.setReadOnly(True)
     page.setAutoFormatting(QTextEdit.AutoBulletList)
     page.setFontWeight(QFont.Normal)
     if self.parent.force_bw_definition:
         page.setStyleSheet(QString("background-color: white; color:black;"))
     self.definition_tabs.addTab(page, "%s: %s" %(number, dictionary))
Ejemplo n.º 2
0
class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(400, 300)
        self.verticalLayout = QtGui.QVBoxLayout(Form)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.textWidget = KTextEdit(Form)
        self.textWidget.setEnabled(True)
        self.textWidget.setReadOnly(True)
        self.textWidget.setAcceptRichText(False)
        self.textWidget.setObjectName(_fromUtf8("textWidget"))
        self.verticalLayout.addWidget(self.textWidget)
        self.downloadButton = KPushButton(Form)
        self.downloadButton.setObjectName(_fromUtf8("downloadButton"))
        self.verticalLayout.addWidget(self.downloadButton)
        self.clearButton = KPushButton(Form)
        self.clearButton.setObjectName(_fromUtf8("clearButton"))
        self.verticalLayout.addWidget(self.clearButton)

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        Form.setWindowTitle(kdecore.i18n(_fromUtf8("Form")))
        self.downloadButton.setText(kdecore.i18n(_fromUtf8("Start example")))
        self.clearButton.setText(kdecore.i18n(_fromUtf8("Clear")))
Ejemplo n.º 3
0
    def __init__(self):
        KXmlGuiWindow.__init__(self)

        self.textArea = KTextEdit()
        self.setCentralWidget(self.textArea)

        self.setupActions()
Ejemplo n.º 4
0
    def setupUi(self, PhrasePage):
        PhrasePage.setObjectName(_fromUtf8("PhrasePage"))
        PhrasePage.resize(540, 421)
        self.verticalLayout_2 = QtGui.QVBoxLayout(PhrasePage)
        self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
        self.urlLabel = KUrlLabel(PhrasePage)
        self.urlLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.urlLabel.setObjectName(_fromUtf8("urlLabel"))
        self.verticalLayout_2.addWidget(self.urlLabel)
        self.phraseText = KTextEdit(PhrasePage)
        self.phraseText.setTabChangesFocus(True)
        self.phraseText.setLineWrapMode(QtGui.QTextEdit.NoWrap)
        self.phraseText.setAcceptRichText(False)
        self.phraseText.setObjectName(_fromUtf8("phraseText"))
        self.verticalLayout_2.addWidget(self.phraseText)
        self.settingsGroupBox = QtGui.QGroupBox(PhrasePage)
        self.settingsGroupBox.setObjectName(_fromUtf8("settingsGroupBox"))
        self.verticalLayout = QtGui.QVBoxLayout(self.settingsGroupBox)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.promptCheckbox = QtGui.QCheckBox(self.settingsGroupBox)
        self.promptCheckbox.setObjectName(_fromUtf8("promptCheckbox"))
        self.verticalLayout.addWidget(self.promptCheckbox)
        self.showInTrayCheckbox = QtGui.QCheckBox(self.settingsGroupBox)
        self.showInTrayCheckbox.setObjectName(_fromUtf8("showInTrayCheckbox"))
        self.verticalLayout.addWidget(self.showInTrayCheckbox)
        self.horizontalLayout_2 = QtGui.QHBoxLayout()
        self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
        self.label = QtGui.QLabel(self.settingsGroupBox)
        self.label.setObjectName(_fromUtf8("label"))
        self.horizontalLayout_2.addWidget(self.label)
        self.sendModeCombo = QtGui.QComboBox(self.settingsGroupBox)
        self.sendModeCombo.setObjectName(_fromUtf8("sendModeCombo"))
        self.horizontalLayout_2.addWidget(self.sendModeCombo)
        spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding,
                                       QtGui.QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.kseparator = KSeparator(self.settingsGroupBox)
        self.kseparator.setObjectName(_fromUtf8("kseparator"))
        self.verticalLayout.addWidget(self.kseparator)
        self.settingsWidget = SettingsWidget(self.settingsGroupBox)
        self.settingsWidget.setObjectName(_fromUtf8("settingsWidget"))
        self.verticalLayout.addWidget(self.settingsWidget)
        self.verticalLayout_2.addWidget(self.settingsGroupBox)

        self.retranslateUi(PhrasePage)
        QtCore.QMetaObject.connectSlotsByName(PhrasePage)
Ejemplo n.º 5
0
class Ui_PhrasePage(object):
    def setupUi(self, PhrasePage):
        PhrasePage.setObjectName(_fromUtf8("PhrasePage"))
        PhrasePage.resize(540, 421)
        self.verticalLayout_2 = QtGui.QVBoxLayout(PhrasePage)
        self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
        self.urlLabel = KUrlLabel(PhrasePage)
        self.urlLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.urlLabel.setObjectName(_fromUtf8("urlLabel"))
        self.verticalLayout_2.addWidget(self.urlLabel)
        self.phraseText = KTextEdit(PhrasePage)
        self.phraseText.setTabChangesFocus(True)
        self.phraseText.setLineWrapMode(QtGui.QTextEdit.NoWrap)
        self.phraseText.setAcceptRichText(False)
        self.phraseText.setObjectName(_fromUtf8("phraseText"))
        self.verticalLayout_2.addWidget(self.phraseText)
        self.settingsGroupBox = QtGui.QGroupBox(PhrasePage)
        self.settingsGroupBox.setObjectName(_fromUtf8("settingsGroupBox"))
        self.verticalLayout = QtGui.QVBoxLayout(self.settingsGroupBox)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.promptCheckbox = QtGui.QCheckBox(self.settingsGroupBox)
        self.promptCheckbox.setObjectName(_fromUtf8("promptCheckbox"))
        self.verticalLayout.addWidget(self.promptCheckbox)
        self.showInTrayCheckbox = QtGui.QCheckBox(self.settingsGroupBox)
        self.showInTrayCheckbox.setObjectName(_fromUtf8("showInTrayCheckbox"))
        self.verticalLayout.addWidget(self.showInTrayCheckbox)
        self.horizontalLayout_2 = QtGui.QHBoxLayout()
        self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
        self.label = QtGui.QLabel(self.settingsGroupBox)
        self.label.setObjectName(_fromUtf8("label"))
        self.horizontalLayout_2.addWidget(self.label)
        self.sendModeCombo = QtGui.QComboBox(self.settingsGroupBox)
        self.sendModeCombo.setObjectName(_fromUtf8("sendModeCombo"))
        self.horizontalLayout_2.addWidget(self.sendModeCombo)
        spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.kseparator = KSeparator(self.settingsGroupBox)
        self.kseparator.setObjectName(_fromUtf8("kseparator"))
        self.verticalLayout.addWidget(self.kseparator)
        self.settingsWidget = SettingsWidget(self.settingsGroupBox)
        self.settingsWidget.setObjectName(_fromUtf8("settingsWidget"))
        self.verticalLayout.addWidget(self.settingsWidget)
        self.verticalLayout_2.addWidget(self.settingsGroupBox)

        self.retranslateUi(PhrasePage)
        QtCore.QMetaObject.connectSlotsByName(PhrasePage)

    def retranslateUi(self, PhrasePage):
        PhrasePage.setWindowTitle(kdecore.i18n(_fromUtf8("Form")))
        self.urlLabel.setTipText(kdecore.i18n(_fromUtf8("Open the phrase in the default text editor")))
        self.settingsGroupBox.setTitle(kdecore.i18n(_fromUtf8("Phrase Settings")))
        self.promptCheckbox.setText(kdecore.i18n(_fromUtf8("Always prompt before pasting this phrase")))
        self.showInTrayCheckbox.setText(kdecore.i18n(_fromUtf8("Show in notification icon menu")))
        self.label.setText(kdecore.i18n(_fromUtf8("Paste using")))
Ejemplo n.º 6
0
class Ui_PhrasePage(object):
    def setupUi(self, PhrasePage):
        PhrasePage.setObjectName(_fromUtf8("PhrasePage"))
        PhrasePage.resize(540, 421)
        self.verticalLayout_2 = QtGui.QVBoxLayout(PhrasePage)
        self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
        self.urlLabel = KUrlLabel(PhrasePage)
        self.urlLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.urlLabel.setObjectName(_fromUtf8("urlLabel"))
        self.verticalLayout_2.addWidget(self.urlLabel)
        self.phraseText = KTextEdit(PhrasePage)
        self.phraseText.setTabChangesFocus(True)
        self.phraseText.setLineWrapMode(QtGui.QTextEdit.NoWrap)
        self.phraseText.setAcceptRichText(False)
        self.phraseText.setObjectName(_fromUtf8("phraseText"))
        self.verticalLayout_2.addWidget(self.phraseText)
        self.settingsGroupBox = QtGui.QGroupBox(PhrasePage)
        self.settingsGroupBox.setObjectName(_fromUtf8("settingsGroupBox"))
        self.verticalLayout = QtGui.QVBoxLayout(self.settingsGroupBox)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.promptCheckbox = QtGui.QCheckBox(self.settingsGroupBox)
        self.promptCheckbox.setObjectName(_fromUtf8("promptCheckbox"))
        self.verticalLayout.addWidget(self.promptCheckbox)
        self.showInTrayCheckbox = QtGui.QCheckBox(self.settingsGroupBox)
        self.showInTrayCheckbox.setObjectName(_fromUtf8("showInTrayCheckbox"))
        self.verticalLayout.addWidget(self.showInTrayCheckbox)
        self.horizontalLayout_2 = QtGui.QHBoxLayout()
        self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
        self.label = QtGui.QLabel(self.settingsGroupBox)
        self.label.setObjectName(_fromUtf8("label"))
        self.horizontalLayout_2.addWidget(self.label)
        self.sendModeCombo = QtGui.QComboBox(self.settingsGroupBox)
        self.sendModeCombo.setObjectName(_fromUtf8("sendModeCombo"))
        self.horizontalLayout_2.addWidget(self.sendModeCombo)
        spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.kseparator = KSeparator(self.settingsGroupBox)
        self.kseparator.setObjectName(_fromUtf8("kseparator"))
        self.verticalLayout.addWidget(self.kseparator)
        self.settingsWidget = SettingsWidget(self.settingsGroupBox)
        self.settingsWidget.setObjectName(_fromUtf8("settingsWidget"))
        self.verticalLayout.addWidget(self.settingsWidget)
        self.verticalLayout_2.addWidget(self.settingsGroupBox)

        self.retranslateUi(PhrasePage)
        QtCore.QMetaObject.connectSlotsByName(PhrasePage)

    def retranslateUi(self, PhrasePage):
        PhrasePage.setWindowTitle(kdecore.i18n(_fromUtf8("Form")))
        self.urlLabel.setTipText(kdecore.i18n(_fromUtf8("Open the phrase in the default text editor")))
        self.settingsGroupBox.setTitle(kdecore.i18n(_fromUtf8("Phrase Settings")))
        self.promptCheckbox.setText(kdecore.i18n(_fromUtf8("Always prompt before pasting this phrase")))
        self.showInTrayCheckbox.setText(kdecore.i18n(_fromUtf8("Show in notification icon menu")))
        self.label.setText(kdecore.i18n(_fromUtf8("Paste using")))
Ejemplo n.º 7
0
    def setupUi(self, PhrasePage):
        PhrasePage.setObjectName(_fromUtf8("PhrasePage"))
        PhrasePage.resize(540, 421)
        self.verticalLayout_2 = QtGui.QVBoxLayout(PhrasePage)
        self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
        self.urlLabel = KUrlLabel(PhrasePage)
        self.urlLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.urlLabel.setObjectName(_fromUtf8("urlLabel"))
        self.verticalLayout_2.addWidget(self.urlLabel)
        self.phraseText = KTextEdit(PhrasePage)
        self.phraseText.setTabChangesFocus(True)
        self.phraseText.setLineWrapMode(QtGui.QTextEdit.NoWrap)
        self.phraseText.setAcceptRichText(False)
        self.phraseText.setObjectName(_fromUtf8("phraseText"))
        self.verticalLayout_2.addWidget(self.phraseText)
        self.settingsGroupBox = QtGui.QGroupBox(PhrasePage)
        self.settingsGroupBox.setObjectName(_fromUtf8("settingsGroupBox"))
        self.verticalLayout = QtGui.QVBoxLayout(self.settingsGroupBox)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.promptCheckbox = QtGui.QCheckBox(self.settingsGroupBox)
        self.promptCheckbox.setObjectName(_fromUtf8("promptCheckbox"))
        self.verticalLayout.addWidget(self.promptCheckbox)
        self.showInTrayCheckbox = QtGui.QCheckBox(self.settingsGroupBox)
        self.showInTrayCheckbox.setObjectName(_fromUtf8("showInTrayCheckbox"))
        self.verticalLayout.addWidget(self.showInTrayCheckbox)
        self.horizontalLayout_2 = QtGui.QHBoxLayout()
        self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
        self.label = QtGui.QLabel(self.settingsGroupBox)
        self.label.setObjectName(_fromUtf8("label"))
        self.horizontalLayout_2.addWidget(self.label)
        self.sendModeCombo = QtGui.QComboBox(self.settingsGroupBox)
        self.sendModeCombo.setObjectName(_fromUtf8("sendModeCombo"))
        self.horizontalLayout_2.addWidget(self.sendModeCombo)
        spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.kseparator = KSeparator(self.settingsGroupBox)
        self.kseparator.setObjectName(_fromUtf8("kseparator"))
        self.verticalLayout.addWidget(self.kseparator)
        self.settingsWidget = SettingsWidget(self.settingsGroupBox)
        self.settingsWidget.setObjectName(_fromUtf8("settingsWidget"))
        self.verticalLayout.addWidget(self.settingsWidget)
        self.verticalLayout_2.addWidget(self.settingsGroupBox)

        self.retranslateUi(PhrasePage)
        QtCore.QMetaObject.connectSlotsByName(PhrasePage)
Ejemplo n.º 8
0
    def __init__(self, parent=None):
        ' Initialize QWidget inside MyMainWindow '
        super(MyMainWindow, self).__init__(parent)
        self.statusBar().showMessage(__doc__.title())
        self.setWindowTitle(__doc__)
        self.setMinimumSize(600, 800)
        self.setMaximumSize(2048, 1024)
        self.resize(1024, 800)
        self.setWindowIcon(QIcon.fromTheme("face-monkey"))
        if not A11Y:
            self.setStyleSheet('''QWidget{color:#fff;font-family:Oxygen}
            QWidget:item:hover, QWidget:item:selected {
                background-color: cyan; color: #000
            }
            QWidget:disabled { color: #404040; background-color: #323232 }
            QWidget:focus { border: 1px solid cyan }
            QPushButton {
                background-color: gray;
                padding: 3px; border: 1px solid gray; border-radius: 9px;
                margin: 0;font-size: 12px;
                padding-left: 5px; padding-right: 5px
            }
            QLineEdit, QTextEdit {
                background-color: #4a4a4a; border: 1px solid gray;
                border-radius: 0; font-size: 12px;
            }
            QPushButton:pressed { background-color: #323232 }
            QComboBox {
                background-color: #4a4a4a; padding-left: 9px;
                border: 1px solid gray; border-radius: 5px;
            }
            QComboBox:pressed { background-color: gray }
            QComboBox QAbstractItemView, QMenu {
                border: 1px solid #4a4a4a; background:grey;
                selection-background-color: cyan;
                selection-color: #000;
            }
            QSlider {
                padding: 3px; font-size: 8px; padding-left: 2px;
                padding-right: 2px; border: 5px solid #1e1e1e
            }
            QSlider::sub-page:vertical {
                background-color: QLinearGradient(spread:pad, x1:0, y1:0, x2:1,
                    y2:0.27, stop:0 rgba(255, 0, 0, 255),
                    stop:1 rgba(50, 0, 0, 200));
                border: 4px solid #1e1e1e; border-radius: 5px
            }
            QSlider::add-page:vertical {
                background-color: QLinearGradient(spread:pad, x1:0, y1:0, x2:1,
                    y2:0.27, stop:0 rgba(0, 255, 0, 255),
                    stop:1 rgba(0, 99, 0, 255));
                border: 4px solid #1e1e1e; border-radius: 5px;
            }
            QSlider::handle:vertical {
                background-color: QLinearGradient(spread:pad, x1:0, y1:0, x2:1,
                    y2:0.273, stop:0 rgba(0, 0, 0, 255), stop:1 gray);
                height: 5px; border: 1px dotted #fff; text-align: center;
                border-top-left-radius: 2px; border-bottom-left-radius: 2px;
                border-top-right-radius: 2px; border-bottom-right-radius 2px;
                margin-left: 2px; margin-right: 2px;
            }
            QSlider::handle:vertical:hover { border: 1px solid cyan }
            QSlider::sub-page:vertical:disabled {
                background: #bbb; border-color: #999;
            }
            QSlider::add-page:vertical:disabled {
                background: #eee; border-color: #999;
            }
            QSlider::handle:vertical:disabled {
                background: #eee; border: 1px solid #aaa; border-radius: 4px;
            }
            QToolBar, QStatusBar, QDockWidget::title{background-color:#323232;}
            QToolBar::handle,
            QToolBar::handle:vertical, QToolBar::handle:horizontal {
                border: 1px solid gray; border-radius: 9px; width: 19px;
                height: 19px; margin: 0.5px
            }
            QGroupBox {
                border: 1px solid gray; border-radius: 9px; padding-top: 9px;
            }
            QStatusBar, QToolBar::separator:horizontal,
            QToolBar::separator:vertical {color:gray}
            QScrollBar:vertical{
                background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0,
                    stop: 0 #212121,stop: 1.0 #323232);
                width: 10px;
            }
            QScrollBar:horizontal{
                background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                    stop: 0 #212121,stop: 1.0 #323232);
                height: 10px;
            }
            QScrollBar::handle:vertical{
                padding: 2px;
                min-height: 50px;
                background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0,
                    stop: 0 #585858,stop: 1.0 #404040);
                border-radius: 5px;
                border: 1px solid #191919;
            }
            QScrollBar::handle:horizontal{
                padding: 2px;
                min-width: 50px;
                background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                    stop: 0 #585858,stop: 1.0 #404040);
                border-radius: 5px;
                border: 1px solid #191919;
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical,
            QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical,
            QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal,
            QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {
                background: none; border: none;
            }
            QDockWidget::close-button, QDockWidget::float-button {
                border: 1px solid gray;
                border-radius: 3px;
                background: darkgray;
            }''')

        self.process = QProcess()
        self.process.readyReadStandardOutput.connect(self.read_output)
        self.process.readyReadStandardError.connect(self.read_errors)
        self.process.finished.connect(self._process_finished)
        self.process.error.connect(self._process_finished)

        self.group0, self.group1 = QGroupBox("Options"), QGroupBox("Paths")
        self.group2 = QGroupBox("Nodes")
        self.group3 = QGroupBox("Python Code")
        self.group4, self.group5 = QGroupBox("Logs"), QGroupBox("Backend")
        g0grid, g1vlay = QGridLayout(self.group0), QVBoxLayout(self.group1)
        g5vlay = QVBoxLayout(self.group5)

        self.treeview_nodes, self.textedit_source = QTextEdit(), QTextEdit()
        self.dock1, self.dock2 = QDockWidget(), QDockWidget()
        self.output, self.dock3 = QTextEdit(), QDockWidget()
        self.treeview_nodes.setAutoFormatting(QTextEdit.AutoAll)
        self.treeview_nodes.setWordWrapMode(QTextOption.NoWrap)
        self.dock1.setWidget(self.treeview_nodes)
        self.dock2.setWidget(self.textedit_source)
        self.dock3.setWidget(self.output)
        self.dock1.setWindowTitle("Tree")
        self.dock2.setWindowTitle("Sources")
        self.dock3.setWindowTitle("STDOutput")
        featur = QDockWidget.DockWidgetMovable | QDockWidget.DockWidgetFloatable
        self.dock1.setFeatures(featur)
        self.dock2.setFeatures(featur)
        self.dock3.setFeatures(featur)
        QVBoxLayout(self.group2).addWidget(self.dock1)
        QVBoxLayout(self.group3).addWidget(self.dock2)
        QVBoxLayout(self.group4).addWidget(self.dock3)
        self.slider1, self.slider2 = QSlider(), QSlider()
        g0grid.addWidget(self.slider1, 0, 0)
        g0grid.addWidget(QLabel('Use Debug'), 0, 1)
        self.slider2.setValue(1)
        g0grid.addWidget(self.slider2, 1, 0)
        g0grid.addWidget(QLabel('Use verbose'), 1, 1)

        self.slider3, self.slider4 = QSlider(), QSlider()
        self.slider3.setValue(1)
        g0grid.addWidget(self.slider3, 2, 0)
        g0grid.addWidget(QLabel('Show compiling progress'), 2, 1)
        self.slider4.setValue(1)
        g0grid.addWidget(self.slider4, 3, 0)
        g0grid.addWidget(QLabel('Show Scons building debug'), 3, 1)

        self.slider5, self.slider6 = QSlider(), QSlider()
        g0grid.addWidget(self.slider5, 4, 0)
        g0grid.addWidget(QLabel('Keep debug unstriped binary'), 4, 1)
        g0grid.addWidget(self.slider6, 5, 0)
        g0grid.addWidget(QLabel('Traced execution outputs'), 5, 1)

        self.slider7, self.slider8 = QSlider(), QSlider()
        self.slider7.setValue(1)
        g0grid.addWidget(self.slider7, 6, 0)
        g0grid.addWidget(QLabel('Remove the build folder'), 6, 1)
        g0grid.addWidget(self.slider8, 7, 0)
        g0grid.addWidget(QLabel('No Python Optimizations'), 7, 1)

        self.slider9, self.slider10 = QSlider(), QSlider()
        g0grid.addWidget(self.slider9, 8, 0)
        g0grid.addWidget(QLabel('No Statements line numbers'), 8, 1)
        g0grid.addWidget(self.slider10, 9, 0)
        g0grid.addWidget(QLabel('Execute the output binary'), 9, 1)

        self.slider11, self.slider12 = QSlider(), QSlider()
        g0grid.addWidget(self.slider11, 10, 0)
        g0grid.addWidget(QLabel('Warning detected implicit exceptions'), 10, 1)
        g0grid.addWidget(self.slider12, 11, 0)
        g0grid.addWidget(QLabel('Keep the PYTHONPATH, do not Reset it'), 11, 1)

        self.slider13 = QSlider()
        g0grid.addWidget(self.slider13, 12, 0)
        g0grid.addWidget(QLabel('Enhance compile, CPython incompatible'), 12,
                         1)

        self.slider1a, self.slider2a = QSlider(), QSlider()
        g0grid.addWidget(self.slider1a, 0, 2)
        g0grid.addWidget(QLabel('Descendent Recursive Compile'), 0, 3)
        self.slider2a.setValue(1)
        g0grid.addWidget(self.slider2a, 1, 2)
        g0grid.addWidget(QLabel('Force non recursive compile'), 1, 3)

        self.slider3a, self.slider4a = QSlider(), QSlider()
        g0grid.addWidget(self.slider3a, 2, 2)
        g0grid.addWidget(QLabel('STD Lib Recursive Compile'), 2, 3)
        g0grid.addWidget(self.slider4a, 3, 2)
        g0grid.addWidget(QLabel('Enforce the use of Clang'), 3, 3)

        self.slider5a, self.slider6a = QSlider(), QSlider()
        self.slider5a.setValue(1)
        g0grid.addWidget(self.slider5a, 4, 2)
        g0grid.addWidget(QLabel('Use G++ link time optimizations'), 4, 3)
        g0grid.addWidget(self.slider6a, 5, 2)
        g0grid.addWidget(QLabel('Disable the console window'), 5, 3)

        self.slider7a, self.slider8a = QSlider(), QSlider()
        g0grid.addWidget(self.slider7a, 6, 2)
        g0grid.addWidget(QLabel('Force compile for MS Windows'), 6, 3)
        g0grid.addWidget(self.slider8a, 7, 2)
        g0grid.addWidget(QLabel('Use Python Debug versions'), 7, 3)

        self.slider9a, self.slider10a = QSlider(), QSlider()
        self.slider9a.setValue(1)
        g0grid.addWidget(self.slider9a, 8, 2)
        g0grid.addWidget(QLabel('Create standalone executable'), 8, 3)
        g0grid.addWidget(self.slider10a, 9, 2)
        g0grid.addWidget(QLabel('Enable Standalone mode build'), 9, 3)

        self.slider11a, self.slider12a = QSlider(), QSlider()
        g0grid.addWidget(self.slider11a, 10, 2)
        g0grid.addWidget(QLabel('Make module executable instead of app'), 10,
                         3)
        g0grid.addWidget(self.slider12a, 11, 2)
        g0grid.addWidget(QLabel('No froze module of stdlib as bytecode'), 11,
                         3)

        self.slider13a = QSlider()
        g0grid.addWidget(self.slider13a, 12, 2)
        g0grid.addWidget(QLabel('Force use of MinGW on MS Windows'), 12, 3)

        for each_widget in (self.slider1, self.slider2, self.slider3,
                            self.slider4, self.slider5, self.slider6,
                            self.slider7, self.slider8, self.slider9,
                            self.slider10, self.slider11, self.slider12,
                            self.slider13, self.slider1a, self.slider2a,
                            self.slider3a, self.slider4a, self.slider5a,
                            self.slider6a, self.slider7a, self.slider8a,
                            self.slider9a, self.slider10a, self.slider11a,
                            self.slider12a, self.slider13a):
            each_widget.setRange(0, 1)
            each_widget.setCursor(QCursor(Qt.OpenHandCursor))
            each_widget.setTickInterval(1)
            each_widget.TickPosition(QSlider.TicksBothSides)

        self.combo1 = QComboBox()
        self.combo1.addItems(('2.7', '2.6', '3.2', '3.3'))
        g5vlay.addWidget(QLabel('Python Version'))
        g5vlay.addWidget(self.combo1)
        self.combo2 = QComboBox()
        self.combo2.addItems(('Default', 'Low', 'High'))
        g5vlay.addWidget(QLabel('CPU priority'))
        g5vlay.addWidget(self.combo2)
        self.combo3 = QComboBox()
        self.combo3.addItems(('1', '2', '3', '4', '5', '6', '7', '8', '9'))
        g5vlay.addWidget(QLabel('MultiProcessing Workers'))
        g5vlay.addWidget(self.combo3)

        self.outdir = QLineEdit()
        self.outdir.setStyleSheet("QLineEdit{margin-left:25px}")
        self.clearButton = QToolButton(self.outdir)
        self.clearButton.setIcon(QIcon.fromTheme("edit-clear"))
        self.clearButton.setIconSize(QSize(25, 25))
        self.clearButton.setStyleSheet("QToolButton{border:none}")
        self.clearButton.hide()
        self.clearButton.clicked.connect(self.outdir.clear)
        self.outdir.textChanged.connect(
            lambda: self.clearButton.setVisible(True))
        self.clearButton.clicked.connect(
            lambda: self.clearButton.setVisible(False))
        self.outdir.setPlaceholderText('Output Directory')
        if path.isfile('.nuitka-output-dir.txt'):
            self.outdir.setText(open('.nuitka-output-dir.txt', 'r').read())
        else:
            self.outdir.setText(path.expanduser("~"))
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.Dirs | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        self.completer.popup().setStyleSheet(
            """border:1px solid #4a4a4a;background:grey;
            selection-background-color:cyan;selection-color:#000""")
        self.completer.popup().setVerticalScrollBarPolicy(
            Qt.ScrollBarAlwaysOff)
        self.outdir.setCompleter(self.completer)

        self.btn1 = QPushButton(QIcon.fromTheme("document-open"),
                                'Open' if IS_WIN else '')
        self.btn1.clicked.connect(
            lambda: open('.nuitka-output-dir.txt', 'w').write(
                str(
                    QFileDialog.getExistingDirectory(
                        None, 'Open Output Directory', path.expanduser("~")))))
        self.btn1.released.connect(lambda: self.outdir.setText(
            open('.nuitka-output-dir.txt', 'r').read()))
        g1vlay.addWidget(QLabel('Output Directory'))
        g1vlay.addWidget(self.outdir)
        g1vlay.addWidget(self.btn1)

        self.target = QLineEdit()
        self.target.setStyleSheet("QLineEdit{margin-left:25px}")
        self.clearButton2 = QToolButton(self.target)
        self.clearButton2.setIcon(QIcon.fromTheme("edit-clear"))
        self.clearButton2.setIconSize(QSize(25, 25))
        self.clearButton2.setStyleSheet("QToolButton{border:none}")
        self.clearButton2.hide()
        self.clearButton2.clicked.connect(self.target.clear)
        self.target.textChanged.connect(
            lambda: self.clearButton2.setVisible(True))
        self.clearButton2.clicked.connect(
            lambda: self.clearButton2.setVisible(False))
        self.target.setPlaceholderText('Target Python App to Binary Compile')
        self.target.setCompleter(self.completer)
        self.btn2 = QPushButton(QIcon.fromTheme("document-open"),
                                'Open' if IS_WIN else '')
        self.btn2.clicked.connect(lambda: self.target.setText(
            str(
                QFileDialog.getOpenFileName(
                    None, "Open", path.expanduser("~"), ';;'.join([
                        '{}(*.{})'.format(e.upper(), e)
                        for e in ('py', 'pyw', '*')
                    ])))))
        g1vlay.addWidget(QLabel('Input File'))
        g1vlay.addWidget(self.target)
        g1vlay.addWidget(self.btn2)

        self.icon, self.icon_label = QLineEdit(), QLabel('Icon File')
        self.icon.setStyleSheet("QLineEdit{margin-left:25px}")
        self.clearButton3 = QToolButton(self.icon)
        self.clearButton3.setIcon(QIcon.fromTheme("edit-clear"))
        self.clearButton3.setIconSize(QSize(25, 25))
        self.clearButton3.setStyleSheet("QToolButton{border:none}")
        self.clearButton3.hide()
        self.clearButton3.clicked.connect(self.icon.clear)
        self.icon.textChanged.connect(
            lambda: self.clearButton3.setVisible(True))
        self.clearButton3.clicked.connect(
            lambda: self.clearButton3.setVisible(False))
        self.icon.setPlaceholderText('Path to Icon file for your App')
        self.icon.setCompleter(self.completer)
        self.btn3 = QPushButton(QIcon.fromTheme("document-open"),
                                'Open' if IS_WIN else '')
        self.btn3.clicked.connect(lambda: self.icon.setText(
            str(
                QFileDialog.getOpenFileName(
                    None, "Open", path.expanduser("~"), ';;'.join([
                        '{}(*.{})'.format(e.upper(), e)
                        for e in ('ico', 'png', 'bmp', 'svg', '*')
                    ])))))
        g1vlay.addWidget(self.icon_label)
        g1vlay.addWidget(self.icon)
        g1vlay.addWidget(self.btn3)

        # Menu Bar inicialization and detail definitions
        menu_salir = QAction(QIcon.fromTheme("application-exit"), 'Quit', self)
        menu_salir.setStatusTip('Quit')
        menu_salir.triggered.connect(exit)
        menu_minimize = QAction(QIcon.fromTheme("go-down"), 'Minimize', self)
        menu_minimize.setStatusTip('Minimize')
        menu_minimize.triggered.connect(lambda: self.showMinimized())
        menu_qt = QAction(QIcon.fromTheme("help-about"), 'About Qt', self)
        menu_qt.setStatusTip('About Qt...')
        menu_qt.triggered.connect(lambda: QMessageBox.aboutQt(self))
        menu_dev = QAction(QIcon.fromTheme("applications-development"),
                           'Developer Manual PDF', self)
        menu_dev.setStatusTip('Open Nuitka Developer Manual PDF...')
        menu_dev.triggered.connect(lambda: call(
            OPEN + '/usr/share/doc/nuitka/Developer_Manual.pdf.gz', shell=True)
                                   )
        menu_usr = QAction(QIcon.fromTheme("help-contents"), 'User Docs', self)
        menu_usr.setStatusTip('Open Nuitka End User Manual PDF...')
        menu_usr.triggered.connect(lambda: call(
            OPEN + '/usr/share/doc/nuitka/README.pdf.gz', shell=True))
        menu_odoc = QAction(QIcon.fromTheme("help-browser"), 'OnLine Doc',
                            self)
        menu_odoc.setStatusTip('Open Nuitka on line Documentation pages...')
        menu_odoc.triggered.connect(
            lambda: open_new_tab('http://nuitka.net/doc/user-manual.html'))
        menu_man = QAction(QIcon.fromTheme("utilities-terminal"), 'Man', self)
        menu_man.setStatusTip('Open Nuitka technical command line Man Pages..')
        menu_man.triggered.connect(
            lambda: call('xterm -e "man nuitka"', shell=True))
        menu_tra = QAction(QIcon.fromTheme("applications-development"),
                           'View Nuitka-GUI Source Code', self)
        menu_tra.setStatusTip('View, study, edit Nuitka-GUI Libre Source Code')
        menu_tra.triggered.connect(lambda: call(OPEN + __file__, shell=True))
        menu_foo = QAction(QIcon.fromTheme("folder"), 'Open Output Dir', self)
        menu_foo.setStatusTip('Open the actual Output Directory location...')
        menu_foo.triggered.connect(
            lambda: call(OPEN + str(self.outdir.text()), shell=True))
        menu_pic = QAction(QIcon.fromTheme("camera-photo"), 'Screenshot', self)
        menu_pic.setStatusTip('Take a Screenshot for Documentation purposes..')
        menu_pic.triggered.connect(
            lambda: QPixmap.grabWindow(QApplication.desktop().winId()).save(
                QFileDialog.getSaveFileName(None, "Save", path.expanduser("~"),
                                            'PNG(*.png)', 'png')))
        menu_don = QAction(QIcon.fromTheme("emblem-favorite"), 'Help Nuitka',
                           self)
        menu_don.setStatusTip('Help the Nuitka Open Source Libre Free Project')
        menu_don.triggered.connect(
            lambda: open_new_tab('http://nuitka.net/pages/donations.html'))

        # movable draggable toolbar
        self.toolbar = QToolBar(self)
        self.toolbar.setIconSize(QSize(16, 16))
        self.toolbar.toggleViewAction().setText("Show/Hide Toolbar")
        l_spacer, r_spacer = QWidget(self), QWidget(self)
        l_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        r_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.toolbar.addWidget(l_spacer)
        self.toolbar.addSeparator()
        self.toolbar.addActions((menu_salir, menu_minimize, menu_qt, menu_odoc,
                                 menu_foo, menu_pic, menu_don))
        if not IS_WIN:
            self.toolbar.addActions((menu_man, menu_dev, menu_tra, menu_usr))
        self.toolbar.addSeparator()
        self.toolbar.addWidget(r_spacer)
        self.addToolBar(Qt.BottomToolBarArea, self.toolbar)

        # Bottom Buttons Bar
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Close)
        self.buttonBox.rejected.connect(exit)
        self.buttonBox.accepted.connect(self.run)

        self.guimode = QComboBox()
        self.guimode.addItems(('Full UX / UI', 'Simple UX / UI'))
        self.guimode.setStyleSheet(
            """QComboBox{background:transparent;border:0;
            margin-left:25px;color:gray;text-decoration:underline}""")
        self.guimode.currentIndexChanged.connect(self.set_guimode)

        container = QWidget()
        container_layout = QGridLayout(container)  # Y, X
        container_layout.addWidget(self.guimode, 0, 1)
        container_layout.addWidget(self.group2, 1, 0)
        container_layout.addWidget(self.group3, 2, 0)
        container_layout.addWidget(self.group0, 1, 1)
        container_layout.addWidget(self.group1, 2, 1)
        container_layout.addWidget(self.group4, 1, 2)
        container_layout.addWidget(self.group5, 2, 2)
        container_layout.addWidget(self.buttonBox, 3, 1)
        self.setCentralWidget(container)
        # Paleta de colores para pintar transparente
        if not A11Y:
            palette = self.palette()
            palette.setBrush(QPalette.Base, Qt.transparent)
            self.setPalette(palette)
            self.setAttribute(Qt.WA_OpaquePaintEvent, False)
Ejemplo n.º 9
0
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        ec = ExplorerContainer()
        super(Main, self).initialize(*args, **kwargs)

        self.editor_s = self.locator.get_service('editor')
        # directory auto completer
        self.completer = QCompleter(self)
        self.dirs = QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)

        self.group0 = QGroupBox()
        self.group0.setTitle(' Source ')
        self.source = QComboBox()
        self.source.addItems(['Clipboard', 'Local File', 'Remote URL', 'Ninja'])
        self.source.currentIndexChanged.connect(self.on_source_changed)
        self.infile = QLineEdit(path.expanduser("~"))
        self.infile.setPlaceholderText(' /full/path/to/file.html ')
        self.infile.setCompleter(self.completer)
        self.open = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open.setCursor(QCursor(Qt.PointingHandCursor))
        self.open.clicked.connect(lambda: self.infile.setText(str(
            QFileDialog.getOpenFileName(self.dock, "Open a File to read from",
            path.expanduser("~"), ';;'.join(['{}(*.{})'.format(e.upper(), e)
            for e in ['css', 'html', 'js', 'txt', '*']])))))
        self.inurl = QLineEdit('http://www.')
        self.inurl.setPlaceholderText('http://www.full/url/to/remote/file.html')
        self.output = QPlainTextEdit(SAMPLE_TEXT)
        vboxg0 = QVBoxLayout(self.group0)
        for each_widget in (self.source, self.infile, self.open, self.inurl,
            self.output, ):
            vboxg0.addWidget(each_widget)
        [a.hide() for a in iter((self.infile, self.open, self.inurl))]

        self.group1 = QGroupBox()
        self.group1.setTitle(' CSS3 ')
        self.group1.setCheckable(True)
        self.group1.setGraphicsEffect(QGraphicsBlurEffect(self))
        self.group1.graphicsEffect().setEnabled(False)
        self.group1.toggled.connect(self.toggle_css_group)
        self.ckcss1 = QCheckBox('Remove unnecessary Comments')
        self.ckcss2 = QCheckBox('Remove unnecessary Whitespace characters')
        self.ckcss3 = QCheckBox('Remove unnecessary Semicolons')
        self.ckcss4 = QCheckBox('Remove unnecessary Empty rules')
        self.ckcss5 = QCheckBox('Condense and Convert Colors from RGB to HEX')
        self.ckcss6 = QCheckBox('Condense all Zero units')
        self.ckcss7 = QCheckBox('Condense Multidimensional Zero units')
        self.ckcss8 = QCheckBox('Condense Floating point numbers')
        self.ckcss9 = QCheckBox('Condense HEX Colors')
        self.ckcss10 = QCheckBox('Condense multiple adjacent Whitespace chars')
        self.ckcss11 = QCheckBox('Condense multiple adjacent semicolon chars')
        self.ckcss12 = QCheckBox('Wrap the lines of the to 80 character length')
        self.ckcss13 = QCheckBox('Condense Font Weight values')
        self.ckcss14 = QCheckBox('Condense the 17 Standard Named Colors values')
        self.ckcss15 = QCheckBox('Condense the 124 Extra Named Colors values')
        self.ckcss16 = QCheckBox('Condense all Percentages values when posible')
        self.ckcss17 = QCheckBox('Condense all Pixels values when posible')
        self.ckcss18 = QCheckBox('Remove unnecessary quotes from url()')
        self.ckcss19 = QCheckBox('Add standard Encoding Declaration if missing')
        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (self.ckcss1, self.ckcss2, self.ckcss3, self.ckcss4,
            self.ckcss5, self.ckcss6, self.ckcss7, self.ckcss8, self.ckcss9,
            self.ckcss10, self.ckcss11, self.ckcss12, self.ckcss13,
            self.ckcss14, self.ckcss15, self.ckcss16, self.ckcss17,
            self.ckcss18, self.ckcss19):
            vboxg1.addWidget(each_widget)
            each_widget.setToolTip(each_widget.text())

        self.group2 = QGroupBox()
        self.group2.setTitle(' HTML5 ')
        self.group2.setCheckable(True)
        self.group2.setGraphicsEffect(QGraphicsBlurEffect(self))
        self.group2.graphicsEffect().setEnabled(False)
        self.group2.toggled.connect(self.toggle_html_group)
        self.ckhtml0 = QCheckBox('Condense Style and Script HTML Tags')
        self.ckhtml1 = QCheckBox('Condense DOCTYPE to new HTML5 Tags')
        self.ckhtml2 = QCheckBox('Condense Href and Src to protocol agnostic')
        self.ckhtml4 = QCheckBox('Remove unnecessary Tags but keep HTML valid')
        self.help1 = QLabel('''<a href=
            "https://developers.google.com/speed/articles/optimizing-html">
            <small><center>Help about Unneeded Unnecessary HTML tags ?</a>''')
        self.help1.setTextInteractionFlags(Qt.LinksAccessibleByMouse)
        self.help1.setOpenExternalLinks(True)
        vboxg2 = QVBoxLayout(self.group2)
        for each_widget in (self.ckhtml0, self.ckhtml1, self.ckhtml2,
            self.ckhtml4, self.help1, ):
            vboxg2.addWidget(each_widget)
            each_widget.setToolTip(each_widget.text())

        self.group3 = QGroupBox()
        self.group3.setTitle(' Javascript ')
        self.ckjs0 = QCheckBox('Condense and Compress Javascript')
        self.ckjs1 = QCheckBox('Condense $(document).ready(function(){ });')
        vboxg2 = QVBoxLayout(self.group3)
        for each_widget in (self.ckjs0, self.ckjs1):
            vboxg2.addWidget(each_widget)
            each_widget.setToolTip(each_widget.text())

        self.group4 = QGroupBox()
        self.group4.setTitle(' General ')
        self.chckbx1 = QCheckBox('Lower case ALL the text')
        self.chckbx2 = QCheckBox('Remove Spaces, Tabs, New Lines, Empty Lines')
        self.befor, self.after = QProgressBar(), QProgressBar()
        self.befor.setFormat("%v Chars")
        self.after.setFormat("%v Chars")
        vboxg4 = QVBoxLayout(self.group4)
        for each_widget in (self.chckbx1, self.chckbx2,
            QLabel('<b>Before:'), self.befor, QLabel('<b>After:'), self.after):
            vboxg4.addWidget(each_widget)
            each_widget.setToolTip(each_widget.text())

        [a.setChecked(True) for a in iter((self.ckcss1, self.ckcss2,
            self.ckcss3, self.ckcss4, self.ckcss5, self.ckcss6, self.ckcss7,
            self.ckcss8, self.ckcss9, self.ckcss10, self.ckcss11, self.ckcss12,
            self.ckcss13, self.ckcss14, self.ckcss15, self.ckcss16,
            self.ckcss17, self.ckcss18, self.ckcss19, self.ckjs1, self.ckhtml0,
            self.ckhtml1, self.ckhtml2, self.ckhtml4, self.chckbx1,
            self.chckbx2))]

        self.button = QPushButton(QIcon.fromTheme("face-cool"), 'Process Text')
        self.button.setCursor(QCursor(Qt.PointingHandCursor))
        self.button.setMinimumSize(100, 50)
        self.button.clicked.connect(self.run)

        def must_glow(widget_list):
            ' apply an glow effect to the widget '
            for glow, each_widget in enumerate(widget_list):
                try:
                    if each_widget.graphicsEffect() is None:
                        glow = QGraphicsDropShadowEffect(self)
                        glow.setOffset(0)
                        glow.setBlurRadius(99)
                        glow.setColor(QColor(99, 255, 255))
                        each_widget.setGraphicsEffect(glow)
                        glow.setEnabled(True)
                except:
                    pass

        must_glow((self.button, ))

        class TransientWidget(QWidget):
            ' persistant widget thingy '
            def __init__(self, widget_list):
                ' init sub class '
                super(TransientWidget, self).__init__()
                vbox = QVBoxLayout(self)
                for each_widget in widget_list:
                    vbox.addWidget(each_widget)

        tw = TransientWidget((QLabel('<b>HTML5/CSS3/JS Optimizer Compressor'),
            self.group0, self.group1, self.group2, self.group3, self.group4,
            self.button, ))
        self.scrollable = QScrollArea()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(tw)
        self.dock = QDockWidget()
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setMinimumWidth(350)
        self.dock.setWidget(self.scrollable)
        ec.addTab(self.dock, "Web")
        QPushButton(QIcon.fromTheme("help-about"), 'About', self.dock
          ).clicked.connect(lambda: QMessageBox.information(self.dock, __doc__,
            HELPMSG))
Ejemplo n.º 10
0
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        ec = ExplorerContainer()
        super(Main, self).initialize(*args, **kwargs)
        # directory auto completer
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        self.RUNS, self.FAILS = 0, 0
        self.group0 = QGroupBox()
        self.group0.setTitle(' Source and Target ')
        self.baseurl = QLineEdit('http://google.com')
        self.outfile = QLineEdit(path.join(path.expanduser("~"), 'test.py'))
        self.outfile.setCompleter(self.completer)
        self.open = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open.clicked.connect(lambda: self.outfile.setText(
            QFileDialog.getSaveFileName(self.dock, "Save", path.expanduser("~"),
            'PYTHON(*.py)')))
        vboxg0 = QVBoxLayout(self.group0)
        for each_widget in (QLabel('<b>Base URL'), self.baseurl,
            QLabel('<b>Local File Target'), self.outfile, self.open):
            vboxg0.addWidget(each_widget)

        self.group1 = QGroupBox()
        self.group1.setTitle(' Selenium ')
        self.group1.setCheckable(True)
        self.group1.setGraphicsEffect(QGraphicsBlurEffect(self))
        self.group1.graphicsEffect().setEnabled(False)
        self.group1.toggled.connect(self.toggle_group)
        self.ckcss1 = QCheckBox('Test for correct Page Loading behaviour')
        self.ckcss2 = QCheckBox('Test for Sucessfull Status Code return')
        self.ckcss3 = QCheckBox('Test for valid Title of the web page')
        self.ckcss4 = QCheckBox('Test for Cookies Basic functionality')
        self.ckcss5 = QCheckBox('Test for Back, Forward, Reload behaviour')
        self.ckcss6 = QCheckBox('Take a Screenshot of page (CSS Debug)')
        self.ckcss7 = QCheckBox('Test for Search Form Field of the page')
        self.ckcss8 = QCheckBox('Test for Arbitrary Javascript (User provided)')
        self.ckcss9 = QCheckBox('Test for iFrame of the web page')
        self.ckcss10 = QCheckBox('Test for HTML5 Canvas element on the page')
        self.ckcss11 = QCheckBox('Test for HTML5 SVG element on the page')
        self.ckcss12 = QCheckBox('Test for HTML5 Audio element on the page')
        self.ckcss13 = QCheckBox('Test for HTML5 Video element on the page')
        self.ckcss14 = QCheckBox('Test for File Upload form on the page')
        self.ckcss15 = QCheckBox('Add ChromeDriver path to sys.path')
        self.webdriver = QComboBox()
        self.webdriver.addItems(['firefox', 'chrome',
                                 'zope.testbrowser', 'phantomjs'])
        self.titletxt = QLineEdit('Google')
        self.javascript = QLineEdit('console.log("test")')
        self.authdata, self.formdata = QLineEdit(), QLineEdit()
        self.authdata.setPlaceholderText("{'username':'******','password':'******'}")
        self.formdata.setPlaceholderText("{'name': 'Joe', 'age': '25'}")
        self.iframurl = QLineEdit()
        self.chrmedrv = QLineEdit('/usr/bin/chromedriver')
        self.timeout = QSpinBox()
        self.timeout.setMaximum(99)
        self.timeout.setMinimum(0)
        self.timeout.setValue(9)
        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (self.ckcss1, self.ckcss2, self.ckcss3, self.ckcss4,
            self.ckcss5, self.ckcss6, self.ckcss7, self.ckcss8, self.ckcss9,
            self.ckcss10, self.ckcss11, self.ckcss12, self.ckcss13,
            self.ckcss14, self.ckcss15, QLabel('<b>WebDriver'), self.webdriver,
            QLabel('''<center><small><i>Firefox is only Driver that dont
                   require additional configuration'''),
            QLabel('<b>Title Content must contain'), self.titletxt,
            QLabel('<b>Minified Javascript for Test'), self.javascript,
            QLabel('<b>Arbitrary Authentication Data for Test'), self.authdata,
            QLabel('<b>Arbitrary Form Data for Test'), self.formdata,
            QLabel('<b>iFrame URL for Test'), self.iframurl,
            QLabel('<b>Chrome Driver'), self.chrmedrv,
            QLabel('<b>Timeout Timer Limit'), self.timeout):
            vboxg1.addWidget(each_widget)
            try:
                each_widget.setToolTip(each_widget.text())
            except:
                each_widget.setToolTip(each_widget.currentText())

        self.group4 = QGroupBox()
        self.group4.setTitle(' General ')
        self.chckbx1 = QCheckBox('Run the Tests after Writing')
        self.chckbx2 = QCheckBox('Open the Tests with Ninja after Writing')
        self.chckbx3 = QCheckBox('Add SheBang, Encoding and Metadata to Tests')
        self.nice = QSpinBox()
        self.nice.setMaximum(20)
        self.nice.setMinimum(0)
        self.nice.setValue(20)
        self.help1 = QLabel('''<a href="http://splinter.cobrateam.info/docs/api"
            ><center><b>API Reference</a>''')
        self.help1.setTextInteractionFlags(Qt.LinksAccessibleByMouse)
        self.help1.setOpenExternalLinks(True)
        vboxg4 = QVBoxLayout(self.group4)
        for each_widget in (self.chckbx1, self.chckbx2, self.chckbx3,
            QLabel('Backend CPU priority:'), self.nice, self.help1):
            vboxg4.addWidget(each_widget)
            each_widget.setToolTip(each_widget.text())

        [a.setChecked(True) for a in (self.ckcss1, self.ckcss2, self.ckcss3,
            self.ckcss4, self.ckcss5, self.ckcss6, self.ckcss7, self.ckcss8,
            self.ckcss15, self.chckbx1, self.chckbx2, self.chckbx3)]

        self.button = QPushButton(QIcon.fromTheme("face-cool"),
                                  'Write and Run Test')
        self.button.setCursor(QCursor(Qt.PointingHandCursor))
        self.button.setMinimumSize(100, 50)
        self.button.clicked.connect(self.run)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.button.setGraphicsEffect(glow)
        glow.setEnabled(True)
        self.output = QPlainTextEdit()
        self.runs = QLabel('<font color="green"><b>Runs: 0')
        self.failures = QLabel('<font color="red"><b>Failures: 0')

        class TransientWidget(QWidget):
            ' persistant widget thingy '
            def __init__(self, widget_list):
                ' init sub class '
                super(TransientWidget, self).__init__()
                vbox = QVBoxLayout(self)
                for each_widget in widget_list:
                    vbox.addWidget(each_widget)

        tw = TransientWidget((QLabel('<b>Selenium Tests'), self.group0,
            self.group1, self.group4, QLabel('<b>Log'), self.output, self.runs,
            self.failures, self.button))
        self.scrollable, self.dock = QScrollArea(), QDockWidget()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(tw)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        ec.addTab(self.dock, "Selenium")
        QPushButton(QIcon.fromTheme("help-about"), 'About', self.dock
          ).clicked.connect(lambda: QMessageBox.information(self.dock, __doc__,
            HELPMSG))
        QPushButton(QIcon.fromTheme("media-record"), 'Record', self.group1,
          ).clicked.connect(lambda: QMessageBox.information(self.dock, __doc__,
        'Not working. If you know how to make it Record, send me Pull Request'))
Ejemplo n.º 11
0
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)

        self.desktop, self.project, menu = '', '', QMenu('Vagrant')
        menu.addAction('UP', lambda: self.vagrant_c('up'))
        menu.addAction('HALT', lambda: self.vagrant_c('halt'))
        menu.addAction('RELOAD', lambda: self.vagrant_c('reload'))
        menu.addAction('STATUS', lambda: self.vagrant_c('status'))
        menu.addAction('SUSPEND', lambda: self.vagrant_c('suspend'))
        menu.addAction('RESUME', lambda: self.vagrant_c('resume'))
        menu.addAction('PROVISION', lambda: self.vagrant_c('provision'))
        menu.addAction('PACKAGE', lambda: self.vagrant_c('package'))
        menu.addAction('INIT', lambda: self.vagrant_c('init'))
        menu.addSeparator()
        menu.addAction('DESTROY (!!!)', lambda: self.vagrant_c('destroy'))
        self.locator.get_service('explorer').add_project_menu(menu, lang='all')

        self.process = QProcess()
        self.process.readyReadStandardOutput.connect(self.readOutput)
        self.process.readyReadStandardError.connect(self.readErrors)
        self.process.finished.connect(self._process_finished)
        self.process.error.connect(self._process_finished)

        # Proxy support, by reading http_proxy os env variable
        proxy_url = QUrl(environ.get('http_proxy', ''))
        QNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.HttpProxy
            if str(proxy_url.scheme()).startswith('http')
            else QNetworkProxy.Socks5Proxy, proxy_url.host(), proxy_url.port(),
                 proxy_url.userName(), proxy_url.password())) \
            if 'http_proxy' in environ else None

        self.mainwidget = QTabWidget()
        self.mainwidget.tabCloseRequested.connect(lambda:
            self.mainwidget.setTabPosition(1)
            if self.mainwidget.tabPosition() == 0
            else self.mainwidget.setTabPosition(0))
        self.mainwidget.setStyleSheet('QTabBar{font-weight:bold;}')
        self.mainwidget.setMovable(True)
        self.mainwidget.setTabsClosable(True)

        self.dock, self.scrollable = QDockWidget(), QScrollArea()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(self.mainwidget)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)

        self.locator.get_service('misc').add_widget(self.dock,
                                 QIcon.fromTheme("virtualbox"), __doc__)

        self.tab1, self.tab2, self.tab3 = QGroupBox(), QGroupBox(), QGroupBox()
        self.tab4, self.tab5, self.tab6 = QGroupBox(), QGroupBox(), QGroupBox()
        for a, b in ((self.tab1, 'Basics'), (self.tab2, 'General Options'),
            (self.tab3, 'VM Package Manager'), (self.tab4, 'VM Provisioning'),
            (self.tab5, 'VM Desktop GUI'), (self.tab6, 'Run')):
            a.setTitle(b)
            a.setToolTip(b)
            self.mainwidget.addTab(a, QIcon.fromTheme("virtualbox"), b)

        QPushButton(QIcon.fromTheme("help-about"), 'About', self.dock
        ).clicked.connect(lambda: QMessageBox.information(self.dock, __doc__,
        HELPMSG))

        self.vmname = QLineEdit(self.get_name())
        self.vmname.setPlaceholderText('type_your_VM_name_here_without_spaces')
        self.vmname.setToolTip('Type VM name, no spaces or special characters')
        self.target = QLabel('<b>Vagrant Target Folder: ' +
                             path.join(BASE, self.vmname.text()))
        self.vmname.textChanged.connect(lambda: self.target.setText(
            '<b>Vagrant Target Folder: ' + path.join(BASE, self.vmname.text())))
        self.btn1 = QPushButton(QIcon.fromTheme("face-smile-big"), 'Suggestion')
        self.btn1.setToolTip('Suggest me a Random VM name !')
        self.btn1.clicked.connect(lambda: self.vmname.setText(self.get_name()))
        self.vmcode, self.vmarch = QComboBox(), QComboBox()
        self.vmcode.addItems(['saucy', 'raring', 'quantal', 'precise'])
        self.vmarch.addItems(['x86_64 (amd64) 64-Bits', 'x86 (i386) 32-Bits'])
        vboxg1 = QVBoxLayout(self.tab1)
        for each_widget in (QLabel('<b>Name for VM'), self.vmname, self.btn1,
            QLabel('<b>Choose Ubuntu Codename for the VM:</b>'), self.vmcode,
            QLabel('<b>Choose Architecture for VM:'), self.vmarch, self.target):
            vboxg1.addWidget(each_widget)

        self.chrt = QCheckBox('LOW CPU priority for Backend Process')
        self.chttps = QComboBox()
        self.chttps.addItems(['https', 'http'])
        try:
            self.vinfo1 = QLabel('''<b> Vagrant Backend Version: </b> {},
                <b> VirtualBox Backend Version: </b> {}. '''.format(
                getoutput('vagrant --version', shell=1).strip(),
                getoutput('vboxmanage --version', shell=1).strip()))
        except:
            self.vinfo1 = QLabel('<b>Warning: Failed to query Vagrant Backend!')
        self.qckb1 = QCheckBox(' Open target directory later')
        self.qckb1.setToolTip('Open the target directory when finished')
        self.qckb2 = QCheckBox(' Save a LOG file to target later')
        self.qckb2.setToolTip('Save a read-only .LOG file to target')
        self.qckb3 = QCheckBox(' NO run Headless Mode, use a Window')
        self.qckb3.setToolTip('Show the VM on a Window GUI instead of Headless')
        self.cpu, self.ram = QSpinBox(), QSpinBox()
        self.cpu.setRange(25, 99)
        self.cpu.setValue(99)
        self.ram.setRange(512, 4096)
        self.ram.setValue(1024)
        vboxg2 = QVBoxLayout(self.tab2)
        for each_widget in (self.qckb1, self.qckb2, self.qckb3, self.chrt,
            QLabel('<b>Max CPU Limit for VM:</b>'), self.cpu,
            QLabel('<b>Max RAM Limit for VM:</b>'), self.ram,
            QLabel('<b>Download Protocol Type:</b>'), self.chttps, self.vinfo1):
            vboxg2.addWidget(each_widget)

        self.qckb10 = QCheckBox('Run apt-get update on the created VM')
        self.qckb11 = QCheckBox('Run apt-get dist-upgrade on the created VM')
        self.qckb12 = QCheckBox('Run apt-get check on the created VM')
        self.qckb12 = QCheckBox('Run apt-get clean on the created VM')
        self.qckb13 = QCheckBox('Run apt-get autoremove on the created VM')
        self.qckb14 = QCheckBox('Try to Fix Broken packages if any on the VM')
        self.aptproxy, self.portredirect = QLineEdit(), QLineEdit('8000, 9000')
        self.aptproxy.setPlaceholderText(' user:password@proxyaddress:port ')
        vboxg3 = QVBoxLayout(self.tab3)
        for each_widget in (self.qckb10, self.qckb11, self.qckb12, self.qckb13,
            self.qckb14,
            QLabel('<b>Network Proxy for apt-get on the VM'), self.aptproxy,
            QLabel('<b>Network Port Redirects for the VM'), self.portredirect):
            vboxg3.addWidget(each_widget)

        self.aptpkg = QTextEdit('build-essential git python-pip vim mc wget')
        self.aptppa, self.pippkg = QLineEdit(), QTextEdit('virtualenv yolk')
        self.aptppa.setPlaceholderText(' ppa:ninja-ide-developers/daily ')
        self.requirements = QLineEdit()
        self.requirements.setPlaceholderText(' /full/path/to/requirements.txt ')
        self.requirements.setCompleter(self.completer)
        vboxg4 = QVBoxLayout(self.tab4)
        for each_widget in (QLabel('<b>Custom APT Ubuntu package'), self.aptpkg,
            QLabel('<b>Custom APT Ubuntu PPA:</b>      '), self.aptppa,
            QLabel('<b>Custom PIP Python packages:</b> '), self.pippkg,
            QLabel('<b>Custom PIP Python requirements: '), self.requirements):
            vboxg4.addWidget(each_widget)

        self.buttonGroup = QButtonGroup()
        self.buttonGroup.buttonClicked[QAbstractButton].connect(self.get_de_pkg)
        vboxg5 = QVBoxLayout(self.tab5)
        for i, d in enumerate(('Ubuntu Unity', 'KDE Plasma', 'LXDE', 'XFCE')):
            button = QPushButton(d)
            button.setCheckable(True)
            button.setMinimumSize(75, 50)
            button.setToolTip(d)
            vboxg5.addWidget(button)
            self.buttonGroup.addButton(button)

        self.output = QTextEdit('''
        We have persistent objects, they are called files.  -Ken Thompson. ''')
        self.runbtn = QPushButton(QIcon.fromTheme("media-playback-start"),
            'Start Vagrant Instrumentation Now !')
        self.runbtn.setMinimumSize(75, 50)
        self.runbtn.clicked.connect(self.build)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.runbtn.setGraphicsEffect(glow)
        self.stopbt = QPushButton(QIcon.fromTheme("media-playback-stop"),
            'Stop Vagrant')
        self.stopbt.clicked.connect(lambda: self.process.stop())
        self.killbt = QPushButton(QIcon.fromTheme("application-exit"),
            'Force Kill Vagrant')
        self.killbt.clicked.connect(lambda: self.process.kill())
        vboxg6 = QVBoxLayout(self.tab6)
        for each_widget in (QLabel('<b>Multiprocess Output Logs'), self.output,
            self.runbtn, self.stopbt, self.killbt):
            vboxg6.addWidget(each_widget)

        [a.setChecked(True) for a in (self.qckb1, self.qckb2, self.qckb3,
            self.qckb10, self.qckb11, self.qckb12, self.qckb13, self.qckb14,
            self.chrt)]
        self.mainwidget.setCurrentIndex(5)
Ejemplo n.º 12
0
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)

        # directory auto completer
        self.completer = QCompleter(self)
        self.dirs = QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)

        # tab widget
        self.mainwidget = QTabWidget()
        self.mainwidget.setToolTip(__doc__)
        self.mainwidget.setTabShape(QTabWidget.Triangular)
        self.mainwidget.setMovable(True)
        self.mainwidget.setTabsClosable(True)
        self.mainwidget.tabCloseRequested.connect(lambda:
            self.mainwidget.setTabPosition(1)
            if self.mainwidget.tabPosition() == 0
            else self.mainwidget.setTabPosition(0))
        self.dock1 = QDockWidget()
        self.dock2 = QDockWidget()
        for indx, a in enumerate((self.dock1, self.dock2)):
            a.setWindowModality(Qt.NonModal)
            a.setWindowOpacity(0.9)
            a.setWindowTitle('Semantic Files' if indx == 0 else 'Simple Query')
            a.setStyleSheet('QDockWidget::title{text-align:center;}')
            self.mainwidget.addTab(a, QIcon.fromTheme("nepomuk"),
                             'Semantic Files' if indx == 0 else 'Simple Query')

        QPushButton(QIcon.fromTheme("help-about"), 'Help About', self.dock1
          ).clicked.connect(lambda:
          QMessageBox.information(self.dock1, __doc__, HELPMSG))

        # Group of widgets for each tab
        self.group1 = QGroupBox()
        self.filename = QLineEdit()
        self.filename.setPlaceholderText('/full/path/to/one_file.py')
        self.filename.setCompleter(self.completer)
        self.filebttn = QPushButton(QIcon.fromTheme("folder-open"), 'Open File')
        self.filebttn.clicked.connect(lambda: self.filename.setText(str(
            QFileDialog.getOpenFileName(self.mainwidget,
            " Please, open a .py file to add Semantics ", path.expanduser("~"),
            ';;'.join(['(*.{}) {}'.format(e, e.upper()) for e in ['*', 'py']])))
        ))

        self.group1a = QGroupBox()
        self.filetag = QLineEdit()
        self.filetag.setPlaceholderText('Type a short Tag for the choosen File')
        self.filelbl = QLineEdit()
        self.filelbl.setPlaceholderText('Type a descriptive Label for the Tag')
        self.filedsc = QLineEdit()
        self.filedsc.setPlaceholderText('Type a large and detailed Description')
        self.filerat = KRatingWidget()
        self.filerat.setToolTip('Set a File Rating')
        vboxg1a = QHBoxLayout(self.group1a)
        for each_widget in (QLabel('<b>File Tag'), self.filetag,
            QLabel('<b>Tag Label'), self.filelbl,
            QLabel('<b>Description'), self.filedsc,
            QLabel('<b>File Rating'), self.filerat):
            vboxg1a.addWidget(each_widget)

        self.nepobtn = QPushButton(QIcon.fromTheme("nepomuk"), 'Add Semantics')
        self.nepobtn.setMinimumSize(self.nepobtn.size().width(), 50)
        self.nepobtn.clicked.connect(lambda: self.nepomuk_set(
            str(self.filename.text()).strip(), str(self.filetag.text()).strip(),
            str(self.filelbl.text()).strip(), str(self.filedsc.text()).strip()))
        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (
            QLabel('<b>Choose a File'), self.filename, self.filebttn,
            self.group1a, self.nepobtn):
            vboxg1.addWidget(each_widget)

        self.group2 = QGroupBox()
        self.group2.setTitle('Sorry!, this Tab is not Ready yet...')
        QLabel('<b style="color:red;"><i>Not Ready Yet!', self.dock2)
        self.search = QLineEdit()
        self.search.setPlaceholderText('Type to Query...')
        self.srcbtn = QPushButton(QIcon.fromTheme("folder-open"), 'Query')
        self.result = QTextEdit()
        self.srcbtn.clicked.connect(lambda:
            self.nepomuk_get(str(self.search.text()).strip().lower()))
        vboxg2 = QVBoxLayout(self.group2)
        for each_widget in (
            QLabel('<b>Type for a Semantic Query'), self.search, self.srcbtn,
            QLabel('<b>Semantic Query Results'), self.result):
            vboxg2.addWidget(each_widget)

        # pack the group of widgets on the gui
        self.dock1.setWidget(self.group1)
        self.dock2.setWidget(self.group2)

        # pack the plugin on ninja-ide gui
        self.locator.get_service('misc').add_widget(
                        self.mainwidget, QIcon.fromTheme("nepomuk"), __doc__)

        def must_have_tooltip(widget_list):
            ' widget tuple passed as argument should have tooltips '
            for each_widget in widget_list:
                try:
                    each_widget.setToolTip(each_widget.text())
                except:
                    each_widget.setToolTip(each_widget.currentText())
                finally:
                    each_widget.setCursor(QCursor(Qt.PointingHandCursor))

        def must_glow(widget_list):
            ' apply an glow effect to the widget '
            for glow, each_widget in enumerate(widget_list):
                try:
                    if each_widget.graphicsEffect() is None:
                        glow = QGraphicsDropShadowEffect(self)
                        glow.setOffset(0)
                        glow.setBlurRadius(99)
                        glow.setColor(QColor(99, 255, 255))
                        each_widget.setGraphicsEffect(glow)
                        # glow.setEnabled(False)
                        try:
                            each_widget.clicked.connect(lambda:
                            each_widget.graphicsEffect().setEnabled(True)
                            if each_widget.graphicsEffect().isEnabled() is False
                            else each_widget.graphicsEffect().setEnabled(False))
                        except:
                            each_widget.sliderPressed.connect(lambda:
                            each_widget.graphicsEffect().setEnabled(True)
                            if each_widget.graphicsEffect().isEnabled() is False
                            else each_widget.graphicsEffect().setEnabled(False))
                except:
                    pass

        must_have_tooltip((self.filebttn, self.nepobtn, self.srcbtn, ))
        must_glow((self.nepobtn, self.srcbtn, ))
Ejemplo n.º 13
0
class PylouApplet(Applet):

    """Main Applet containing the UI of Pylou."""

    def __init__(self, parent, args=None):
        """Init class."""
        Applet.__init__(self, parent)

    def init(self):
        """Start the Applet."""
        self._widget = None
        self.setHasConfigurationInterface(True)
        self.setAspectRatioMode(Plasma.IgnoreAspectRatio)
        self.configurations = self.config()
        self._widget = PylouWidget(self)
        self._widget.init()
        self.setGraphicsWidget(self._widget)
        self.applet.setPassivePopup(True)
        self.setPopupIcon(QIcon.fromTheme("edit-find"))
        # for some odd reason this has to be called twice?
        self.setGraphicsWidget(self._widget)
        self.prepareConfigDialog()

    def update_db(self):
        """Update the DB."""
        return call("kdesudo --noignorebutton -c updatedb", shell=True)

    def prepareConfigDialog(self):
        """Prepare the Configuration Dialog."""
        self.bcolor, self.dialog = QColor(), KDialog()
        self.dialog.setWindowTitle(__package__ + "Settings")
        self.layBox = QGridLayout(self.dialog.mainWidget())
        self.title = KTitleWidget(self.dialog)
        self.title.setText(__doc__ + " !")
        self.title.setAutoHideTimeout(3000)
        self.FontButton = KFontRequester(self.dialog)
        self.tfont = QFont(QVariant(self.configurations.readEntry("TextFont",
                           QVariant(QFont()))))
        self.FontButton.setFont(self.tfont)
        self.ColorButton = KColorButton(self.dialog)
        self.tcolor = QColor(self.configurations.readEntry("TextColor",
                             QColor("#000").name()))
        self.ColorButton.setColor(self.tcolor)
        self.BColorButton = KColorButton(self.dialog)
        # button to update the DB via sudo updatedb

        self.UpdateDB = KPushButton("Update Database", self.dialog,
                                    clicked=lambda: self.update_db())
        self.UpdateDB.setToolTip("Database is Updated every Reboot and Daily!")
        self.Histor = KPushButton("Delete my History", self.dialog,
                                  clicked=delete_my_history)
        self.Histor.setToolTip("History is Deleted every Reboot !")
        # list of banned words separated by spaces
        self.banned = KTextEdit(self.dialog)
        self.banned.setPlainText(self.configurations.readEntry(
            "Banned", "sex p**n drugs suicide decapitate religion").toString())
        # set the colors
        cg = KConfig("kdeglobals")
        color = cg.group("Colors:View").readEntry(
            "BackgroundAlternate").split(",")
        self.bcolor = QColor(int(color[0]), int(color[1]), int(color[2]))
        self.BColorButton.setColor(self.bcolor)
        self.history_file_path_field = KLineEdit(HISTORY_FILE_PATH)
        self.history_file_path_field.setDisabled(True)
        self.python_file_path_field = KLineEdit(__file__)
        self.python_file_path_field.setDisabled(True)
        self.kill_baloo = QCheckBox("Disable Baloo")
        self.kill_baloo.setToolTip("Enable/Disable Desktop Search Indexing")
        self.kill_baloo.stateChanged.connect(lambda: call(
            DISABLE_BALOO_CMD.format(str(
                not self.kill_baloo.isChecked()).lower()), shell=True))
        self.kill_baloo.stateChanged.connect(lambda: QMessageBox.information(
            self.dialog, __doc__, """
            <b>Indexing Disabled, Baloo is Dead !
            """ if self.kill_baloo.isChecked() else """
            <b>Indexing Enabled, Baloo is Running !"""))
        self.updatez = KPushButton("Check for Updates", self.dialog,
                                   clicked=lambda: self.check_for_updates())
        self.updatez.setToolTip("Check for Pylou updates from the internet")
        self.home_sweet_home = QCheckBox("Only Search Home")
        self.home_sweet_home.setToolTip("Only Search on my Home folders")
        self.home_sweet_home.setChecked(
            bool(self.configurations.readEntry("Home", True)))
        # pack all widgets
        self.layBox.addWidget(self.title, 0, 1)
        self.layBox.addWidget(QLabel("Font"), 1, 0)
        self.layBox.addWidget(self.FontButton, 1, 1)
        self.layBox.addWidget(QLabel("Text Color"), 2, 0)
        self.layBox.addWidget(self.ColorButton, 2, 1)
        self.layBox.addWidget(QLabel("Alternate Color"), 3, 0)
        self.layBox.addWidget(self.BColorButton, 3, 1)
        self.layBox.addWidget(QLabel(), 4, 0)
        self.layBox.addWidget(QLabel("Mainteniance"), 5, 0)
        self.layBox.addWidget(self.UpdateDB, 5, 1)
        self.layBox.addWidget(QLabel("Privacy"), 6, 0)
        self.layBox.addWidget(self.Histor, 6, 1)
        self.layBox.addWidget(QLabel("History file"), 7, 0)
        self.layBox.addWidget(self.history_file_path_field, 7, 1)
        self.layBox.addWidget(QLabel(__package__ + "file"), 8, 0)
        self.layBox.addWidget(self.python_file_path_field, 8, 1)
        self.layBox.addWidget(QLabel("Banned Words"), 9, 0)
        self.layBox.addWidget(self.banned, 9, 1)
        self.layBox.addWidget(QLabel("SelfUpdating"), 10, 0)
        self.layBox.addWidget(self.updatez, 10, 1)
        self.layBox.addWidget(QLabel("<b>Disable Indexing"), 12, 0)
        self.layBox.addWidget(self.kill_baloo, 12, 1)
        self.layBox.addWidget(QLabel("Search Paths"), 13, 0)
        self.layBox.addWidget(self.home_sweet_home, 13, 1)
        # button box on the bottom
        self.dialog.setButtons(KDialog.ButtonCodes(
            KDialog.ButtonCode(KDialog.Ok | KDialog.Cancel | KDialog.Apply)))
        # connect
        self.dialog.applyClicked.connect(self.configAccepted)
        self.dialog.okClicked.connect(self.configAccepted)

    @pyqtSignature("configAccepted()")
    def configAccepted(self):
        """Save configuration settings."""
        self.tcolor = self.ColorButton.color()
        self.bcolor = self.BColorButton.color()
        self._widget.treeview.nativeWidget().setFont(self.tfont)
        self._widget.treeview.nativeWidget().setStyleSheet(
            "color:{};alternate-background-color:{}".format(
                self.tcolor.name(), self.bcolor.name()))
        self.configurations.writeEntry("TextColor", self.tcolor.name())
        self.configurations.writeEntry("AlternateBColor", self.bcolor.name())
        self.configurations.writeEntry("TextFont", QVariant(self.tfont))
        self.configurations.writeEntry("Banned", self.banned.toPlainText())
        self.configurations.writeEntry("Home",
                                       self.home_sweet_home.isChecked())

    def showConfigurationInterface(self):
        """Show configuration dialog."""
        self.dialog.show()
        self.dialog.raise_()

    def check_for_updates(self):
        """Method to check for updates from Git repo versus this version."""
        this_version = str(open(__file__).read())
        last_version = str(urlopen(__source__).read())
        if this_version != last_version:
            m = "Theres new Version available!<br>Download update from the web"
        else:
            m = "No new updates!<br>You have the lastest version of this app!."
        return QMessageBox.information(None, __doc__.title(), "<b>" + m)
Ejemplo n.º 14
0
    def __init__(self):
        KXmlGuiWindow.__init__(self)

        textArea = KTextEdit()
        self.setCentralWidget(textArea)
        self.setupGUI()
Ejemplo n.º 15
0
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(533, 596)
        MainWindow.setDockNestingEnabled(True)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout_2 = QtGui.QGridLayout(self.centralwidget)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.label = QtGui.QLabel(self.centralwidget)
        self.label.setObjectName("label")
        self.gridLayout_2.addWidget(self.label, 0, 0, 1, 1)
        self.branchComboBox = QtGui.QComboBox(self.centralwidget)
        self.branchComboBox.setObjectName("branchComboBox")
        self.gridLayout_2.addWidget(self.branchComboBox, 0, 1, 1, 1)
        spacerItem = QtGui.QSpacerItem(222, 23, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
        self.gridLayout_2.addItem(spacerItem, 0, 2, 1, 1)
        self.diffTextEdit = KTextEdit(self.centralwidget)
        self.diffTextEdit.setObjectName("diffTextEdit")
        self.gridLayout_2.addWidget(self.diffTextEdit, 1, 0, 1, 3)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 533, 24))
        self.menubar.setObjectName("menubar")
        self.menuFile = QtGui.QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")
        self.menu_Repository = QtGui.QMenu(self.menubar)
        self.menu_Repository.setObjectName("menu_Repository")
        MainWindow.setMenuBar(self.menubar)
        self.unstagedFilesDockWidget = QtGui.QDockWidget(MainWindow)
        self.unstagedFilesDockWidget.setObjectName("unstagedFilesDockWidget")
        self.dockWidgetContents = QtGui.QWidget()
        self.dockWidgetContents.setObjectName("dockWidgetContents")
        self.gridLayout = QtGui.QGridLayout(self.dockWidgetContents)
        self.gridLayout.setObjectName("gridLayout")
        self.unstagedChangesView = QtGui.QTreeView(self.dockWidgetContents)
        self.unstagedChangesView.setObjectName("unstagedChangesView")
        self.gridLayout.addWidget(self.unstagedChangesView, 0, 0, 1, 1)
        self.unstagedFilesDockWidget.setWidget(self.dockWidgetContents)
        MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(1), self.unstagedFilesDockWidget)
        self.dockWidget_3 = QtGui.QDockWidget(MainWindow)
        self.dockWidget_3.setObjectName("dockWidget_3")
        self.dockWidgetContents_4 = QtGui.QWidget()
        self.dockWidgetContents_4.setObjectName("dockWidgetContents_4")
        self.gridLayout_3 = QtGui.QGridLayout(self.dockWidgetContents_4)
        self.gridLayout_3.setObjectName("gridLayout_3")
        self.stagedChangesView = QtGui.QListView(self.dockWidgetContents_4)
        self.stagedChangesView.setObjectName("stagedChangesView")
        self.gridLayout_3.addWidget(self.stagedChangesView, 0, 0, 1, 1)
        self.dockWidget_3.setWidget(self.dockWidgetContents_4)
        MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(1), self.dockWidget_3)
        self.dockWidget_5 = QtGui.QDockWidget(MainWindow)
        self.dockWidget_5.setObjectName("dockWidget_5")
        self.dockWidgetContents_6 = QtGui.QWidget()
        self.dockWidgetContents_6.setObjectName("dockWidgetContents_6")
        self.gridLayout_4 = QtGui.QGridLayout(self.dockWidgetContents_6)
        self.gridLayout_4.setObjectName("gridLayout_4")
        self.historyTableView = QtGui.QTableView(self.dockWidgetContents_6)
        self.historyTableView.setAlternatingRowColors(True)
        self.historyTableView.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        self.historyTableView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
        self.historyTableView.setShowGrid(False)
        self.historyTableView.setObjectName("historyTableView")
        self.gridLayout_4.addWidget(self.historyTableView, 0, 0, 1, 1)
        self.dockWidget_5.setWidget(self.dockWidgetContents_6)
        MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(8), self.dockWidget_5)
        self.action_OpenRepository = QtGui.QAction(MainWindow)
        self.action_OpenRepository.setObjectName("action_OpenRepository")
        self.action_Quit = QtGui.QAction(MainWindow)
        self.action_Quit.setObjectName("action_Quit")
        self.action_ReloadRepository = QtGui.QAction(MainWindow)
        self.action_ReloadRepository.setObjectName("action_ReloadRepository")
        self.menuFile.addAction(self.action_Quit)
        self.menu_Repository.addAction(self.action_OpenRepository)
        self.menu_Repository.addAction(self.action_ReloadRepository)
        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menu_Repository.menuAction())
        self.label.setBuddy(self.branchComboBox)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
class MyMainWindow(QMainWindow):
    ' Main Window '
    def __init__(self, AUTO):
        ' Initialize QWidget inside MyMainWindow '
        super(MyMainWindow, self).__init__()
        QWidget.__init__(self)
        self.auto = AUTO
        self.statusBar().showMessage('               {}'.format(__doc__))
        self.setStyleSheet('QStatusBar{color:grey;}')
        self.setWindowTitle(__doc__)
        self.setWindowIcon(QIcon.fromTheme("face-monkey"))
        self.setFont(QFont('Ubuntu Light', 10))
        self.setMaximumSize(QDesktopWidget().screenGeometry().width(),
                            QDesktopWidget().screenGeometry().height())

        self.base = path.abspath(path.join(getcwd(), str(datetime.now().year)))

        # directory auto completer
        self.completer = QCompleter(self)
        self.dirs = QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)

        # process
        self.process1 = None
        self.process2 = None
        self.cmd1 = 'nice -n {n} arecord{v} -f {f} -c {c} -r {b} -t raw'
        self.cmd2 = 'oggenc - -r -C {c} -R {b} -q {q} {d}{t}{a} -o {o}'
        self.process3 = QProcess(self)
        #self.process3.finished.connect(self.on_process3_finished)
        #self.process3.error.connect(self.on_process3_error)

        self.cmd3 = ('nice -n 20 ' +
          'sox "{o}" -n spectrogram -x {x} -y {y} -z 99 -t "{o}" -o "{o}.png"')
        self.actual_file = ''

        # re starting timers, one stops, one starts
        self.timerFirst = QTimer(self)
        self.timerFirst.timeout.connect(self.end)
        self.timerSecond = QTimer(self)
        self.timerSecond.timeout.connect(self.run)

        # Proxy support, by reading http_proxy os env variable
        proxy_url = QUrl(environ.get('http_proxy', ''))
        QNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.HttpProxy
            if str(proxy_url.scheme()).startswith('http')
            else QNetworkProxy.Socks5Proxy, proxy_url.host(), proxy_url.port(),
                 proxy_url.userName(), proxy_url.password())) \
            if 'http_proxy' in environ else None
        print((' INFO: Proxy Auto-Config as ' + str(proxy_url)))

        # basic widgets layouts and set up
        self.mainwidget = QTabWidget()
        self.mainwidget.setToolTip(__doc__)
        self.mainwidget.setMovable(True)
        self.mainwidget.setTabShape(QTabWidget.Triangular)
        self.mainwidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.mainwidget.setStyleSheet('QTabBar{color:white;font-weight:bold;}')
        self.mainwidget.setTabBar(TabBar(self))
        self.mainwidget.setTabsClosable(False)
        self.setCentralWidget(self.mainwidget)
        self.dock1 = QDockWidget()
        self.dock2 = QDockWidget()
        self.dock3 = QDockWidget()
        self.dock4 = QDockWidget()
        self.dock5 = QDockWidget()
        for a in (self.dock1, self.dock2, self.dock3, self.dock4, self.dock5):
            a.setWindowModality(Qt.NonModal)
            # a.setWindowOpacity(0.9)
            a.setWindowTitle(__doc__
                             if a.windowTitle() == '' else a.windowTitle())
            a.setStyleSheet('QDockWidget::title{text-align:center;}')
            self.mainwidget.addTab(a, QIcon.fromTheme("face-smile"),
                                   'Double Click Me')

        # Paleta de colores para pintar transparente
        self.palette().setBrush(QPalette.Base, Qt.transparent)
        self.setPalette(self.palette())
        self.setAttribute(Qt.WA_OpaquePaintEvent, False)

        # toolbar and basic actions
        self.toolbar = QToolBar(self)
        self.toolbar.setIconSize(QSize(24, 24))
        # spacer widget for left
        self.left_spacer = QWidget(self)
        self.left_spacer.setSizePolicy(QSizePolicy.Expanding,
                                       QSizePolicy.Expanding)
        # spacer widget for right
        self.right_spacer = QWidget(self)
        self.right_spacer.setSizePolicy(QSizePolicy.Expanding,
                                        QSizePolicy.Expanding)
        qaqq = QAction(QIcon.fromTheme("application-exit"), 'Quit', self)
        qaqq.setShortcut('Ctrl+Q')
        qaqq.triggered.connect(exit)
        qamin = QAction(QIcon.fromTheme("go-down"), 'Minimize', self)
        qamin.triggered.connect(lambda: self.showMinimized())
        qamax = QAction(QIcon.fromTheme("go-up"), 'Maximize', self)
        qanor = QAction(QIcon.fromTheme("view-fullscreen"),
                        'AutoCenter AutoResize', self)
        qanor.triggered.connect(self.center)
        qatim = QAction(QIcon.fromTheme("mail-signed-verified"),
                        'View Date and Time', self)
        qatim.triggered.connect(self.timedate)
        qabug = QAction(QIcon.fromTheme("help-about"), 'Report a Problem', self)
        qabug.triggered.connect(lambda: qabug.setDisabled(True) if not call(
            'xdg-open mailto:' + '*****@*****.**'.decode('rot13'),
            shell=True) else ' ERROR ')
        qamax.triggered.connect(lambda: self.showMaximized())
        qaqt = QAction(QIcon.fromTheme("help-about"), 'About Qt', self)
        qaqt.triggered.connect(lambda: QMessageBox.aboutQt(self))
        qakde = QAction(QIcon.fromTheme("help-about"), 'About KDE', self)
        if KDE:
            qakde.triggered.connect(KHelpMenu(self, "", False).aboutKDE)
        qaslf = QAction(QIcon.fromTheme("help-about"), 'About Self', self)
        if KDE:
            qaslf.triggered.connect(
                                KAboutApplicationDialog(aboutData, self).exec_)
        else:
            qaslf.triggered.connect(lambda: QMessageBox.about(self.mainwidget,
            __doc__, ''.join((__doc__, linesep, 'version ', __version__, ', (',
            __license__, '), by ', __author__, ', ( ', __email__, ' )', linesep
            ))))
        qafnt = QAction(QIcon.fromTheme("tools-check-spelling"),
                        'Set GUI Font', self)
        if KDE:
            font = QFont()
            qafnt.triggered.connect(lambda:
            self.setStyleSheet(''.join((
                '*{font-family:', str(font.toString()), '}'))
                if KFontDialog.getFont(font)[0] == QDialog.Accepted else ''))
        else:
            qafnt.triggered.connect(lambda:
                self.setStyleSheet(''.join(('*{font-family:',
                            str(QFontDialog.getFont()[0].toString()), '}'))))
        qasrc = QAction(QIcon.fromTheme("applications-development"),
                        'View Source Code', self)
        qasrc.triggered.connect(lambda:
                            call('xdg-open {}'.format(__file__), shell=True))
        qakb = QAction(QIcon.fromTheme("input-keyboard"),
                       'Keyboard Shortcuts', self)
        qakb.triggered.connect(lambda: QMessageBox.information(self.mainwidget,
                               'Keyboard Shortcuts', ' Ctrl+Q = Quit '))
        qapic = QAction(QIcon.fromTheme("camera-photo"),
                        'Take a Screenshot', self)
        qapic.triggered.connect(lambda: QPixmap.grabWindow(
            QApplication.desktop().winId()).save(QFileDialog.getSaveFileName(
            self.mainwidget, " Save Screenshot As ...", path.expanduser("~"),
            ';;(*.png) PNG', 'png')))
        qatb = QAction(QIcon.fromTheme("go-top"), 'Toggle ToolBar', self)
        qatb.triggered.connect(lambda: self.toolbar.hide()
                if self.toolbar.isVisible() is True else self.toolbar.show())
        qati = QAction(QIcon.fromTheme("zoom-in"),
                       'Switch ToolBar Icon Size', self)
        qati.triggered.connect(lambda:
            self.toolbar.setIconSize(self.toolbar.iconSize() * 4)
            if self.toolbar.iconSize().width() * 4 == 24
            else self.toolbar.setIconSize(self.toolbar.iconSize() / 4))
        qasb = QAction(QIcon.fromTheme("preferences-other"),
                       'Toggle Tabs Bar', self)
        qasb.triggered.connect(lambda: self.mainwidget.tabBar().hide()
                               if self.mainwidget.tabBar().isVisible() is True
                               else self.mainwidget.tabBar().show())
        qadoc = QAction(QIcon.fromTheme("help-browser"), 'On-line Docs', self)
        qadoc.triggered.connect(lambda: open_new_tab(str(__url__).strip()))
        qapy = QAction(QIcon.fromTheme("help-about"), 'About Python', self)
        qapy.triggered.connect(lambda: open_new_tab('http://python.org/about'))
        qali = QAction(QIcon.fromTheme("help-browser"), 'Read Licence', self)
        qali.triggered.connect(lambda: open_new_tab(__full_licence__))
        qacol = QAction(QIcon.fromTheme("preferences-system"), 'Set GUI Colors',
                        self)
        if KDE:
            color = QColor()
            qacol.triggered.connect(lambda:
                self.setStyleSheet(''.join(('* { background-color: ',
                                            str(color.name()), '}')))
                if KColorDialog.getColor(color, self) else '')
        else:
            qacol.triggered.connect(lambda: self.setStyleSheet(''.join((
                ' * { background-color: ', str(QColorDialog.getColor().name()),
                ' } '))))
        qatit = QAction(QIcon.fromTheme("preferences-system"),
                        'Set the App Window Title', self)
        qatit.triggered.connect(self.seTitle)
        self.toolbar.addWidget(self.left_spacer)
        self.toolbar.addSeparator()
        self.toolbar.addActions((qaqq, qamin, qanor, qamax, qasrc, qakb, qacol,
            qatim, qatb, qafnt, qati, qasb, qatit, qapic, qadoc, qali, qaslf,
            qaqt, qakde, qapy, qabug))
        self.addToolBar(Qt.TopToolBarArea, self.toolbar)
        self.toolbar.addSeparator()
        self.toolbar.addWidget(self.right_spacer)
        # define the menu
        menu = self.menuBar()
        # File menu items
        menu.addMenu('&File').addActions((qaqq, ))
        menu.addMenu('&Window').addActions((qamax, qanor, qamin))
        # Settings menu
        menu.addMenu('&Settings').addActions((qasrc, qacol, qafnt, qatim,
                                              qatb, qati, qasb, qapic))
        # Help menu items
        menu.addMenu('&Help').addActions((qadoc, qakb, qabug, qali,
                                          qaqt, qakde, qapy, qaslf))
        # Tray Icon
        tray = QSystemTrayIcon(QIcon.fromTheme("face-devilish"), self)
        tray.setToolTip(__doc__)
        traymenu = QMenu()
        traymenu.addActions((qamax, qanor, qamin, qaqq))
        tray.setContextMenu(traymenu)
        tray.show()

        def contextMenuRequested(point):
            ' quick and dirty custom context menu '
            menu = QMenu()
            menu.addActions((qaqq, qamin, qanor, qamax, qasrc, qakb, qacol,
                qafnt, qati, qasb, qatb, qatim, qatit, qapic, qadoc, qali,
                qaslf, qaqt, qakde, qapy, qabug))
            menu.exec_(self.mapToGlobal(point))
        self.mainwidget.customContextMenuRequested.connect(contextMenuRequested)

        def must_be_checked(widget_list):
            ' widget tuple passed as argument should be checked as ON '
            for each_widget in widget_list:
                try:
                    each_widget.setChecked(True)
                except:
                    pass

        def must_have_tooltip(widget_list):
            ' widget tuple passed as argument should have tooltips '
            for each_widget in widget_list:
                try:
                    each_widget.setToolTip(each_widget.text())
                except:
                    each_widget.setToolTip(each_widget.currentText())
                finally:
                    each_widget.setCursor(QCursor(Qt.PointingHandCursor))

        def must_autofillbackground(widget_list):
            ' widget tuple passed as argument should have filled background '
            for each_widget in widget_list:
                try:
                    each_widget.setAutoFillBackground(True)
                except:
                    pass

        def must_glow(widget_list):
            ' apply an glow effect to the widget '
            for glow, each_widget in enumerate(widget_list):
                try:
                    if each_widget.graphicsEffect() is None:
                        glow = QGraphicsDropShadowEffect(self)
                        glow.setOffset(0)
                        glow.setBlurRadius(99)
                        glow.setColor(QColor(99, 255, 255))
                        each_widget.setGraphicsEffect(glow)
                        # glow.setEnabled(False)
                        try:
                            each_widget.clicked.connect(lambda:
                            each_widget.graphicsEffect().setEnabled(True)
                            if each_widget.graphicsEffect().isEnabled() is False
                            else each_widget.graphicsEffect().setEnabled(False))
                        except:
                            each_widget.sliderPressed.connect(lambda:
                            each_widget.graphicsEffect().setEnabled(True)
                            if each_widget.graphicsEffect().isEnabled() is False
                            else each_widget.graphicsEffect().setEnabled(False))
                except:
                    pass

        #######################################################################

        # dock 1
        QLabel('<h1 style="color:white;"> Record !</h1>', self.dock1).resize(
               self.dock3.size().width() / 4, 25)
        self.group1 = QGroupBox()
        self.group1.setTitle(__doc__)

        self.spec = QPushButton(self)
        self.spec.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.spec.setMinimumSize(self.spec.size().width(), 250)
        self.spec.setFlat(True)
        self.spec.clicked.connect(self.spectro)

        self.clock = QLCDNumber()
        self.clock.setSegmentStyle(QLCDNumber.Flat)
        self.clock.setMinimumSize(self.clock.size().width(), 50)
        self.clock.setNumDigits(25)
        self.timer1 = QTimer(self)
        self.timer1.timeout.connect(lambda: self.clock.display(
            datetime.now().strftime("%d-%m-%Y %H:%M:%S %p")))
        self.timer1.start(1000)
        self.clock.setToolTip(datetime.now().strftime("%c %x"))
        self.clock.setCursor(QCursor(Qt.CrossCursor))

        self.diskBar = QProgressBar()
        self.diskBar.setMinimum(0)
        self.diskBar.setMaximum(statvfs(HOME).f_blocks *
            statvfs(HOME).f_frsize / 1024 / 1024 / 1024)
        self.diskBar.setValue(statvfs(HOME).f_bfree *
            statvfs(HOME).f_frsize / 1024 / 1024 / 1024)
        self.diskBar.setToolTip(str(statvfs(HOME).f_bfree *
            statvfs(HOME).f_frsize / 1024 / 1024 / 1024) + ' Gigabytes free')

        self.feedback = QPlainTextEdit(''.join(('<center><h3>', __doc__,
            ', version', __version__, __license__, ' <br> by ', __author__,
            ' <i>(Dev)</i>, Radio Comunitaria FM Reconquista <i>(Q.A.)</i><br>',
            'FMReconquista.org.ar & GitHub.com/JuanCarlosPaco/Cinta-Testigo')))

        self.rec = QPushButton(QIcon.fromTheme("media-record"), 'Record')
        self.rec.setMinimumSize(self.rec.size().width(), 50)
        self.rec.clicked.connect(self.go)  # self.run

        self.stop = QPushButton(QIcon.fromTheme("media-playback-stop"), 'Stop')
        self.stop.clicked.connect(self.end)

        self.kill = QPushButton(QIcon.fromTheme("process-stop"), 'Kill')
        self.kill.clicked.connect(self.killer)

        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (
            QLabel('<b style="color:white;"> Spectro'), self.spec,
            QLabel('<b style="color:white;"> Time '), self.clock,
            QLabel('<b style="color:white;"> Disk '), self.diskBar,
            QLabel('<b style="color:white;"> STDOUT + STDIN '), self.feedback,
            QLabel('<b style="color:white;"> Record '), self.rec, self.stop,
            self.kill):
            vboxg1.addWidget(each_widget)

        self.group2 = QGroupBox()
        self.group2.setTitle(__doc__)

        self.slider = QSlider(self)
        self.slid_l = QLabel(self.slider)
        self.slider.setCursor(QCursor(Qt.OpenHandCursor))
        self.slider.sliderPressed.connect(lambda:
                            self.slider.setCursor(QCursor(Qt.ClosedHandCursor)))
        self.slider.sliderReleased.connect(lambda:
                            self.slider.setCursor(QCursor(Qt.OpenHandCursor)))
        self.slider.valueChanged.connect(lambda:
                            self.slider.setToolTip(str(self.slider.value())))
        self.slider.valueChanged.connect(lambda: self.slid_l.setText(
                    '<h2 style="color:white;">{}'.format(self.slider.value())))
        self.slider.setMinimum(10)
        self.slider.setMaximum(99)
        self.slider.setValue(30)
        self.slider.setOrientation(Qt.Vertical)
        self.slider.setTickPosition(QSlider.TicksBothSides)
        self.slider.setTickInterval(2)
        self.slider.setSingleStep(10)
        self.slider.setPageStep(10)

        vboxg2 = QVBoxLayout(self.group2)
        for each_widget in (
            QLabel('<b style="color:white;">MINUTES of recording'), self.slider,
            QLabel('<b style="color:white;"> Default: 30 Min')):
            vboxg2.addWidget(each_widget)

        group3 = QGroupBox()
        group3.setTitle(__doc__)
        try:
            self.label2 = QLabel(getoutput('sox --version', shell=True))
            self.label4 = QLabel(getoutput('arecord --version', shell=1)[:25])
            self.label6 = QLabel(str(getoutput('oggenc --version', shell=True)))
        except:
            print(''' ERROR: No SOX, OGGenc avaliable !
                  ( sudo apt-get install vorbis-tools sox alsa-utils ) ''')
            exit()

        self.button5 = QPushButton(QIcon.fromTheme("audio-x-generic"),
                                   'OGG --> ZIP')
        self.button5.clicked.connect(lambda: make_archive(
            str(QFileDialog.getSaveFileName(self, "Save OGG to ZIP file As...",
            getcwd(), ';;(*.zip)', 'zip')).replace('.zip', ''), "zip",
            path.abspath(path.join(getcwd(), str(datetime.now().year)))))

        self.button1 = QPushButton(QIcon.fromTheme("folder-open"), 'Files')
        self.button1.clicked.connect(lambda:
                                     call('xdg-open ' + getcwd(), shell=True))

        self.button0 = QPushButton(
            QIcon.fromTheme("preferences-desktop-screensaver"), 'LCD OFF')
        self.button0.clicked.connect(lambda:
            call('sleep 3 ; xset dpms force off', shell=True))

        vboxg3 = QVBoxLayout(group3)
        for each_widget in (
            QLabel('<b style="color:white;"> OGG Output Codec '), self.label6,
            QLabel('<b style="color:white;"> Raw Record Backend '), self.label4,
            QLabel('<b style="color:white;"> Helper Libs '), self.label2,
            QLabel('<b style="color:white;"> OGG ZIP '), self.button5,
            QLabel('<b style="color:white;"> Files '), self.button1,
            QLabel('<b style="color:white;"> LCD '), self.button0):
            vboxg3.addWidget(each_widget)
        container = QWidget()
        hbox = QHBoxLayout(container)
        for each_widget in (self.group2, self.group1, group3):
            hbox.addWidget(each_widget)
        self.dock1.setWidget(container)

        # dock 2
        QLabel('<h1 style="color:white;"> Hardware !</h1>', self.dock2).resize(
               self.dock2.size().width() / 4, 25)
        try:
            audioDriverStr = {Solid.AudioInterface.Alsa: "ALSA",
                Solid.AudioInterface.OpenSoundSystem: "Open Sound",
                Solid.AudioInterface.UnknownAudioDriver: "Unknown?"}
            audioInterfaceTypeStr = {
                Solid.AudioInterface.AudioControl: "Control",
                Solid.AudioInterface.UnknownAudioInterfaceType: "Unknown?",
                Solid.AudioInterface.AudioInput: "In",
                Solid.AudioInterface.AudioOutput: "Out"}
            soundcardTypeStr = {
                Solid.AudioInterface.InternalSoundcard: "Internal",
                Solid.AudioInterface.UsbSoundcard: "USB3",
                Solid.AudioInterface.FirewireSoundcard: "FireWire",
                Solid.AudioInterface.Headset: "Headsets",
                Solid.AudioInterface.Modem: "Modem"}
            display = QTreeWidget()
            display.setAlternatingRowColors(True)
            display.setHeaderLabels(["Items", "ID", "Drivers", "I / O", "Type"])
            display.setColumnWidth(0, 350)
            display.setColumnWidth(1, 350)
            display.setColumnWidth(3, 75)
            # retrieve a list of Solid.Device for this machine
            deviceList = Solid.Device.allDevices()
            # filter the list of all devices and display matching results
            # note that we never create a Solid.AudioInterface object, but
            # receive one from the 'asDeviceInterface' call
            for device in deviceList:
                if device.isDeviceInterface(
                                         Solid.DeviceInterface.AudioInterface):
                    audio = device.asDeviceInterface(
                            Solid.DeviceInterface.AudioInterface)
                    devtype = audio.deviceType()
                    devstr = []
                    for key in audioInterfaceTypeStr:
                        flag = key & devtype
                        if flag:
                            devstr.append(audioInterfaceTypeStr[key])
                    QTreeWidgetItem(display, [device.product(), audio.name(),
                        audioDriverStr[audio.driver()], "/".join(devstr),
                        soundcardTypeStr[audio.soundcardType()]])
            self.dock2.setWidget(display)
        except:
            self.dock2.setWidget(QLabel(""" <center style='color:white;'>
            <h1>:(<br>ERROR: Please, install PyKDE !</h1><br>
            <br><i> (Sorry, can not use non-Qt Libs). Thanks </i><center>"""))

        ## dock 3
        QLabel('<h1 style="color:white;"> Previews !</h1>', self.dock3).resize(
               self.dock3.size().width() / 4, 25)
        self.fileView = QColumnView()
        self.fileView.updatePreviewWidget.connect(self.play)
        self.fileView.setToolTip(' Browse and Preview Files ')
        self.media = None
        self.model = QDirModel()
        self.fileView.setModel(self.model)
        self.dock3.setWidget(self.fileView)

        # dock4
        QLabel('<h1 style="color:white;"> Setup !</h1>', self.dock4).resize(
               self.dock4.size().width() / 4, 25)
        self.group4 = QGroupBox()
        self.group4.setTitle(__doc__)

        self.combo0 = QComboBox()
        self.combo0.addItems(['S16_LE', 'S32_LE', 'S16_BE', 'U16_LE', 'U16_BE',
          'S24_LE', 'S24_BE', 'U24_LE', 'U24_BE', 'S32_BE', 'U32_LE', 'U32_BE'])

        self.combo1 = QComboBox()
        self.combo1.addItems(['1', '-1', '0', '2', '3', '4',
                              '5', '6', '7', '8', '9', '10'])

        self.combo2 = QComboBox()
        self.combo2.addItems(['128', '256', '512', '1024', '64', '32', '16'])

        self.combo3 = QComboBox(self)
        self.combo3.addItems(['MONO', 'STEREO', 'Surround'])

        self.combo4 = QComboBox()
        self.combo4.addItems(['44100', '96000', '48000', '32000',
                              '22050', '16000', '11025', '8000'])

        self.combo5 = QComboBox(self)
        self.combo5.addItems(['20', '19', '18', '17', '16', '15', '14', '13',
            '12', '10', '9', '8', '7', '6', '5', '4', '3', '2', '1', '0'])

        self.nepochoose = QCheckBox('Auto-Tag Files using Nepomuk Semantic')

        self.chckbx0 = QCheckBox('Disable Software based Volume Control')

        self.chckbx1 = QCheckBox('Output Sound Stereo-to-Mono Downmix')

        self.chckbx2 = QCheckBox('Add Date and Time MetaData to Sound files')

        self.chckbx3 = QCheckBox('Add Yourself as the Author Artist of Sound')

        vboxg4 = QVBoxLayout(self.group4)
        for each_widget in (
            QLabel('<b style="color:white;"> Sound OGG Quality'), self.combo1,
            QLabel('<b style="color:white;"> Sound Record Format'), self.combo0,
            QLabel('<b style="color:white;"> Sound KBps '), self.combo2,
            QLabel('<b style="color:white;"> Sound Channels '), self.combo3,
            QLabel('<b style="color:white;"> Sound Sample Rate '), self.combo4,
            QLabel('<b style="color:white;"> Sound Volume'), self.chckbx0,
            QLabel('<b style="color:white;"> Sound Mix'), self.chckbx1,
            QLabel('<b style="color:white;"> Sound Meta'), self.chckbx2,
            QLabel('<b style="color:white;"> Sound Authorship'), self.chckbx3,
            QLabel('<b style="color:white;"> CPUs Priority'), self.combo5,
            QLabel('<b style="color:white;">Nepomuk Semantic User Experience'),
            self.nepochoose):
            vboxg4.addWidget(each_widget)
        self.dock4.setWidget(self.group4)

        # dock 5
        QLabel('<h1 style="color:white;"> Voice Changer ! </h1>', self.dock5
               ).resize(self.dock5.size().width() / 3, 25)
        self.group5 = QGroupBox()
        self.group5.setTitle(__doc__)

        self.dial = QDial()
        self.dial.setCursor(QCursor(Qt.OpenHandCursor))
        self.di_l = QLabel(self.dial)
        self.di_l.resize(self.dial.size() / 8)
        self.dial.sliderPressed.connect(lambda:
                            self.dial.setCursor(QCursor(Qt.ClosedHandCursor)))
        self.dial.sliderReleased.connect(lambda:
                            self.dial.setCursor(QCursor(Qt.OpenHandCursor)))
        self.dial.valueChanged.connect(lambda:
                            self.dial.setToolTip(str(self.dial.value())))
        self.dial.valueChanged.connect(lambda: self.di_l.setText(
                    '<h1 style="color:white;">{}'.format(self.dial.value())))
        self.dial.setValue(0)
        self.dial.setMinimum(-999)
        self.dial.setMaximum(999)
        self.dial.setSingleStep(100)
        self.dial.setPageStep(100)
        self.dial.setWrapping(False)
        self.dial.setNotchesVisible(True)

        self.defo = QPushButton(QIcon.fromTheme("media-playback-start"), 'Run')
        self.defo.setMinimumSize(self.defo.size().width(), 50)
        self.defo.clicked.connect(lambda: self.process3.start(
            'play -q -V0 "|rec -q -V0 -n -d -R riaa pitch {} "'
            .format(self.dial.value()) if int(self.dial.value()) != 0 else
            'play -q -V0 "|rec -q -V0 --multi-threaded -n -d -R bend {} "'
            .format(' 3,2500,3 3,-2500,3 ' * 999)))

        self.qq = QPushButton(QIcon.fromTheme("media-playback-stop"), 'Stop')
        self.qq.clicked.connect(self.process3.kill)

        self.die = QPushButton(QIcon.fromTheme("process-stop"), 'Kill')
        self.die.clicked.connect(lambda: call('killall rec', shell=True))

        vboxg5 = QVBoxLayout(self.group5)
        for each_widget in (self.dial, self.defo, self.qq, self.die):
            vboxg5.addWidget(each_widget)
        self.dock5.setWidget(self.group5)

        # configure some widget settings
        must_be_checked((self.nepochoose, self.chckbx1,
                         self.chckbx2, self.chckbx3))
        must_have_tooltip((self.label2, self.label4, self.label6, self.combo0,
            self.nepochoose, self.combo1, self.combo2, self.combo3, self.combo4,
            self.combo5, self.chckbx0, self.chckbx1, self.chckbx2, self.chckbx3,
            self.rec, self.stop, self.defo, self.qq, self.die, self.kill,
            self.button0, self.button1, self.button5))
        must_autofillbackground((self.clock, self.label2, self.label4,
            self.label6, self.nepochoose, self.chckbx0, self.chckbx1,
            self.chckbx2, self.chckbx3))
        must_glow((self.rec, self.dial, self.combo1))
        self.nepomuk_get('testigo')
        if self.auto is True:
            self.go()

    def play(self, index):
        ' play with delay '
        if not self.media:
            self.media = Phonon.MediaObject(self)
            audioOutput = Phonon.AudioOutput(Phonon.MusicCategory, self)
            Phonon.createPath(self.media, audioOutput)
        self.media.setCurrentSource(Phonon.MediaSource(
            self.model.filePath(index)))
        self.media.play()

    def end(self):
        ' kill it with fire '
        print((' INFO: Stoping Processes at {}'.format(str(datetime.now()))))
        self.process1.terminate()
        self.process2.terminate()
        self.feedback.setText('''
            <h5>Errors for RECORDER QProcess 1:</h5>{}<hr>
            <h5>Errors for ENCODER QProcess 2:</h5>{}<hr>
            <h5>Output for RECORDER QProcess 1:</h5>{}<hr>
            <h5>Output for ENCODER QProcess 2:</h5>{}<hr>
            '''.format(self.process1.readAllStandardError(),
                       self.process2.readAllStandardError(),
                       self.process1.readAllStandardOutput(),
                       self.process2.readAllStandardOutput(),
        ))

    def killer(self):
        ' kill -9 '
        QMessageBox.information(self.mainwidget, __doc__,
            ' KILL -9 was sent to the multi-process backend ! ')
        self.process1.kill()
        self.process2.kill()

    def go(self):
        ' run timeout re-starting timers '
        self.timerFirst.start(int(self.slider.value()) * 60 * 1000 + 2000)
        self.timerSecond.start(int(self.slider.value()) * 60 * 1000 + 2010)
        self.run()

    def run(self):
        ' run forest run '
        print((' INFO: Working at {}'.format(str(datetime.now()))))

        chnl = 1 if self.combo3.currentText() == 'MONO' else 2
        print((' INFO: Using {} Channels . . . '.format(chnl)))

        btrt = int(self.combo4.currentText())
        print((' INFO: Using {} Hz per Second . . . '.format(btrt)))

        threshold = int(self.dial.value())
        print((' INFO: Using Thresold of {} . . . '.format(threshold)))

        print((' INFO: Using Recording time of {}'.format(self.slider.value())))

        frmt = str(self.combo0.currentText()).strip()
        print((' INFO: Using Recording quality of {} ...'.format(frmt)))

        qlt = str(self.combo1.currentText()).strip()
        print((' INFO: Using Recording quality of {} ...'.format(qlt)))

        prio = str(self.combo5.currentText()).strip()
        print((' INFO: Using CPU Priority of {} ...'.format(prio)))

        downmix = '--downmix ' if self.chckbx1.isChecked() is True else ''
        print((' INFO: Using Downmix is {} ...'.format(downmix)))

        aut = '-a ' + getuser() if self.chckbx3.isChecked() is True else ''
        print((' INFO: The Author Artist of this sound is: {}'.format(aut)))

        T = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        tim = '--date {} '.format(T) if self.chckbx2.isChecked() is True else ''
        print((' INFO: The Date and Time of this sound is: {}'.format(tim)))

        vol = ' --disable-softvol' if self.chckbx0.isChecked() is True else ''
        print((' INFO: Software based Volume Control is: {}'.format(vol)))

        # make base directory
        try:
            mkdir(self.base)
            print((' INFO: Base Directory path created {}'.format(self.base)))
        except OSError:
            print((' INFO: Base Directory already exist {}'.format(self.base)))
        except:
            print((' ERROR: Can not create Directory ?, {}'.format(self.base)))

        # make directory tree
        try:
            for dr in range(1, 13):
                mkdir(path.abspath(path.join(self.base, str(dr))))
                print((' INFO:Directory created {}/{}'.format(self.base, dr)))
        except OSError:
            print((' INFO: Directory already exist {}/1,12'.format(self.base)))
        except:
            print((' ERROR: Cant create Directory?, {}/1,12'.format(self.base)))

        # make new filename
        flnm = path.abspath(path.join(self.base, str(datetime.now().month),
                   datetime.now().strftime("%Y-%m-%d_%H:%M:%S.ogg")))
        self.actual_file = flnm
        print((' INFO: Recording on the file {}'.format(flnm)))

        # make custom commands
        cmd1 = self.cmd1.format(n=prio, f=frmt, c=chnl, b=btrt, v=vol)
        cmd2 = self.cmd2.format(c=chnl, b=btrt, q=qlt,
                                d=downmix, o=flnm, a=aut, t=tim)
        print((cmd1, cmd2))
        #  multiprocess recording loop pipe
        self.process1 = QProcess(self)
        self.process2 = QProcess(self)
        self.process1.setStandardOutputProcess(self.process2)
        self.process1.start(cmd1)
        if not self.process1.waitForStarted():
            print((" ERROR: RECORDER QProcess 1 Failed: \n {}   ".format(cmd1)))
        self.process2.start(cmd2)
        if not self.process2.waitForStarted():
            print((" ERROR: ENCODER QProcess 2 Failed: \n   {} ".format(cmd2)))
        self.nepomuk_set(flnm, 'testigo', 'testigo', 'AutoTag by Cinta-Testigo')

    def spectro(self):
        ' spectrometer '
        wid = self.spec.size().width()
        hei = self.spec.size().height()
        command = self.cmd3.format(o=self.actual_file, x=wid, y=hei)
        print(' INFO: Spectrometer is deleting OLD .ogg.png Files on target ')
        call('rm --verbose --force {}/*/*.ogg.png'.format(self.base), shell=1)
        print(' INFO: Spectrometer finished Deleting Files, Starting Render ')
        call(command, shell=True)
        print((''' INFO: Spectrometer finished Rendering Sound using:
               {}{}   OutPut: {}'''.format(command, linesep, self.actual_file)))
        self.spec.setIcon(QIcon('{o}.png'.format(o=self.actual_file)))
        self.spec.setIconSize(QSize(wid, hei))
        self.spec.resize(wid, hei)

    ###########################################################################

    def paintEvent(self, event):
        'Paint semi-transparent background, animated pattern, background text'
        QWidget.paintEvent(self, event)
        # make a painter
        p = QPainter(self)
        p.setRenderHint(QPainter.TextAntialiasing)
        p.setRenderHint(QPainter.HighQualityAntialiasing)
        # fill a rectangle with transparent painting
        p.fillRect(event.rect(), Qt.transparent)
        # animated random dots background pattern
        for i in range(4096):
            x = randint(9, self.size().width() - 9)
            y = randint(9, self.size().height() - 9)
            p.setPen(QPen(QColor(randint(200, 255), randint(200, 255), 255), 1))
            p.drawPoint(x, y)
        # set pen to use white color
        p.setPen(QPen(QColor(randint(9, 255), randint(9, 255), 255), 1))
        # Rotate painter 45 Degree
        p.rotate(35)
        # Set painter Font for text
        p.setFont(QFont('Ubuntu', 300))
        # draw the background text, with antialiasing
        p.drawText(99, 199, "Radio")
        # Rotate -45 the QPen back !
        p.rotate(-35)
        # set the pen to no pen
        p.setPen(Qt.NoPen)
        # Background Color
        p.setBrush(QColor(0, 0, 0))
        # Background Opacity
        p.setOpacity(0.75)
        # Background Rounded Borders
        p.drawRoundedRect(self.rect(), 50, 50)
        # finalize the painter
        p.end()

    def seTitle(self):
        ' set the title of the main window '
        dialog = QDialog(self)
        textEditInput = QLineEdit(' Type Title Here ')
        ok = QPushButton(' O K ')
        ok.clicked.connect(lambda: self.setWindowTitle(textEditInput.text()))
        ly = QVBoxLayout()
        [ly.addWidget(wdgt) for wdgt in (QLabel('Title:'), textEditInput, ok)]
        dialog.setLayout(ly)
        dialog.exec_()

    def timedate(self):
        ' get the time and date '
        dialog = QDialog(self)
        clock = QLCDNumber()
        clock.setNumDigits(24)
        timer = QTimer()
        timer.timeout.connect(lambda: clock.display(
            datetime.now().strftime("%d-%m-%Y %H:%M:%S %p")))
        timer.start(1000)
        clock.setToolTip(datetime.now().strftime("%c %x"))
        ok = QPushButton(' O K ')
        ok.clicked.connect(dialog.close)
        ly = QVBoxLayout()
        [ly.addWidget(wdgt) for wdgt in (QCalendarWidget(), clock, ok)]
        dialog.setLayout(ly)
        dialog.exec_()

    def closeEvent(self, event):
        ' Ask to Quit '
        if QMessageBox.question(self, ' Close ', ' Quit ? ',
           QMessageBox.Yes | QMessageBox.No, QMessageBox.No) == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def center(self):
        ' Center and resize the window '
        self.showNormal()
        self.resize(QDesktopWidget().screenGeometry().width() // 1.25,
                    QDesktopWidget().screenGeometry().height() // 1.25)
        qr = self.frameGeometry()
        qr.moveCenter(QDesktopWidget().availableGeometry().center())
        self.move(qr.topLeft())

    def nepomuk_set(self, file_tag=None, __tag='', _label='', _description=''):
        ' Quick and Easy Nepomuk Taggify for Files '
        print((''' INFO: Semantic Desktop Experience is Tagging Files :
              {}, {}, {}, {})'''.format(file_tag, __tag, _label, _description)))
        if Nepomuk.ResourceManager.instance().init() is 0:
            fle = Nepomuk.Resource(KUrl(QFileInfo(file_tag).absoluteFilePath()))
            _tag = Nepomuk.Tag(__tag)
            _tag.setLabel(_label)
            fle.addTag(_tag)
            fle.setDescription(_description)
            print(([str(a.label()) for a in fle.tags()], fle.description()))
            return ([str(a.label()) for a in fle.tags()], fle.description())
        else:
            print(" ERROR: FAIL: Nepomuk is not running ! ")

    def nepomuk_get(self, query_to_search):
        ' Quick and Easy Nepomuk Query for Files '
        print((''' INFO: Semantic Desktop Experience is Quering Files :
              {} '''.format(query_to_search)))
        results = []
        nepo = Nepomuk.Query.QueryServiceClient()
        nepo.desktopQuery("hasTag:{}".format(query_to_search))

        def _query(data):
            ''' ('filename.ext', 'file description', ['list', 'of', 'tags']) '''
            results.append(([str(a.resource().genericLabel()) for a in data][0],
                            [str(a.resource().description()) for a in data][0],
            [str(a.label()) for a in iter([a.resource().tags() for a in data][0]
            )]))
        nepo.newEntries.connect(_query)

        def _end():
            '''
            [  ('filename.ext', 'file description', ['list', 'of', 'tags']),
               ('filename.ext', 'file description', ['list', 'of', 'tags']),
               ('filename.ext', 'file description', ['list', 'of', 'tags'])  ]
            '''
            nepo.newEntries.disconnect
            print(results)
            return results
        nepo.finishedListing.connect(_end)
Ejemplo n.º 17
0
class Main(plugin.Plugin):
    " Main Class "
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        self.infile = QLineEdit(path.expanduser("~"))
        self.infile.setPlaceholderText(' /full/path/to/file ')
        self.infile.returnPressed.connect(self.run)
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        self.infile.setCompleter(self.completer)

        self.menu = QMenu('Base64')
        self.menu.aboutToShow.connect(self.build_submenu)
        self.ex_locator = self.locator.get_service('explorer')
        self.ex_locator.add_project_menu(self.menu, lang='all')

        self.open = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open.setCursor(QCursor(Qt.PointingHandCursor))
        self.open.clicked.connect(lambda: self.infile.setText(str(
            QFileDialog.getOpenFileName(self.dock, "Open a File to Encode...",
            path.expanduser("~"), ';;'.join(['{}(*.{})'.format(e.upper(), e)
            for e in ['*', 'jpg', 'png', 'webp', 'svg', 'gif', 'webm']])))))
        self.chckbx1 = QCheckBox('Use basic Caesar Cipher (ROT13)')
        self.chckbx1.setToolTip('Use "string".decode("rot13") to Decipher ! ')
        self.chckbx2 = QCheckBox('Use "data:type/subtype;base64,..."')
        self.chckbx2.setChecked(True)
        self.chckbx3 = QCheckBox('Copy encoded output to Clipboard')
        self.chckbx4 = QCheckBox('Use URL-Safe Base64 Encoder')
        self.combo1 = QComboBox()
        self.combo1.addItems(['Do Not Generate Code', 'Generate CSS embed Code',
            'Generate Python Embed Code', 'Generate HTML embed Code',
            'Generate JS embed Code', 'Generate QML embed Code'])
        self.combo1.currentIndexChanged.connect(self.combo_changed)

        self.output = QTextEdit('''
        We can only see a short distance ahead,
        but we can see plenty there that needs to be done.
        - Alan Turing ''')
        self.output.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.button = QPushButton(QIcon.fromTheme("face-cool"), 'Encode BASE64')
        self.button.setCursor(QCursor(Qt.PointingHandCursor))
        self.button.setMinimumSize(100, 50)
        self.button.clicked.connect(self.run)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.button.setGraphicsEffect(glow)
        glow.setEnabled(True)

        class TransientWidget(QWidget):
            ' persistant widget thingy '
            def __init__(self, widget_list):
                ' init sub class '
                super(TransientWidget, self).__init__()
                vbox = QVBoxLayout(self)
                for each_widget in widget_list:
                    vbox.addWidget(each_widget)

        tw = TransientWidget((QLabel('<i>Encode file as plain text string</i>'),
            QLabel('<b>File to Encode:'), self.infile, self.open, self.chckbx2,
            self.chckbx3, self.chckbx1, self.chckbx4,
            QLabel('<b>Embedding Template Code:'), self.combo1,
            QLabel(' <b>Base64 String Output: '), self.output,
            QLabel('<center><small><i>' + ''.join((__doc__, __version__,
                   __license__, 'by', __author__))), self.button
        ))
        self.scrollable, self.dock = QScrollArea(), QDockWidget()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(tw)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        ExplorerContainer().addTab(self.dock, "Base64")
        self.guimode = QComboBox(self.dock)
        self.guimode.addItems(['Full Mode', 'Simple Mode'])
        self.guimode.currentIndexChanged.connect(self.guimode_change)

    def guimode_change(self):
        """ Change from Simple Mode to Full Mode by Hide or Show Widgets """
        if self.guimode.currentIndex() is 0:
            self.chckbx1.show()
            self.chckbx2.show()
            self.chckbx3.show()
            self.chckbx4.show()
        else:
            self.chckbx1.hide()
            self.chckbx2.hide()
            self.chckbx3.hide()
            self.chckbx4.hide()
            self.chckbx1.setChecked(False)
            self.chckbx2.setChecked(True)
            self.chckbx3.setChecked(False)
            self.chckbx4.setChecked(False)

    def build_submenu(self):
        ''' build sub menu on the fly based on file path '''
        self.menu.clear()
        if self.ex_locator.get_current_project_item().isFolder is not True:
            filenam = self.ex_locator.get_current_project_item().get_full_path()
            self.menu.addActions([
                QAction('Copy {} as Base64'.format(path.basename(filenam)[:50]),
                        self, triggered=lambda:
                        QApplication.clipboard().setText(
                        '"data:{};charset=utf-8;base64,{}"'.format(
                            guess_type(filenam, strict=False)[0],
                            b64encode(open(filenam, "rb").read())))),
                QAction('Copy {} as Base64 URL-Safe'.format(
                        path.basename(filenam)[:50]),
                        self, triggered=lambda:
                        QApplication.clipboard().setText(
                        '"data:{};charset=utf-8;base64,{}"'.format(
                            guess_type(filenam, strict=False)[0],
                            urlsafe_b64encode(open(filenam, "rb").read()))))])
            self.menu.show()

    def run(self):
        ' run the encoding '
        mimetype = guess_type(str(self.infile.text()).strip(), strict=False)[0]
        _mime = mimetype if mimetype is not None else self.ask_mime()
        fle = str(self.infile.text()).strip().replace('file:///', '/')
        encoder = urlsafe_b64encode if self.chckbx4.isChecked() else b64encode
        if int(path.getsize(fle)) / 1024 / 1024 >= 1:
            QMessageBox.information(self.dock, __doc__,
            '''<b style="color:red"> WARNING!: File size is > 1 Megabyte!,<br>
            this will take some time, depending your CPU Processing power!.''')
        output = '"{}{}{}{}"'.format(
            'data:' if self.chckbx2.isChecked() is True else '',
            _mime if self.chckbx2.isChecked() is True else '',
           ';charset=utf-8;base64,' if self.chckbx2.isChecked() is True else '',
            encoder(open(fle, "rb").read()))
        if self.combo1.currentIndex() is 1:
            output = ('html, body { margin:0; padding:0; background: url(' +
            output + ') no-repeat center center fixed; background-size:cover }')
        elif self.combo1.currentIndex() is 2:
            output = PY_EMBED.format(getuser(),
                     datetime.now().isoformat().split('.')[0], output)
        elif self.combo1.currentIndex() is 3:
            output = '<img src={} alt="{}" title="{}"/>'.format(output,
                     fle.split(sep)[-1], fle.split(sep)[-1])
        elif self.combo1.currentIndex() is 4:
            output = 'var embedded_file = window.atob({}); '.format(output)
        elif self.combo1.currentIndex() is 5:
            output = 'Image { source: ' + output + ' } '
        if self.chckbx1.isChecked() is True:
            output = str(output).encode('rot13')
        if self.chckbx3.isChecked() is True:
            QApplication.clipboard().setText(output)
        self.output.setPlainText(output)
        self.output.setFocus()
        self.output.selectAll()

    def ask_mime(self):
        ' ask user for mime type '
        return str(QInputDialog.getText(self.dock, __doc__, 'Write a MIME-Type',
               QLineEdit.Normal, 'application/octet-stream')[0]).strip().lower()

    def combo_changed(self):
        ' on combo changed '
        if self.combo1.currentIndex() is 1 or self.combo1.currentIndex() is 3:
            self.chckbx1.setChecked(False)
            self.chckbx2.setChecked(True)
        elif self.combo1.currentIndex() is 2 or self.combo1.currentIndex() is 4:
            self.chckbx1.setChecked(False)
            self.chckbx2.setChecked(False)
Ejemplo n.º 18
0
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        self.process = QProcess()
        self.process.readyReadStandardOutput.connect(self.readOutput)
        self.process.readyReadStandardError.connect(self.readErrors)
        self.process.finished.connect(self._process_finished)
        self.process.error.connect(self._process_finished)
        self.editor_s = self.locator.get_service('editor')
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)

        self.group0 = QGroupBox()
        self.group0.setTitle(' Source ')
        self.infile = QLineEdit(path.expanduser("~"))
        self.infile.setPlaceholderText(' /full/path/to/file.html ')
        self.infile.setCompleter(self.completer)
        self.open = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open.setCursor(QCursor(Qt.PointingHandCursor))
        self.open.clicked.connect(lambda: self.infile.setText(str(
            QFileDialog.getOpenFileName(self.dock, "Open a File to read from",
            path.expanduser("~"), ';;'.join(['{}(*.{})'.format(e.upper(), e)
            for e in ['py', 'pyw', 'txt', '*']])))))
        self.output = QTextEdit()
        vboxg0 = QVBoxLayout(self.group0)
        for each_widget in (self.infile, self.open, self.output):
            vboxg0.addWidget(each_widget)

        self.group1 = QGroupBox()
        self.group1.setTitle(' General ')
        self.group1.setCheckable(True)
        self.group1.setGraphicsEffect(QGraphicsBlurEffect(self))
        self.group1.graphicsEffect().setEnabled(False)
        self.group1.toggled.connect(self.toggle_gral_group)
        self.ckgrl1 = QCheckBox('Create standalone executable')
        self.ckgrl2 = QCheckBox('Use Python debug')
        self.ckgrl3 = QCheckBox('Force compilation for MS Windows')
        self.ckgrl4 = QCheckBox('When compiling, disable the console window')
        self.ckgrl5 = QCheckBox('Use link time optimizations if available')
        self.ckgrl6 = QCheckBox('Force the use of clang')
        self.ckgrl7 = QCheckBox('Allow minor devitations from Python behaviour')
        self.ckgrl8 = QCheckBox('Warnings implicit exceptions at compile time')
        self.pyver, self.jobs = QComboBox(), QSpinBox()
        self.pyver.addItems(['2.7', '2.6', '3.2', '3.3'])
        self.jobs.setValue(1)
        self.jobs.setMaximum(12)
        self.jobs.setMinimum(1)
        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (self.ckgrl1, self.ckgrl2, self.ckgrl3, self.ckgrl4,
            self.ckgrl5, self.ckgrl6, self.ckgrl7, self.ckgrl8,
            QLabel('Python Version to Target'), self.pyver,
            QLabel('Multi-Processing Parallel Workers'), self.jobs):
            vboxg1.addWidget(each_widget)
            try:
                each_widget.setToolTip(each_widget.text())
            except:
                pass

        self.group2 = QGroupBox()
        self.group2.setTitle(' Recursion Control ')
        self.ckrec0 = QCheckBox('Descend to imported modules from standard lib')
        self.ckrec1 = QCheckBox('Force not descend to any imported modules')
        self.ckrec2 = QCheckBox('Try to descend into all imported modules')
        vboxg2 = QVBoxLayout(self.group2)
        for each_widget in (self.ckrec0, self.ckrec1, self.ckrec2):
            vboxg2.addWidget(each_widget)
            each_widget.setToolTip(each_widget.text())

        self.group3 = QGroupBox()
        self.group3.setTitle(' Execution after compilation ')
        self.ckexe0 = QCheckBox('Execute created binary (or import the module)')
        self.ckexe1 = QCheckBox('When executing binary dont reset PYTHONPATH')
        vboxg2 = QVBoxLayout(self.group3)
        for each_widget in (self.ckexe0, self.ckexe1):
            vboxg2.addWidget(each_widget)
            each_widget.setToolTip(each_widget.text())

        self.group4, self.dumptree = QGroupBox(), QTextEdit()
        self.group4.setTitle(' Dump of internal tree ')
        QVBoxLayout(self.group4).addWidget(self.dumptree)

        self.group5 = QGroupBox()
        self.group5.setTitle(' Code generation ')
        self.chdmp1 = QCheckBox('Statements shall have their line numbers set')
        self.chdmp2 = QCheckBox('Disable all unnecessary Python optimization')
        vboxg5 = QVBoxLayout(self.group5)
        for each_widget in (self.chdmp1, self.chdmp2):
            vboxg5.addWidget(each_widget)
            each_widget.setToolTip(each_widget.text())

        self.group6 = QGroupBox()
        self.group6.setTitle(' Output ')
        self.outdir = QLineEdit(path.expanduser("~"))
        self.outdir.setPlaceholderText(' /full/path/to/target/directory ')
        self.outdir.setCompleter(self.completer)
        self.open2 = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open2.setCursor(QCursor(Qt.PointingHandCursor))
        self.open2.clicked.connect(lambda: self.outdir.setText(str(
            QFileDialog.getExistingDirectory(self.dock, "Open Target Folder",
            path.expanduser("~")))))
        self.ckcgn2 = QCheckBox('Remove build dir after compile module or exe')
        vboxg6 = QVBoxLayout(self.group6)
        for each_widget in (QLabel('Target Output Directory'), self.outdir,
                            self.open2, self.ckcgn2):
            vboxg6.addWidget(each_widget)
            each_widget.setToolTip(each_widget.text())

        self.group7 = QGroupBox()
        self.group7.setTitle(' Debug ')
        self.ckdbg1 = QCheckBox('Execute self checks to find errors in Nuitka')
        self.ckdbg2 = QCheckBox('Keep debug info in resulting file')
        self.ckdbg3 = QCheckBox('Traced execution output')
        self.ckdbg4 = QCheckBox('Allow compile edited C++ file, debug changes')
        self.ckdbg5 = QCheckBox('Use experimental features')
        vboxg7 = QVBoxLayout(self.group7)
        for each_widget in (self.ckdbg1, self.ckdbg2, self.ckdbg3,
                            self.ckdbg4, self.ckdbg5):
            vboxg7.addWidget(each_widget)
            each_widget.setToolTip(each_widget.text())

        self.group8 = QGroupBox()
        self.group8.setTitle(' Tracing ')
        self.cktrc1 = QCheckBox('Show Scons in non-quiet mode, showing command')
        self.cktrc2 = QCheckBox('Show Progress information and statistics')
        self.cktrc3 = QCheckBox('Show Verbose output details')
        vboxg8 = QVBoxLayout(self.group8)
        for each_widget in (self.cktrc1, self.cktrc2, self.cktrc3):
            vboxg8.addWidget(each_widget)
            each_widget.setToolTip(each_widget.text())

        self.group9 = QGroupBox()
        self.group9.setTitle(' Extras ')
        self.group9.setCheckable(True)
        self.group9.toggled.connect(self.group9.hide)
        self.nice = QSpinBox()
        self.nice.setValue(20)
        self.nice.setMaximum(20)
        self.nice.setMinimum(0)
        self.ckxtr1 = QCheckBox('Open Target Directory later')
        self.ckxtr2 = QCheckBox('Save a LOG file to target later')
        self.ckxtr3 = QCheckBox('Save SH Bash script to reproduce Nuitka build')
        try:
            self.vinfo = QLabel('<center> <b> Nuitka Backend Version: </b>' +
                            getoutput('nuitka --version',).strip())
        except:
            self.vinfo = QLabel('<b>Warning: Failed to query Nuitka Backend!')
        vboxg9 = QVBoxLayout(self.group9)
        for each_widget in (QLabel('Backend CPU Priority'), self.nice,
                            self.ckxtr1, self.ckxtr2, self.ckxtr3, self.vinfo):
            vboxg9.addWidget(each_widget)

        self.group10 = QGroupBox()
        self.group10.setTitle(' Documentation ')
        self.group10.setCheckable(True)
        self.group10.toggled.connect(self.group10.hide)
        vboxg10 = QVBoxLayout(self.group10)
        for each_widget in (QLabel('''<a href=
            "file:///usr/share/doc/nuitka/README.pdf.gz">
            <small><center> Nuitka User Documentation Local PDF </a>'''),
            QLabel('''<a href=
            "file:///usr/share/doc/nuitka/Developer_Manual.pdf.gz">
            <small><center> Nuitka Developer Documentation Local PDF </a>'''),
            QLabel('''<a href="http://nuitka.net/doc/user-manual.html">
            <small><center> Nuitka User Documentation On Line HTML </a>'''),
            QLabel('''<a href="http://nuitka.net/doc/developer-manual.html">
            <small><center> Nuitka Developer Documentation On Line HTML </a>''')
             ):
            vboxg10.addWidget(each_widget)
            each_widget.setOpenExternalLinks(True)
            each_widget.setTextInteractionFlags(Qt.LinksAccessibleByMouse)

        [a.setChecked(True) for a in (self.ckgrl1, self.ckgrl2, self.ckgrl4,
            self.ckgrl5, self.ckgrl6, self.ckgrl7, self.ckgrl8, self.ckrec0,
            self.ckrec1, self.ckrec2, self.ckexe1, self.ckcgn2, self.ckdbg1,
            self.ckdbg3, self.ckdbg4, self.ckdbg5, self.cktrc1, self.cktrc2,
            self.cktrc3, self.ckxtr1, self.ckxtr2, self.ckxtr3,)]

        self.button = QPushButton(QIcon.fromTheme("face-cool"),
                                  'Compile Python')
        self.button.setCursor(QCursor(Qt.PointingHandCursor))
        self.button.setMinimumSize(100, 50)
        self.button.clicked.connect(self.run)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.button.setGraphicsEffect(glow)

        class TransientWidget(QWidget):
            ' persistant widget thingy '
            def __init__(self, widget_list):
                ' init sub class '
                super(TransientWidget, self).__init__()
                vbox = QVBoxLayout(self)
                for each_widget in widget_list:
                    vbox.addWidget(each_widget)

        tw = TransientWidget((
            QLabel('<b>Python Code to Binary Executable Compiler'), self.group0,
            self.group6, self.group1, self.group2, self.group3, self.group4,
            self.group5, self.group7, self.group8, self.group9, self.group10,
            self.button, ))
        self.scrollable, self.dock = QScrollArea(), QDockWidget()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(tw)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        ExplorerContainer().addTab(self.dock, "Nuitka")
        QPushButton(QIcon.fromTheme("help-about"), 'About', self.dock
          ).clicked.connect(lambda: QMessageBox.information(self.dock, __doc__,
            HELPMSG))
Ejemplo n.º 19
0
class Main(plugin.Plugin):
    " Main Class "
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        self.process = QProcess()
        self.process.readyReadStandardOutput.connect(self.readOutput)
        self.process.readyReadStandardError.connect(self.readErrors)
        self.process.finished.connect(self._process_finished)
        self.process.error.connect(self._process_finished)
        self.editor_s = self.locator.get_service('editor')
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)

        self.group0 = QGroupBox()
        self.group0.setTitle(' Source ')
        self.infile = QLineEdit(path.expanduser("~"))
        self.infile.setPlaceholderText(' /full/path/to/file.html ')
        self.infile.setCompleter(self.completer)
        self.open = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open.setCursor(QCursor(Qt.PointingHandCursor))
        self.open.clicked.connect(lambda: self.infile.setText(str(
            QFileDialog.getOpenFileName(self.dock, "Open a File to read from",
            path.expanduser("~"), ';;'.join(['{}(*.{})'.format(e.upper(), e)
            for e in ['py', 'pyw', 'txt', '*']])))))
        self.output = QTextEdit()
        vboxg0 = QVBoxLayout(self.group0)
        for each_widget in (self.infile, self.open, self.output):
            vboxg0.addWidget(each_widget)

        self.group1 = QGroupBox()
        self.group1.setTitle(' General ')
        self.group1.setCheckable(True)
        self.group1.setGraphicsEffect(QGraphicsBlurEffect(self))
        self.group1.graphicsEffect().setEnabled(False)
        self.group1.toggled.connect(self.toggle_gral_group)
        self.ckgrl1 = QCheckBox('Create standalone executable')
        self.ckgrl2 = QCheckBox('Use Python debug')
        self.ckgrl3 = QCheckBox('Force compilation for MS Windows')
        self.ckgrl4 = QCheckBox('When compiling, disable the console window')
        self.ckgrl5 = QCheckBox('Use link time optimizations if available')
        self.ckgrl6 = QCheckBox('Force the use of clang')
        self.ckgrl7 = QCheckBox('Allow minor devitations from Python behaviour')
        self.ckgrl8 = QCheckBox('Warnings implicit exceptions at compile time')
        self.pyver, self.jobs = QComboBox(), QSpinBox()
        self.pyver.addItems(['2.7', '2.6', '3.2', '3.3'])
        self.jobs.setValue(1)
        self.jobs.setMaximum(12)
        self.jobs.setMinimum(1)
        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (self.ckgrl1, self.ckgrl2, self.ckgrl3, self.ckgrl4,
            self.ckgrl5, self.ckgrl6, self.ckgrl7, self.ckgrl8,
            QLabel('Python Version to Target'), self.pyver,
            QLabel('Multi-Processing Parallel Workers'), self.jobs):
            vboxg1.addWidget(each_widget)
            try:
                each_widget.setToolTip(each_widget.text())
            except:
                pass

        self.group2 = QGroupBox()
        self.group2.setTitle(' Recursion Control ')
        self.ckrec0 = QCheckBox('Descend to imported modules from standard lib')
        self.ckrec1 = QCheckBox('Force not descend to any imported modules')
        self.ckrec2 = QCheckBox('Try to descend into all imported modules')
        vboxg2 = QVBoxLayout(self.group2)
        for each_widget in (self.ckrec0, self.ckrec1, self.ckrec2):
            vboxg2.addWidget(each_widget)
            each_widget.setToolTip(each_widget.text())

        self.group3 = QGroupBox()
        self.group3.setTitle(' Execution after compilation ')
        self.ckexe0 = QCheckBox('Execute created binary (or import the module)')
        self.ckexe1 = QCheckBox('When executing binary dont reset PYTHONPATH')
        vboxg2 = QVBoxLayout(self.group3)
        for each_widget in (self.ckexe0, self.ckexe1):
            vboxg2.addWidget(each_widget)
            each_widget.setToolTip(each_widget.text())

        self.group4, self.dumptree = QGroupBox(), QTextEdit()
        self.group4.setTitle(' Dump of internal tree ')
        QVBoxLayout(self.group4).addWidget(self.dumptree)

        self.group5 = QGroupBox()
        self.group5.setTitle(' Code generation ')
        self.chdmp1 = QCheckBox('Statements shall have their line numbers set')
        self.chdmp2 = QCheckBox('Disable all unnecessary Python optimization')
        vboxg5 = QVBoxLayout(self.group5)
        for each_widget in (self.chdmp1, self.chdmp2):
            vboxg5.addWidget(each_widget)
            each_widget.setToolTip(each_widget.text())

        self.group6 = QGroupBox()
        self.group6.setTitle(' Output ')
        self.outdir = QLineEdit(path.expanduser("~"))
        self.outdir.setPlaceholderText(' /full/path/to/target/directory ')
        self.outdir.setCompleter(self.completer)
        self.open2 = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open2.setCursor(QCursor(Qt.PointingHandCursor))
        self.open2.clicked.connect(lambda: self.outdir.setText(str(
            QFileDialog.getExistingDirectory(self.dock, "Open Target Folder",
            path.expanduser("~")))))
        self.ckcgn2 = QCheckBox('Remove build dir after compile module or exe')
        vboxg6 = QVBoxLayout(self.group6)
        for each_widget in (QLabel('Target Output Directory'), self.outdir,
                            self.open2, self.ckcgn2):
            vboxg6.addWidget(each_widget)
            each_widget.setToolTip(each_widget.text())

        self.group7 = QGroupBox()
        self.group7.setTitle(' Debug ')
        self.ckdbg1 = QCheckBox('Execute self checks to find errors in Nuitka')
        self.ckdbg2 = QCheckBox('Keep debug info in resulting file')
        self.ckdbg3 = QCheckBox('Traced execution output')
        self.ckdbg4 = QCheckBox('Allow compile edited C++ file, debug changes')
        self.ckdbg5 = QCheckBox('Use experimental features')
        vboxg7 = QVBoxLayout(self.group7)
        for each_widget in (self.ckdbg1, self.ckdbg2, self.ckdbg3,
                            self.ckdbg4, self.ckdbg5):
            vboxg7.addWidget(each_widget)
            each_widget.setToolTip(each_widget.text())

        self.group8 = QGroupBox()
        self.group8.setTitle(' Tracing ')
        self.cktrc1 = QCheckBox('Show Scons in non-quiet mode, showing command')
        self.cktrc2 = QCheckBox('Show Progress information and statistics')
        self.cktrc3 = QCheckBox('Show Verbose output details')
        vboxg8 = QVBoxLayout(self.group8)
        for each_widget in (self.cktrc1, self.cktrc2, self.cktrc3):
            vboxg8.addWidget(each_widget)
            each_widget.setToolTip(each_widget.text())

        self.group9 = QGroupBox()
        self.group9.setTitle(' Extras ')
        self.group9.setCheckable(True)
        self.group9.toggled.connect(self.group9.hide)
        self.nice = QSpinBox()
        self.nice.setValue(20)
        self.nice.setMaximum(20)
        self.nice.setMinimum(0)
        self.ckxtr1 = QCheckBox('Open Target Directory later')
        self.ckxtr2 = QCheckBox('Save a LOG file to target later')
        self.ckxtr3 = QCheckBox('Save SH Bash script to reproduce Nuitka build')
        try:
            self.vinfo = QLabel('<center> <b> Nuitka Backend Version: </b>' +
                            getoutput('nuitka --version',).strip())
        except:
            self.vinfo = QLabel('<b>Warning: Failed to query Nuitka Backend!')
        vboxg9 = QVBoxLayout(self.group9)
        for each_widget in (QLabel('Backend CPU Priority'), self.nice,
                            self.ckxtr1, self.ckxtr2, self.ckxtr3, self.vinfo):
            vboxg9.addWidget(each_widget)

        self.group10 = QGroupBox()
        self.group10.setTitle(' Documentation ')
        self.group10.setCheckable(True)
        self.group10.toggled.connect(self.group10.hide)
        vboxg10 = QVBoxLayout(self.group10)
        for each_widget in (QLabel('''<a href=
            "file:///usr/share/doc/nuitka/README.pdf.gz">
            <small><center> Nuitka User Documentation Local PDF </a>'''),
            QLabel('''<a href=
            "file:///usr/share/doc/nuitka/Developer_Manual.pdf.gz">
            <small><center> Nuitka Developer Documentation Local PDF </a>'''),
            QLabel('''<a href="http://nuitka.net/doc/user-manual.html">
            <small><center> Nuitka User Documentation On Line HTML </a>'''),
            QLabel('''<a href="http://nuitka.net/doc/developer-manual.html">
            <small><center> Nuitka Developer Documentation On Line HTML </a>''')
             ):
            vboxg10.addWidget(each_widget)
            each_widget.setOpenExternalLinks(True)
            each_widget.setTextInteractionFlags(Qt.LinksAccessibleByMouse)

        [a.setChecked(True) for a in (self.ckgrl1, self.ckgrl2, self.ckgrl4,
            self.ckgrl5, self.ckgrl6, self.ckgrl7, self.ckgrl8, self.ckrec0,
            self.ckrec1, self.ckrec2, self.ckexe1, self.ckcgn2, self.ckdbg1,
            self.ckdbg3, self.ckdbg4, self.ckdbg5, self.cktrc1, self.cktrc2,
            self.cktrc3, self.ckxtr1, self.ckxtr2, self.ckxtr3,)]

        self.button = QPushButton(QIcon.fromTheme("face-cool"),
                                  'Compile Python')
        self.button.setCursor(QCursor(Qt.PointingHandCursor))
        self.button.setMinimumSize(100, 50)
        self.button.clicked.connect(self.run)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.button.setGraphicsEffect(glow)

        class TransientWidget(QWidget):
            ' persistant widget thingy '
            def __init__(self, widget_list):
                ' init sub class '
                super(TransientWidget, self).__init__()
                vbox = QVBoxLayout(self)
                for each_widget in widget_list:
                    vbox.addWidget(each_widget)

        tw = TransientWidget((
            QLabel('<b>Python Code to Binary Executable Compiler'), self.group0,
            self.group6, self.group1, self.group2, self.group3, self.group4,
            self.group5, self.group7, self.group8, self.group9, self.group10,
            self.button, ))
        self.scrollable, self.dock = QScrollArea(), QDockWidget()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(tw)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        ExplorerContainer().addTab(self.dock, "Nuitka")
        QPushButton(QIcon.fromTheme("help-about"), 'About', self.dock
          ).clicked.connect(lambda: QMessageBox.information(self.dock, __doc__,
            HELPMSG))

    def run(self):
        ' run the compile '
        target = path.abspath(str(self.infile.text()).strip())
        self.button.setDisabled(True)
        self.output.clear()
        self.output.show()
        self.output.setFocus()
        self.output.append(self.formatInfoMsg('INFO:{}'.format(datetime.now())))
        self.output.append(self.formatInfoMsg(' INFO: Dumping Internal Tree'))
        try:
            self.dumptree.setPlainText(
                getoutput('nuitka --dump-tree {}'.format(target)))
            self.dumptree.setMinimumSize(100, 500)
        except:
            self.output.append(self.formatErrorMsg('ERROR:FAIL: Internal Tree'))
        self.output.append(self.formatInfoMsg(' INFO: OK: Parsing Arguments'))
        cmd = ' '.join(('nice --adjustment={} nuitka'.format(self.nice.value()),

            # output
            '--remove-output' if self.ckcgn2.isChecked() is True else '',

            # general
            '--exe' if self.ckgrl1.isChecked() is True else '',
            '--python-debug' if self.ckgrl2.isChecked() is True else '',
            '--verbose' if self.cktrc3.isChecked() is True else '',
            '--windows-target' if self.ckgrl3.isChecked() is True else '',
            '--windows-disable-console' if self.ckgrl4.isChecked() is True else '',
            '--lto' if self.ckgrl5.isChecked() is True else '',
            '--clang' if self.ckgrl6.isChecked() is True else '',
            '--improved' if self.ckgrl7.isChecked() is True else '',
            '--warn-implicit-exceptions' if self.ckgrl8.isChecked() is True else '',

            # recursion control
            '--recurse-stdlib' if self.ckrec0.isChecked() is True else '',
            '--recurse-none' if self.ckrec1.isChecked() is True else '',
            '--recurse-all' if self.ckrec2.isChecked() is True else '',

            # execution after compilation
            '--execute' if self.ckexe0.isChecked() is True else '',
            '--keep-pythonpath' if self.ckexe1.isChecked() is True else '',

            # code generation
            '--code-gen-no-statement-lines' if self.chdmp1.isChecked() is True else '',
            '--no-optimization' if self.chdmp2.isChecked() is True else '',

            # debug
            '--debug' if self.ckdbg1.isChecked() is True else '',
            '--unstripped' if self.ckdbg2.isChecked() is True else '',
            '--trace-execution' if self.ckdbg3.isChecked() is True else '',
            '--c++-only' if self.ckdbg4.isChecked() is True else '',
            '--experimental' if self.ckdbg5.isChecked() is True else '',

            # tracing
            '--show-scons' if self.cktrc1.isChecked() is True else '',
            '--show-progress' if self.cktrc2.isChecked() is True else '',
            '--verbose' if self.cktrc3.isChecked() is True else '',

            # non boolean parametrization
            '--python-version={}'.format(self.pyver.currentText()),
            '--jobs={}'.format(self.jobs.value()),
            '--output-dir="{}"'.format(self.outdir.text()),
            target))
        self.output.append(self.formatInfoMsg(' INFO: Command: {}'.format(cmd)))
        self.output.append(self.formatInfoMsg(' INFO: OK: Starting to Compile'))
        self.process.start(cmd)
        if not self.process.waitForStarted():
            self.output.append(self.formatErrorMsg('ERROR: FAIL: Compile Fail'))
            self.output.append(self.formatErrorMsg('ERROR:FAIL:{}'.format(cmd)))
            self.button.setEnabled(True)
            return
        # write a .sh bash script file on target
        if self.ckxtr3.isChecked() is True:
            sh_file = 'nuitka_compile_python_to_cpp.sh'
            with open(path.join(str(self.outdir.text()), sh_file), 'w') as _sh:
                self.output.append(self.formatInfoMsg('''INFO: OK: Writing Bash:
                    {}'''.format(sh_file)))
                _sh.write('#!/usr/bin/env bash {}{}'.format(linesep, cmd))
                _sh.close()
            self.output.append(self.formatInfoMsg('INFO: OK: Bash chmod: 775'))
            try:
                chmod(path.join(str(self.outdir.text()), sh_file), 0775)  # Py2
            except:
                chmod(path.join(str(self.outdir.text()), sh_file), 0o775)  # Py3

    def _process_finished(self):
        """sphinx-build finished sucessfully"""
        self.output.append(self.formatInfoMsg('INFO:{}'.format(datetime.now())))
        if self.ckxtr2.isChecked() is True:
            log_file = 'nuitka_ninja.log'
            with open(path.join(str(self.outdir.text()), log_file), 'w') as log:
                self.output.append(self.formatInfoMsg('''INFO: OK: Writing LOG:
                    {}'''.format(log_file)))
                log.write(self.output.toPlainText())
        if self.ckxtr1.isChecked() is True:
            try:
                startfile(path.abspath(str(self.outdir.text())))
            except:
                Popen(["xdg-open", path.abspath(str(self.outdir.text()))])
        self.button.setDisabled(False)
        self.output.show()
        self.output.setFocus()
        self.output.selectAll()

    def toggle_gral_group(self):
        ' toggle on or off the checkboxes '
        if self.group1.isChecked() is True:
            [a.setChecked(True) for a in (self.ckgrl1, self.ckgrl2, self.ckgrl4,
            self.ckgrl5, self.ckgrl6, self.ckgrl7, self.ckgrl8)]
            self.group1.graphicsEffect().setEnabled(False)
        else:
            [a.setChecked(False) for a in (self.ckgrl1, self.ckgrl2,
            self.ckgrl4, self.ckgrl5, self.ckgrl6, self.ckgrl7, self.ckgrl8)]
            self.group1.graphicsEffect().setEnabled(True)

    def readOutput(self):
        """Read and append sphinx-build output to the logBrowser"""
        self.output.append(str(self.process.readAllStandardOutput()))

    def readErrors(self):
        """Read and append sphinx-build errors to the logBrowser"""
        self.output.append(self.formatErrorMsg(str(
                                        self.process.readAllStandardError())))

    def formatErrorMsg(self, msg):
        """Format error messages in red color"""
        return self.formatMsg(msg, 'red')

    def formatInfoMsg(self, msg):
        """Format informative messages in blue color"""
        return self.formatMsg(msg, 'green')

    def formatMsg(self, msg, color):
        """Format message with the given color"""
        return '<font color="{}">{}</font>'.format(color, msg)
Ejemplo n.º 20
0
    def setupUi(self, Lekhonee):
        Lekhonee.setObjectName("Lekhonee")
        Lekhonee.resize(1001, 586)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(":/pixmaps/lekhonee.png"),
                       QtGui.QIcon.Normal, QtGui.QIcon.Off)
        Lekhonee.setWindowIcon(icon)
        self.centralwidget = QtGui.QWidget(Lekhonee)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout_5 = QtGui.QGridLayout(self.centralwidget)
        self.gridLayout_5.setObjectName("gridLayout_5")
        self.verticalLayout = QtGui.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.hboxlayout = QtGui.QHBoxLayout()
        self.hboxlayout.setObjectName("hboxlayout")
        self.label = QtGui.QLabel(self.centralwidget)
        self.label.setObjectName("label")
        self.hboxlayout.addWidget(self.label)
        self.titleTxt = QtGui.QLineEdit(self.centralwidget)
        self.titleTxt.setObjectName("titleTxt")
        self.hboxlayout.addWidget(self.titleTxt)
        self.commentCheckBox = QtGui.QCheckBox(self.centralwidget)
        self.commentCheckBox.setChecked(True)
        self.commentCheckBox.setObjectName("commentCheckBox")
        self.hboxlayout.addWidget(self.commentCheckBox)
        self.verticalLayout.addLayout(self.hboxlayout)
        self.hboxlayout1 = QtGui.QHBoxLayout()
        self.hboxlayout1.setObjectName("hboxlayout1")
        self.boldBttn = QtGui.QPushButton(self.centralwidget)
        font = QtGui.QFont()
        font.setWeight(75)
        font.setBold(True)
        self.boldBttn.setFont(font)
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap(":/icons/bold.png"), QtGui.QIcon.Normal,
                        QtGui.QIcon.Off)
        self.boldBttn.setIcon(icon1)
        self.boldBttn.setIconSize(QtCore.QSize(20, 20))
        self.boldBttn.setObjectName("boldBttn")
        self.hboxlayout1.addWidget(self.boldBttn)
        self.italicBttn = QtGui.QPushButton(self.centralwidget)
        font = QtGui.QFont()
        font.setWeight(50)
        font.setItalic(True)
        font.setBold(False)
        self.italicBttn.setFont(font)
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap(":/icons/italic.png"),
                        QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.italicBttn.setIcon(icon2)
        self.italicBttn.setIconSize(QtCore.QSize(20, 20))
        self.italicBttn.setObjectName("italicBttn")
        self.hboxlayout1.addWidget(self.italicBttn)
        self.linkBttn = QtGui.QPushButton(self.centralwidget)
        self.linkBttn.setObjectName("linkBttn")
        self.hboxlayout1.addWidget(self.linkBttn)
        self.imageBttn = QtGui.QPushButton(self.centralwidget)
        icon3 = QtGui.QIcon()
        icon3.addPixmap(QtGui.QPixmap(":/icons/insert-image.png"),
                        QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.imageBttn.setIcon(icon3)
        self.imageBttn.setIconSize(QtCore.QSize(20, 20))
        self.imageBttn.setObjectName("imageBttn")
        self.hboxlayout1.addWidget(self.imageBttn)
        spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding,
                                       QtGui.QSizePolicy.Minimum)
        self.hboxlayout1.addItem(spacerItem)
        self.oldPostBttn = QtGui.QPushButton(self.centralwidget)
        self.oldPostBttn.setCheckable(True)
        self.oldPostBttn.setObjectName("oldPostBttn")
        self.hboxlayout1.addWidget(self.oldPostBttn)
        self.stateBttn = QtGui.QPushButton(self.centralwidget)
        self.stateBttn.setObjectName("stateBttn")
        self.hboxlayout1.addWidget(self.stateBttn)
        self.verticalLayout.addLayout(self.hboxlayout1)
        self.stack = QtGui.QStackedWidget(self.centralwidget)
        self.stack.setObjectName("stack")
        self.page = QtGui.QWidget()
        self.page.setObjectName("page")
        self.gridLayout = QtGui.QGridLayout(self.page)
        self.gridLayout.setObjectName("gridLayout")
        self.blogTxt = KTextEdit(self.page)
        self.blogTxt.setObjectName("blogTxt")
        self.gridLayout.addWidget(self.blogTxt, 0, 0, 1, 1)
        self.stack.addWidget(self.page)
        self.page_2 = QtGui.QWidget()
        self.page_2.setObjectName("page_2")
        self.gridLayout_2 = QtGui.QGridLayout(self.page_2)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.webView = QtWebKit.QWebView(self.page_2)
        self.webView.setUrl(QtCore.QUrl("about:blank"))
        self.webView.setObjectName("webView")
        self.gridLayout_2.addWidget(self.webView, 0, 0, 1, 1)
        self.stack.addWidget(self.page_2)
        self.page_3 = QtGui.QWidget()
        self.page_3.setObjectName("page_3")
        self.gridLayout_4 = QtGui.QGridLayout(self.page_3)
        self.gridLayout_4.setObjectName("gridLayout_4")
        self.entryList = QtGui.QListWidget(self.page_3)
        self.entryList.setObjectName("entryList")
        self.gridLayout_4.addWidget(self.entryList, 0, 0, 1, 1)
        self.stack.addWidget(self.page_3)
        self.verticalLayout.addWidget(self.stack)
        self.uploadframe = QtGui.QFrame(self.centralwidget)
        self.uploadframe.setFrameShape(QtGui.QFrame.StyledPanel)
        self.uploadframe.setFrameShadow(QtGui.QFrame.Plain)
        self.uploadframe.setObjectName("uploadframe")
        self.gridLayout_3 = QtGui.QGridLayout(self.uploadframe)
        self.gridLayout_3.setObjectName("gridLayout_3")
        self.horizontalLayout_3 = QtGui.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.fileTxt = QtGui.QLineEdit(self.uploadframe)
        self.fileTxt.setObjectName("fileTxt")
        self.horizontalLayout_3.addWidget(self.fileTxt)
        self.selectUploadBttn = QtGui.QPushButton(self.uploadframe)
        self.selectUploadBttn.setObjectName("selectUploadBttn")
        self.horizontalLayout_3.addWidget(self.selectUploadBttn)
        self.gridLayout_3.addLayout(self.horizontalLayout_3, 0, 0, 1, 1)
        self.horizontalLayout_2 = QtGui.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.uploadCancelBttn = QtGui.QPushButton(self.uploadframe)
        self.uploadCancelBttn.setObjectName("uploadCancelBttn")
        self.horizontalLayout_2.addWidget(self.uploadCancelBttn)
        spacerItem1 = QtGui.QSpacerItem(328, 20, QtGui.QSizePolicy.Expanding,
                                        QtGui.QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem1)
        self.uploadBttn = QtGui.QPushButton(self.uploadframe)
        self.uploadBttn.setObjectName("uploadBttn")
        self.horizontalLayout_2.addWidget(self.uploadBttn)
        self.gridLayout_3.addLayout(self.horizontalLayout_2, 1, 0, 1, 1)
        self.verticalLayout.addWidget(self.uploadframe)
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.spellCheckBox = QtGui.QCheckBox(self.centralwidget)
        self.spellCheckBox.setObjectName("spellCheckBox")
        self.horizontalLayout.addWidget(self.spellCheckBox)
        self.tagsTxt = QtGui.QLineEdit(self.centralwidget)
        self.tagsTxt.setObjectName("tagsTxt")
        self.horizontalLayout.addWidget(self.tagsTxt)
        spacerItem2 = QtGui.QSpacerItem(38, 28, QtGui.QSizePolicy.Expanding,
                                        QtGui.QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem2)
        self.draftBttn = QtGui.QPushButton(self.centralwidget)
        icon4 = QtGui.QIcon()
        icon4.addPixmap(QtGui.QPixmap(":/icons/draft.png"), QtGui.QIcon.Normal,
                        QtGui.QIcon.Off)
        self.draftBttn.setIcon(icon4)
        self.draftBttn.setIconSize(QtCore.QSize(20, 20))
        self.draftBttn.setObjectName("draftBttn")
        self.horizontalLayout.addWidget(self.draftBttn)
        self.publishBttn = QtGui.QPushButton(self.centralwidget)
        icon5 = QtGui.QIcon()
        icon5.addPixmap(QtGui.QPixmap(":/icons/internet.png"),
                        QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.publishBttn.setIcon(icon5)
        self.publishBttn.setIconSize(QtCore.QSize(20, 20))
        self.publishBttn.setObjectName("publishBttn")
        self.horizontalLayout.addWidget(self.publishBttn)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.gridLayout_5.addLayout(self.verticalLayout, 0, 0, 1, 1)
        self.vboxlayout = QtGui.QVBoxLayout()
        self.vboxlayout.setObjectName("vboxlayout")
        spacerItem3 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum,
                                        QtGui.QSizePolicy.Fixed)
        self.vboxlayout.addItem(spacerItem3)
        self.label_2 = QtGui.QLabel(self.centralwidget)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed,
                                       QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.label_2.sizePolicy().hasHeightForWidth())
        self.label_2.setSizePolicy(sizePolicy)
        self.label_2.setObjectName("label_2")
        self.vboxlayout.addWidget(self.label_2)
        self.categoryList = QtGui.QListWidget(self.centralwidget)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred,
                                       QtGui.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.categoryList.sizePolicy().hasHeightForWidth())
        self.categoryList.setSizePolicy(sizePolicy)
        self.categoryList.setSelectionMode(
            QtGui.QAbstractItemView.MultiSelection)
        self.categoryList.setObjectName("categoryList")
        self.vboxlayout.addWidget(self.categoryList)
        self.getCategoriesBttn = QtGui.QPushButton(self.centralwidget)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred,
                                       QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.getCategoriesBttn.sizePolicy().hasHeightForWidth())
        self.getCategoriesBttn.setSizePolicy(sizePolicy)
        icon6 = QtGui.QIcon()
        icon6.addPixmap(QtGui.QPixmap(":/icons/get-arrow.png"),
                        QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.getCategoriesBttn.setIcon(icon6)
        self.getCategoriesBttn.setIconSize(QtCore.QSize(20, 20))
        self.getCategoriesBttn.setObjectName("getCategoriesBttn")
        self.vboxlayout.addWidget(self.getCategoriesBttn)
        self.addCategoryTxt = QtGui.QLineEdit(self.centralwidget)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred,
                                       QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.addCategoryTxt.sizePolicy().hasHeightForWidth())
        self.addCategoryTxt.setSizePolicy(sizePolicy)
        self.addCategoryTxt.setObjectName("addCategoryTxt")
        self.vboxlayout.addWidget(self.addCategoryTxt)
        self.addCategoryBttn = QtGui.QPushButton(self.centralwidget)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred,
                                       QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.addCategoryBttn.sizePolicy().hasHeightForWidth())
        self.addCategoryBttn.setSizePolicy(sizePolicy)
        self.addCategoryBttn.setObjectName("addCategoryBttn")
        self.vboxlayout.addWidget(self.addCategoryBttn)
        self.gridLayout_5.addLayout(self.vboxlayout, 0, 1, 1, 1)
        self.serverTabs = QtGui.QTabWidget(self.centralwidget)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,
                                       QtGui.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.serverTabs.sizePolicy().hasHeightForWidth())
        self.serverTabs.setSizePolicy(sizePolicy)
        self.serverTabs.setObjectName("serverTabs")
        self.tab = QtGui.QWidget()
        self.tab.setObjectName("tab")
        self.gridLayout_6 = QtGui.QGridLayout(self.tab)
        self.gridLayout_6.setObjectName("gridLayout_6")
        self.addPageBttn = QtGui.QPushButton(self.tab)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed,
                                       QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.addPageBttn.sizePolicy().hasHeightForWidth())
        self.addPageBttn.setSizePolicy(sizePolicy)
        icon7 = QtGui.QIcon()
        icon7.addPixmap(QtGui.QPixmap(":/icons/addpage.png"),
                        QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.addPageBttn.setIcon(icon7)
        self.addPageBttn.setIconSize(QtCore.QSize(20, 20))
        self.addPageBttn.setObjectName("addPageBttn")
        self.gridLayout_6.addWidget(self.addPageBttn, 0, 0, 1, 1)
        self.serverTabs.addTab(self.tab, "")
        self.tab_2 = QtGui.QWidget()
        self.tab_2.setObjectName("tab_2")
        self.serverTabs.addTab(self.tab_2, "")
        self.gridLayout_5.addWidget(self.serverTabs, 1, 0, 1, 1)
        Lekhonee.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(Lekhonee)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1001, 28))
        self.menubar.setObjectName("menubar")
        self.menu_File = QtGui.QMenu(self.menubar)
        self.menu_File.setObjectName("menu_File")
        self.menu_Edit = QtGui.QMenu(self.menubar)
        self.menu_Edit.setObjectName("menu_Edit")
        self.menuHTML_Tags = QtGui.QMenu(self.menubar)
        self.menuHTML_Tags.setObjectName("menuHTML_Tags")
        Lekhonee.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(Lekhonee)
        self.statusbar.setObjectName("statusbar")
        Lekhonee.setStatusBar(self.statusbar)
        self.action_Open = QtGui.QAction(Lekhonee)
        icon8 = QtGui.QIcon()
        icon8.addPixmap(QtGui.QPixmap(":/icons/document-open.png"),
                        QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.action_Open.setIcon(icon8)
        self.action_Open.setObjectName("action_Open")
        self.action_Save = QtGui.QAction(Lekhonee)
        icon9 = QtGui.QIcon()
        icon9.addPixmap(QtGui.QPixmap(":/icons/document-save.png"),
                        QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.action_Save.setIcon(icon9)
        self.action_Save.setObjectName("action_Save")
        self.actionBold = QtGui.QAction(Lekhonee)
        self.actionBold.setIcon(icon1)
        self.actionBold.setObjectName("actionBold")
        self.actionItalic = QtGui.QAction(Lekhonee)
        self.actionItalic.setIcon(icon2)
        self.actionItalic.setObjectName("actionItalic")
        self.actionUnderline = QtGui.QAction(Lekhonee)
        icon10 = QtGui.QIcon()
        icon10.addPixmap(QtGui.QPixmap(":/icons/underline.png"),
                         QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionUnderline.setIcon(icon10)
        self.actionUnderline.setObjectName("actionUnderline")
        self.actionSuperscript = QtGui.QAction(Lekhonee)
        icon11 = QtGui.QIcon()
        icon11.addPixmap(QtGui.QPixmap(":/icons/superscript.png"),
                         QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionSuperscript.setIcon(icon11)
        self.actionSuperscript.setObjectName("actionSuperscript")
        self.actionSubscript = QtGui.QAction(Lekhonee)
        icon12 = QtGui.QIcon()
        icon12.addPixmap(QtGui.QPixmap(":/icons/subscript.png"),
                         QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionSubscript.setIcon(icon12)
        self.actionSubscript.setObjectName("actionSubscript")
        self.actionInsert_Image = QtGui.QAction(Lekhonee)
        self.actionInsert_Image.setIcon(icon3)
        self.actionInsert_Image.setObjectName("actionInsert_Image")
        self.actionInsert_link = QtGui.QAction(Lekhonee)
        self.actionInsert_link.setObjectName("actionInsert_link")
        self.actionIn_FireFox = QtGui.QAction(Lekhonee)
        self.actionIn_FireFox.setObjectName("actionIn_FireFox")
        self.actionIn_Konqueror = QtGui.QAction(Lekhonee)
        icon13 = QtGui.QIcon()
        icon13.addPixmap(QtGui.QPixmap(":/icons/konqueror.png"),
                         QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionIn_Konqueror.setIcon(icon13)
        self.actionIn_Konqueror.setObjectName("actionIn_Konqueror")
        self.actionPrevious_Entries = QtGui.QAction(Lekhonee)
        self.actionPrevious_Entries.setEnabled(False)
        self.actionPrevious_Entries.setObjectName("actionPrevious_Entries")
        self.actionPreferences = QtGui.QAction(Lekhonee)
        icon14 = QtGui.QIcon()
        icon14.addPixmap(QtGui.QPixmap(":/icons/configure.png"),
                         QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionPreferences.setIcon(icon14)
        self.actionPreferences.setObjectName("actionPreferences")
        self.action_Quit = QtGui.QAction(Lekhonee)
        icon15 = QtGui.QIcon()
        icon15.addPixmap(QtGui.QPixmap(":/icons/application-exit.png"),
                         QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.action_Quit.setIcon(icon15)
        self.action_Quit.setObjectName("action_Quit")
        self.action_New = QtGui.QAction(Lekhonee)
        icon16 = QtGui.QIcon()
        icon16.addPixmap(QtGui.QPixmap(":/icons/document-new.png"),
                         QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.action_New.setIcon(icon16)
        self.action_New.setObjectName("action_New")
        self.action_Help = QtGui.QAction(Lekhonee)
        self.action_Help.setEnabled(False)
        self.action_Help.setObjectName("action_Help")
        self.actionAbout_Chotha = QtGui.QAction(Lekhonee)
        icon17 = QtGui.QIcon()
        icon17.addPixmap(
            QtGui.QPixmap("../../../../../../usr/share/pixmaps/chotha.png"),
            QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionAbout_Chotha.setIcon(icon17)
        self.actionAbout_Chotha.setObjectName("actionAbout_Chotha")
        self.actionLast_Entry = QtGui.QAction(Lekhonee)
        self.actionLast_Entry.setObjectName("actionLast_Entry")
        self.actionLekhonee_msg = QtGui.QAction(Lekhonee)
        self.actionLekhonee_msg.setCheckable(True)
        self.actionLekhonee_msg.setChecked(True)
        self.actionLekhonee_msg.setObjectName("actionLekhonee_msg")
        self.actionOld_Posts = QtGui.QAction(Lekhonee)
        self.actionOld_Posts.setObjectName("actionOld_Posts")
        self.actionUpload_File = QtGui.QAction(Lekhonee)
        self.actionUpload_File.setObjectName("actionUpload_File")
        self.menu_File.addAction(self.action_New)
        self.menu_File.addAction(self.action_Open)
        self.menu_File.addAction(self.action_Save)
        self.menu_File.addAction(self.action_Quit)
        self.menu_Edit.addAction(self.actionLast_Entry)
        self.menu_Edit.addAction(self.actionLekhonee_msg)
        self.menu_Edit.addAction(self.actionUpload_File)
        self.menu_Edit.addAction(self.actionPreferences)
        self.menuHTML_Tags.addAction(self.actionBold)
        self.menuHTML_Tags.addAction(self.actionItalic)
        self.menuHTML_Tags.addAction(self.actionUnderline)
        self.menuHTML_Tags.addSeparator()
        self.menuHTML_Tags.addAction(self.actionSuperscript)
        self.menuHTML_Tags.addAction(self.actionSubscript)
        self.menuHTML_Tags.addSeparator()
        self.menuHTML_Tags.addAction(self.actionInsert_Image)
        self.menuHTML_Tags.addAction(self.actionInsert_link)
        self.menubar.addAction(self.menu_File.menuAction())
        self.menubar.addAction(self.menu_Edit.menuAction())
        self.menubar.addAction(self.menuHTML_Tags.menuAction())

        self.retranslateUi(Lekhonee)
        self.stack.setCurrentIndex(0)
        self.serverTabs.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(Lekhonee)
        Lekhonee.setTabOrder(self.titleTxt, self.commentCheckBox)
        Lekhonee.setTabOrder(self.commentCheckBox, self.publishBttn)
        Lekhonee.setTabOrder(self.publishBttn, self.draftBttn)
        Lekhonee.setTabOrder(self.draftBttn, self.boldBttn)
        Lekhonee.setTabOrder(self.boldBttn, self.italicBttn)
        Lekhonee.setTabOrder(self.italicBttn, self.linkBttn)
        Lekhonee.setTabOrder(self.linkBttn, self.stateBttn)
        Lekhonee.setTabOrder(self.stateBttn, self.categoryList)
Ejemplo n.º 21
0
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        ec = ExplorerContainer()
        super(Main, self).initialize(*args, **kwargs)
        # directory auto completer
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        self.RUNS, self.FAILS = 0, 0
        self.group0 = QGroupBox()
        self.group0.setTitle(' Source and Target ')
        self.baseurl = QLineEdit('http://google.com')
        self.outfile = QLineEdit(path.join(path.expanduser("~"), 'test.py'))
        self.outfile.setCompleter(self.completer)
        self.open = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open.clicked.connect(lambda: self.outfile.setText(
            QFileDialog.getSaveFileName(self.dock, "Save", path.expanduser(
                "~"), 'PYTHON(*.py)')))
        vboxg0 = QVBoxLayout(self.group0)
        for each_widget in (QLabel('<b>Base URL'), self.baseurl,
                            QLabel('<b>Local File Target'), self.outfile,
                            self.open):
            vboxg0.addWidget(each_widget)

        self.group1 = QGroupBox()
        self.group1.setTitle(' Selenium ')
        self.group1.setCheckable(True)
        self.group1.setGraphicsEffect(QGraphicsBlurEffect(self))
        self.group1.graphicsEffect().setEnabled(False)
        self.group1.toggled.connect(self.toggle_group)
        self.ckcss1 = QCheckBox('Test for correct Page Loading behaviour')
        self.ckcss2 = QCheckBox('Test for Sucessfull Status Code return')
        self.ckcss3 = QCheckBox('Test for valid Title of the web page')
        self.ckcss4 = QCheckBox('Test for Cookies Basic functionality')
        self.ckcss5 = QCheckBox('Test for Back, Forward, Reload behaviour')
        self.ckcss6 = QCheckBox('Take a Screenshot of page (CSS Debug)')
        self.ckcss7 = QCheckBox('Test for Search Form Field of the page')
        self.ckcss8 = QCheckBox(
            'Test for Arbitrary Javascript (User provided)')
        self.ckcss9 = QCheckBox('Test for iFrame of the web page')
        self.ckcss10 = QCheckBox('Test for HTML5 Canvas element on the page')
        self.ckcss11 = QCheckBox('Test for HTML5 SVG element on the page')
        self.ckcss12 = QCheckBox('Test for HTML5 Audio element on the page')
        self.ckcss13 = QCheckBox('Test for HTML5 Video element on the page')
        self.ckcss14 = QCheckBox('Test for File Upload form on the page')
        self.ckcss15 = QCheckBox('Add ChromeDriver path to sys.path')
        self.webdriver = QComboBox()
        self.webdriver.addItems(
            ['firefox', 'chrome', 'zope.testbrowser', 'phantomjs'])
        self.titletxt = QLineEdit('Google')
        self.javascript = QLineEdit('console.log("test")')
        self.authdata, self.formdata = QLineEdit(), QLineEdit()
        self.authdata.setPlaceholderText(
            "{'username':'******','password':'******'}")
        self.formdata.setPlaceholderText("{'name': 'Joe', 'age': '25'}")
        self.iframurl = QLineEdit()
        self.chrmedrv = QLineEdit('/usr/bin/chromedriver')
        self.timeout = QSpinBox()
        self.timeout.setMaximum(99)
        self.timeout.setMinimum(0)
        self.timeout.setValue(9)
        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (
                self.ckcss1, self.ckcss2, self.ckcss3, self.ckcss4,
                self.ckcss5, self.ckcss6, self.ckcss7, self.ckcss8,
                self.ckcss9, self.ckcss10, self.ckcss11,
                self.ckcss12, self.ckcss13, self.ckcss14, self.ckcss15,
                QLabel('<b>WebDriver'), self.webdriver,
                QLabel('''<center><small><i>Firefox is only Driver that dont
                   require additional configuration'''),
                QLabel('<b>Title Content must contain'), self.titletxt,
                QLabel('<b>Minified Javascript for Test'), self.javascript,
                QLabel('<b>Arbitrary Authentication Data for Test'),
                self.authdata, QLabel('<b>Arbitrary Form Data for Test'),
                self.formdata, QLabel('<b>iFrame URL for Test'), self.iframurl,
                QLabel('<b>Chrome Driver'), self.chrmedrv,
                QLabel('<b>Timeout Timer Limit'), self.timeout):
            vboxg1.addWidget(each_widget)
            try:
                each_widget.setToolTip(each_widget.text())
            except:
                each_widget.setToolTip(each_widget.currentText())

        self.group4 = QGroupBox()
        self.group4.setTitle(' General ')
        self.chckbx1 = QCheckBox('Run the Tests after Writing')
        self.chckbx2 = QCheckBox('Open the Tests with Ninja after Writing')
        self.chckbx3 = QCheckBox('Add SheBang, Encoding and Metadata to Tests')
        self.nice = QSpinBox()
        self.nice.setMaximum(20)
        self.nice.setMinimum(0)
        self.nice.setValue(20)
        self.help1 = QLabel(
            '''<a href="http://splinter.cobrateam.info/docs/api"
            ><center><b>API Reference</a>''')
        self.help1.setTextInteractionFlags(Qt.LinksAccessibleByMouse)
        self.help1.setOpenExternalLinks(True)
        vboxg4 = QVBoxLayout(self.group4)
        for each_widget in (self.chckbx1, self.chckbx2, self.chckbx3,
                            QLabel('Backend CPU priority:'), self.nice,
                            self.help1):
            vboxg4.addWidget(each_widget)
            each_widget.setToolTip(each_widget.text())

        [
            a.setChecked(True)
            for a in (self.ckcss1, self.ckcss2, self.ckcss3, self.ckcss4,
                      self.ckcss5, self.ckcss6, self.ckcss7, self.ckcss8,
                      self.ckcss15, self.chckbx1, self.chckbx2, self.chckbx3)
        ]

        self.button = QPushButton(QIcon.fromTheme("face-cool"),
                                  'Write and Run Test')
        self.button.setCursor(QCursor(Qt.PointingHandCursor))
        self.button.setMinimumSize(100, 50)
        self.button.clicked.connect(self.run)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.button.setGraphicsEffect(glow)
        glow.setEnabled(True)
        self.output = QPlainTextEdit()
        self.runs = QLabel('<font color="green"><b>Runs: 0')
        self.failures = QLabel('<font color="red"><b>Failures: 0')

        class TransientWidget(QWidget):
            ' persistant widget thingy '

            def __init__(self, widget_list):
                ' init sub class '
                super(TransientWidget, self).__init__()
                vbox = QVBoxLayout(self)
                for each_widget in widget_list:
                    vbox.addWidget(each_widget)

        tw = TransientWidget(
            (QLabel('<b>Selenium Tests'), self.group0, self.group1,
             self.group4, QLabel('<b>Log'), self.output, self.runs,
             self.failures, self.button))
        self.scrollable, self.dock = QScrollArea(), QDockWidget()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(tw)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        ec.addTab(self.dock, "Selenium")
        QPushButton(
            QIcon.fromTheme("help-about"), 'About', self.dock).clicked.connect(
                lambda: QMessageBox.information(self.dock, __doc__, HELPMSG))
        QPushButton(
            QIcon.fromTheme("media-record"),
            'Record',
            self.group1,
        ).clicked.connect(lambda: QMessageBox.information(
            self.dock, __doc__,
            'Not working. If you know how to make it Record, send me Pull Request'
        ))
    def __init__(self, AUTO):
        ' Initialize QWidget inside MyMainWindow '
        super(MyMainWindow, self).__init__()
        QWidget.__init__(self)
        self.auto = AUTO
        self.statusBar().showMessage('               {}'.format(__doc__))
        self.setStyleSheet('QStatusBar{color:grey;}')
        self.setWindowTitle(__doc__)
        self.setWindowIcon(QIcon.fromTheme("face-monkey"))
        self.setFont(QFont('Ubuntu Light', 10))
        self.setMaximumSize(QDesktopWidget().screenGeometry().width(),
                            QDesktopWidget().screenGeometry().height())

        self.base = path.abspath(path.join(getcwd(), str(datetime.now().year)))

        # directory auto completer
        self.completer = QCompleter(self)
        self.dirs = QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)

        # process
        self.process1 = None
        self.process2 = None
        self.cmd1 = 'nice -n {n} arecord{v} -f {f} -c {c} -r {b} -t raw'
        self.cmd2 = 'oggenc - -r -C {c} -R {b} -q {q} {d}{t}{a} -o {o}'
        self.process3 = QProcess(self)
        #self.process3.finished.connect(self.on_process3_finished)
        #self.process3.error.connect(self.on_process3_error)

        self.cmd3 = ('nice -n 20 ' +
          'sox "{o}" -n spectrogram -x {x} -y {y} -z 99 -t "{o}" -o "{o}.png"')
        self.actual_file = ''

        # re starting timers, one stops, one starts
        self.timerFirst = QTimer(self)
        self.timerFirst.timeout.connect(self.end)
        self.timerSecond = QTimer(self)
        self.timerSecond.timeout.connect(self.run)

        # Proxy support, by reading http_proxy os env variable
        proxy_url = QUrl(environ.get('http_proxy', ''))
        QNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.HttpProxy
            if str(proxy_url.scheme()).startswith('http')
            else QNetworkProxy.Socks5Proxy, proxy_url.host(), proxy_url.port(),
                 proxy_url.userName(), proxy_url.password())) \
            if 'http_proxy' in environ else None
        print((' INFO: Proxy Auto-Config as ' + str(proxy_url)))

        # basic widgets layouts and set up
        self.mainwidget = QTabWidget()
        self.mainwidget.setToolTip(__doc__)
        self.mainwidget.setMovable(True)
        self.mainwidget.setTabShape(QTabWidget.Triangular)
        self.mainwidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.mainwidget.setStyleSheet('QTabBar{color:white;font-weight:bold;}')
        self.mainwidget.setTabBar(TabBar(self))
        self.mainwidget.setTabsClosable(False)
        self.setCentralWidget(self.mainwidget)
        self.dock1 = QDockWidget()
        self.dock2 = QDockWidget()
        self.dock3 = QDockWidget()
        self.dock4 = QDockWidget()
        self.dock5 = QDockWidget()
        for a in (self.dock1, self.dock2, self.dock3, self.dock4, self.dock5):
            a.setWindowModality(Qt.NonModal)
            # a.setWindowOpacity(0.9)
            a.setWindowTitle(__doc__
                             if a.windowTitle() == '' else a.windowTitle())
            a.setStyleSheet('QDockWidget::title{text-align:center;}')
            self.mainwidget.addTab(a, QIcon.fromTheme("face-smile"),
                                   'Double Click Me')

        # Paleta de colores para pintar transparente
        self.palette().setBrush(QPalette.Base, Qt.transparent)
        self.setPalette(self.palette())
        self.setAttribute(Qt.WA_OpaquePaintEvent, False)

        # toolbar and basic actions
        self.toolbar = QToolBar(self)
        self.toolbar.setIconSize(QSize(24, 24))
        # spacer widget for left
        self.left_spacer = QWidget(self)
        self.left_spacer.setSizePolicy(QSizePolicy.Expanding,
                                       QSizePolicy.Expanding)
        # spacer widget for right
        self.right_spacer = QWidget(self)
        self.right_spacer.setSizePolicy(QSizePolicy.Expanding,
                                        QSizePolicy.Expanding)
        qaqq = QAction(QIcon.fromTheme("application-exit"), 'Quit', self)
        qaqq.setShortcut('Ctrl+Q')
        qaqq.triggered.connect(exit)
        qamin = QAction(QIcon.fromTheme("go-down"), 'Minimize', self)
        qamin.triggered.connect(lambda: self.showMinimized())
        qamax = QAction(QIcon.fromTheme("go-up"), 'Maximize', self)
        qanor = QAction(QIcon.fromTheme("view-fullscreen"),
                        'AutoCenter AutoResize', self)
        qanor.triggered.connect(self.center)
        qatim = QAction(QIcon.fromTheme("mail-signed-verified"),
                        'View Date and Time', self)
        qatim.triggered.connect(self.timedate)
        qabug = QAction(QIcon.fromTheme("help-about"), 'Report a Problem', self)
        qabug.triggered.connect(lambda: qabug.setDisabled(True) if not call(
            'xdg-open mailto:' + '*****@*****.**'.decode('rot13'),
            shell=True) else ' ERROR ')
        qamax.triggered.connect(lambda: self.showMaximized())
        qaqt = QAction(QIcon.fromTheme("help-about"), 'About Qt', self)
        qaqt.triggered.connect(lambda: QMessageBox.aboutQt(self))
        qakde = QAction(QIcon.fromTheme("help-about"), 'About KDE', self)
        if KDE:
            qakde.triggered.connect(KHelpMenu(self, "", False).aboutKDE)
        qaslf = QAction(QIcon.fromTheme("help-about"), 'About Self', self)
        if KDE:
            qaslf.triggered.connect(
                                KAboutApplicationDialog(aboutData, self).exec_)
        else:
            qaslf.triggered.connect(lambda: QMessageBox.about(self.mainwidget,
            __doc__, ''.join((__doc__, linesep, 'version ', __version__, ', (',
            __license__, '), by ', __author__, ', ( ', __email__, ' )', linesep
            ))))
        qafnt = QAction(QIcon.fromTheme("tools-check-spelling"),
                        'Set GUI Font', self)
        if KDE:
            font = QFont()
            qafnt.triggered.connect(lambda:
            self.setStyleSheet(''.join((
                '*{font-family:', str(font.toString()), '}'))
                if KFontDialog.getFont(font)[0] == QDialog.Accepted else ''))
        else:
            qafnt.triggered.connect(lambda:
                self.setStyleSheet(''.join(('*{font-family:',
                            str(QFontDialog.getFont()[0].toString()), '}'))))
        qasrc = QAction(QIcon.fromTheme("applications-development"),
                        'View Source Code', self)
        qasrc.triggered.connect(lambda:
                            call('xdg-open {}'.format(__file__), shell=True))
        qakb = QAction(QIcon.fromTheme("input-keyboard"),
                       'Keyboard Shortcuts', self)
        qakb.triggered.connect(lambda: QMessageBox.information(self.mainwidget,
                               'Keyboard Shortcuts', ' Ctrl+Q = Quit '))
        qapic = QAction(QIcon.fromTheme("camera-photo"),
                        'Take a Screenshot', self)
        qapic.triggered.connect(lambda: QPixmap.grabWindow(
            QApplication.desktop().winId()).save(QFileDialog.getSaveFileName(
            self.mainwidget, " Save Screenshot As ...", path.expanduser("~"),
            ';;(*.png) PNG', 'png')))
        qatb = QAction(QIcon.fromTheme("go-top"), 'Toggle ToolBar', self)
        qatb.triggered.connect(lambda: self.toolbar.hide()
                if self.toolbar.isVisible() is True else self.toolbar.show())
        qati = QAction(QIcon.fromTheme("zoom-in"),
                       'Switch ToolBar Icon Size', self)
        qati.triggered.connect(lambda:
            self.toolbar.setIconSize(self.toolbar.iconSize() * 4)
            if self.toolbar.iconSize().width() * 4 == 24
            else self.toolbar.setIconSize(self.toolbar.iconSize() / 4))
        qasb = QAction(QIcon.fromTheme("preferences-other"),
                       'Toggle Tabs Bar', self)
        qasb.triggered.connect(lambda: self.mainwidget.tabBar().hide()
                               if self.mainwidget.tabBar().isVisible() is True
                               else self.mainwidget.tabBar().show())
        qadoc = QAction(QIcon.fromTheme("help-browser"), 'On-line Docs', self)
        qadoc.triggered.connect(lambda: open_new_tab(str(__url__).strip()))
        qapy = QAction(QIcon.fromTheme("help-about"), 'About Python', self)
        qapy.triggered.connect(lambda: open_new_tab('http://python.org/about'))
        qali = QAction(QIcon.fromTheme("help-browser"), 'Read Licence', self)
        qali.triggered.connect(lambda: open_new_tab(__full_licence__))
        qacol = QAction(QIcon.fromTheme("preferences-system"), 'Set GUI Colors',
                        self)
        if KDE:
            color = QColor()
            qacol.triggered.connect(lambda:
                self.setStyleSheet(''.join(('* { background-color: ',
                                            str(color.name()), '}')))
                if KColorDialog.getColor(color, self) else '')
        else:
            qacol.triggered.connect(lambda: self.setStyleSheet(''.join((
                ' * { background-color: ', str(QColorDialog.getColor().name()),
                ' } '))))
        qatit = QAction(QIcon.fromTheme("preferences-system"),
                        'Set the App Window Title', self)
        qatit.triggered.connect(self.seTitle)
        self.toolbar.addWidget(self.left_spacer)
        self.toolbar.addSeparator()
        self.toolbar.addActions((qaqq, qamin, qanor, qamax, qasrc, qakb, qacol,
            qatim, qatb, qafnt, qati, qasb, qatit, qapic, qadoc, qali, qaslf,
            qaqt, qakde, qapy, qabug))
        self.addToolBar(Qt.TopToolBarArea, self.toolbar)
        self.toolbar.addSeparator()
        self.toolbar.addWidget(self.right_spacer)
        # define the menu
        menu = self.menuBar()
        # File menu items
        menu.addMenu('&File').addActions((qaqq, ))
        menu.addMenu('&Window').addActions((qamax, qanor, qamin))
        # Settings menu
        menu.addMenu('&Settings').addActions((qasrc, qacol, qafnt, qatim,
                                              qatb, qati, qasb, qapic))
        # Help menu items
        menu.addMenu('&Help').addActions((qadoc, qakb, qabug, qali,
                                          qaqt, qakde, qapy, qaslf))
        # Tray Icon
        tray = QSystemTrayIcon(QIcon.fromTheme("face-devilish"), self)
        tray.setToolTip(__doc__)
        traymenu = QMenu()
        traymenu.addActions((qamax, qanor, qamin, qaqq))
        tray.setContextMenu(traymenu)
        tray.show()

        def contextMenuRequested(point):
            ' quick and dirty custom context menu '
            menu = QMenu()
            menu.addActions((qaqq, qamin, qanor, qamax, qasrc, qakb, qacol,
                qafnt, qati, qasb, qatb, qatim, qatit, qapic, qadoc, qali,
                qaslf, qaqt, qakde, qapy, qabug))
            menu.exec_(self.mapToGlobal(point))
        self.mainwidget.customContextMenuRequested.connect(contextMenuRequested)

        def must_be_checked(widget_list):
            ' widget tuple passed as argument should be checked as ON '
            for each_widget in widget_list:
                try:
                    each_widget.setChecked(True)
                except:
                    pass

        def must_have_tooltip(widget_list):
            ' widget tuple passed as argument should have tooltips '
            for each_widget in widget_list:
                try:
                    each_widget.setToolTip(each_widget.text())
                except:
                    each_widget.setToolTip(each_widget.currentText())
                finally:
                    each_widget.setCursor(QCursor(Qt.PointingHandCursor))

        def must_autofillbackground(widget_list):
            ' widget tuple passed as argument should have filled background '
            for each_widget in widget_list:
                try:
                    each_widget.setAutoFillBackground(True)
                except:
                    pass

        def must_glow(widget_list):
            ' apply an glow effect to the widget '
            for glow, each_widget in enumerate(widget_list):
                try:
                    if each_widget.graphicsEffect() is None:
                        glow = QGraphicsDropShadowEffect(self)
                        glow.setOffset(0)
                        glow.setBlurRadius(99)
                        glow.setColor(QColor(99, 255, 255))
                        each_widget.setGraphicsEffect(glow)
                        # glow.setEnabled(False)
                        try:
                            each_widget.clicked.connect(lambda:
                            each_widget.graphicsEffect().setEnabled(True)
                            if each_widget.graphicsEffect().isEnabled() is False
                            else each_widget.graphicsEffect().setEnabled(False))
                        except:
                            each_widget.sliderPressed.connect(lambda:
                            each_widget.graphicsEffect().setEnabled(True)
                            if each_widget.graphicsEffect().isEnabled() is False
                            else each_widget.graphicsEffect().setEnabled(False))
                except:
                    pass

        #######################################################################

        # dock 1
        QLabel('<h1 style="color:white;"> Record !</h1>', self.dock1).resize(
               self.dock3.size().width() / 4, 25)
        self.group1 = QGroupBox()
        self.group1.setTitle(__doc__)

        self.spec = QPushButton(self)
        self.spec.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.spec.setMinimumSize(self.spec.size().width(), 250)
        self.spec.setFlat(True)
        self.spec.clicked.connect(self.spectro)

        self.clock = QLCDNumber()
        self.clock.setSegmentStyle(QLCDNumber.Flat)
        self.clock.setMinimumSize(self.clock.size().width(), 50)
        self.clock.setNumDigits(25)
        self.timer1 = QTimer(self)
        self.timer1.timeout.connect(lambda: self.clock.display(
            datetime.now().strftime("%d-%m-%Y %H:%M:%S %p")))
        self.timer1.start(1000)
        self.clock.setToolTip(datetime.now().strftime("%c %x"))
        self.clock.setCursor(QCursor(Qt.CrossCursor))

        self.diskBar = QProgressBar()
        self.diskBar.setMinimum(0)
        self.diskBar.setMaximum(statvfs(HOME).f_blocks *
            statvfs(HOME).f_frsize / 1024 / 1024 / 1024)
        self.diskBar.setValue(statvfs(HOME).f_bfree *
            statvfs(HOME).f_frsize / 1024 / 1024 / 1024)
        self.diskBar.setToolTip(str(statvfs(HOME).f_bfree *
            statvfs(HOME).f_frsize / 1024 / 1024 / 1024) + ' Gigabytes free')

        self.feedback = QPlainTextEdit(''.join(('<center><h3>', __doc__,
            ', version', __version__, __license__, ' <br> by ', __author__,
            ' <i>(Dev)</i>, Radio Comunitaria FM Reconquista <i>(Q.A.)</i><br>',
            'FMReconquista.org.ar & GitHub.com/JuanCarlosPaco/Cinta-Testigo')))

        self.rec = QPushButton(QIcon.fromTheme("media-record"), 'Record')
        self.rec.setMinimumSize(self.rec.size().width(), 50)
        self.rec.clicked.connect(self.go)  # self.run

        self.stop = QPushButton(QIcon.fromTheme("media-playback-stop"), 'Stop')
        self.stop.clicked.connect(self.end)

        self.kill = QPushButton(QIcon.fromTheme("process-stop"), 'Kill')
        self.kill.clicked.connect(self.killer)

        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (
            QLabel('<b style="color:white;"> Spectro'), self.spec,
            QLabel('<b style="color:white;"> Time '), self.clock,
            QLabel('<b style="color:white;"> Disk '), self.diskBar,
            QLabel('<b style="color:white;"> STDOUT + STDIN '), self.feedback,
            QLabel('<b style="color:white;"> Record '), self.rec, self.stop,
            self.kill):
            vboxg1.addWidget(each_widget)

        self.group2 = QGroupBox()
        self.group2.setTitle(__doc__)

        self.slider = QSlider(self)
        self.slid_l = QLabel(self.slider)
        self.slider.setCursor(QCursor(Qt.OpenHandCursor))
        self.slider.sliderPressed.connect(lambda:
                            self.slider.setCursor(QCursor(Qt.ClosedHandCursor)))
        self.slider.sliderReleased.connect(lambda:
                            self.slider.setCursor(QCursor(Qt.OpenHandCursor)))
        self.slider.valueChanged.connect(lambda:
                            self.slider.setToolTip(str(self.slider.value())))
        self.slider.valueChanged.connect(lambda: self.slid_l.setText(
                    '<h2 style="color:white;">{}'.format(self.slider.value())))
        self.slider.setMinimum(10)
        self.slider.setMaximum(99)
        self.slider.setValue(30)
        self.slider.setOrientation(Qt.Vertical)
        self.slider.setTickPosition(QSlider.TicksBothSides)
        self.slider.setTickInterval(2)
        self.slider.setSingleStep(10)
        self.slider.setPageStep(10)

        vboxg2 = QVBoxLayout(self.group2)
        for each_widget in (
            QLabel('<b style="color:white;">MINUTES of recording'), self.slider,
            QLabel('<b style="color:white;"> Default: 30 Min')):
            vboxg2.addWidget(each_widget)

        group3 = QGroupBox()
        group3.setTitle(__doc__)
        try:
            self.label2 = QLabel(getoutput('sox --version', shell=True))
            self.label4 = QLabel(getoutput('arecord --version', shell=1)[:25])
            self.label6 = QLabel(str(getoutput('oggenc --version', shell=True)))
        except:
            print(''' ERROR: No SOX, OGGenc avaliable !
                  ( sudo apt-get install vorbis-tools sox alsa-utils ) ''')
            exit()

        self.button5 = QPushButton(QIcon.fromTheme("audio-x-generic"),
                                   'OGG --> ZIP')
        self.button5.clicked.connect(lambda: make_archive(
            str(QFileDialog.getSaveFileName(self, "Save OGG to ZIP file As...",
            getcwd(), ';;(*.zip)', 'zip')).replace('.zip', ''), "zip",
            path.abspath(path.join(getcwd(), str(datetime.now().year)))))

        self.button1 = QPushButton(QIcon.fromTheme("folder-open"), 'Files')
        self.button1.clicked.connect(lambda:
                                     call('xdg-open ' + getcwd(), shell=True))

        self.button0 = QPushButton(
            QIcon.fromTheme("preferences-desktop-screensaver"), 'LCD OFF')
        self.button0.clicked.connect(lambda:
            call('sleep 3 ; xset dpms force off', shell=True))

        vboxg3 = QVBoxLayout(group3)
        for each_widget in (
            QLabel('<b style="color:white;"> OGG Output Codec '), self.label6,
            QLabel('<b style="color:white;"> Raw Record Backend '), self.label4,
            QLabel('<b style="color:white;"> Helper Libs '), self.label2,
            QLabel('<b style="color:white;"> OGG ZIP '), self.button5,
            QLabel('<b style="color:white;"> Files '), self.button1,
            QLabel('<b style="color:white;"> LCD '), self.button0):
            vboxg3.addWidget(each_widget)
        container = QWidget()
        hbox = QHBoxLayout(container)
        for each_widget in (self.group2, self.group1, group3):
            hbox.addWidget(each_widget)
        self.dock1.setWidget(container)

        # dock 2
        QLabel('<h1 style="color:white;"> Hardware !</h1>', self.dock2).resize(
               self.dock2.size().width() / 4, 25)
        try:
            audioDriverStr = {Solid.AudioInterface.Alsa: "ALSA",
                Solid.AudioInterface.OpenSoundSystem: "Open Sound",
                Solid.AudioInterface.UnknownAudioDriver: "Unknown?"}
            audioInterfaceTypeStr = {
                Solid.AudioInterface.AudioControl: "Control",
                Solid.AudioInterface.UnknownAudioInterfaceType: "Unknown?",
                Solid.AudioInterface.AudioInput: "In",
                Solid.AudioInterface.AudioOutput: "Out"}
            soundcardTypeStr = {
                Solid.AudioInterface.InternalSoundcard: "Internal",
                Solid.AudioInterface.UsbSoundcard: "USB3",
                Solid.AudioInterface.FirewireSoundcard: "FireWire",
                Solid.AudioInterface.Headset: "Headsets",
                Solid.AudioInterface.Modem: "Modem"}
            display = QTreeWidget()
            display.setAlternatingRowColors(True)
            display.setHeaderLabels(["Items", "ID", "Drivers", "I / O", "Type"])
            display.setColumnWidth(0, 350)
            display.setColumnWidth(1, 350)
            display.setColumnWidth(3, 75)
            # retrieve a list of Solid.Device for this machine
            deviceList = Solid.Device.allDevices()
            # filter the list of all devices and display matching results
            # note that we never create a Solid.AudioInterface object, but
            # receive one from the 'asDeviceInterface' call
            for device in deviceList:
                if device.isDeviceInterface(
                                         Solid.DeviceInterface.AudioInterface):
                    audio = device.asDeviceInterface(
                            Solid.DeviceInterface.AudioInterface)
                    devtype = audio.deviceType()
                    devstr = []
                    for key in audioInterfaceTypeStr:
                        flag = key & devtype
                        if flag:
                            devstr.append(audioInterfaceTypeStr[key])
                    QTreeWidgetItem(display, [device.product(), audio.name(),
                        audioDriverStr[audio.driver()], "/".join(devstr),
                        soundcardTypeStr[audio.soundcardType()]])
            self.dock2.setWidget(display)
        except:
            self.dock2.setWidget(QLabel(""" <center style='color:white;'>
            <h1>:(<br>ERROR: Please, install PyKDE !</h1><br>
            <br><i> (Sorry, can not use non-Qt Libs). Thanks </i><center>"""))

        ## dock 3
        QLabel('<h1 style="color:white;"> Previews !</h1>', self.dock3).resize(
               self.dock3.size().width() / 4, 25)
        self.fileView = QColumnView()
        self.fileView.updatePreviewWidget.connect(self.play)
        self.fileView.setToolTip(' Browse and Preview Files ')
        self.media = None
        self.model = QDirModel()
        self.fileView.setModel(self.model)
        self.dock3.setWidget(self.fileView)

        # dock4
        QLabel('<h1 style="color:white;"> Setup !</h1>', self.dock4).resize(
               self.dock4.size().width() / 4, 25)
        self.group4 = QGroupBox()
        self.group4.setTitle(__doc__)

        self.combo0 = QComboBox()
        self.combo0.addItems(['S16_LE', 'S32_LE', 'S16_BE', 'U16_LE', 'U16_BE',
          'S24_LE', 'S24_BE', 'U24_LE', 'U24_BE', 'S32_BE', 'U32_LE', 'U32_BE'])

        self.combo1 = QComboBox()
        self.combo1.addItems(['1', '-1', '0', '2', '3', '4',
                              '5', '6', '7', '8', '9', '10'])

        self.combo2 = QComboBox()
        self.combo2.addItems(['128', '256', '512', '1024', '64', '32', '16'])

        self.combo3 = QComboBox(self)
        self.combo3.addItems(['MONO', 'STEREO', 'Surround'])

        self.combo4 = QComboBox()
        self.combo4.addItems(['44100', '96000', '48000', '32000',
                              '22050', '16000', '11025', '8000'])

        self.combo5 = QComboBox(self)
        self.combo5.addItems(['20', '19', '18', '17', '16', '15', '14', '13',
            '12', '10', '9', '8', '7', '6', '5', '4', '3', '2', '1', '0'])

        self.nepochoose = QCheckBox('Auto-Tag Files using Nepomuk Semantic')

        self.chckbx0 = QCheckBox('Disable Software based Volume Control')

        self.chckbx1 = QCheckBox('Output Sound Stereo-to-Mono Downmix')

        self.chckbx2 = QCheckBox('Add Date and Time MetaData to Sound files')

        self.chckbx3 = QCheckBox('Add Yourself as the Author Artist of Sound')

        vboxg4 = QVBoxLayout(self.group4)
        for each_widget in (
            QLabel('<b style="color:white;"> Sound OGG Quality'), self.combo1,
            QLabel('<b style="color:white;"> Sound Record Format'), self.combo0,
            QLabel('<b style="color:white;"> Sound KBps '), self.combo2,
            QLabel('<b style="color:white;"> Sound Channels '), self.combo3,
            QLabel('<b style="color:white;"> Sound Sample Rate '), self.combo4,
            QLabel('<b style="color:white;"> Sound Volume'), self.chckbx0,
            QLabel('<b style="color:white;"> Sound Mix'), self.chckbx1,
            QLabel('<b style="color:white;"> Sound Meta'), self.chckbx2,
            QLabel('<b style="color:white;"> Sound Authorship'), self.chckbx3,
            QLabel('<b style="color:white;"> CPUs Priority'), self.combo5,
            QLabel('<b style="color:white;">Nepomuk Semantic User Experience'),
            self.nepochoose):
            vboxg4.addWidget(each_widget)
        self.dock4.setWidget(self.group4)

        # dock 5
        QLabel('<h1 style="color:white;"> Voice Changer ! </h1>', self.dock5
               ).resize(self.dock5.size().width() / 3, 25)
        self.group5 = QGroupBox()
        self.group5.setTitle(__doc__)

        self.dial = QDial()
        self.dial.setCursor(QCursor(Qt.OpenHandCursor))
        self.di_l = QLabel(self.dial)
        self.di_l.resize(self.dial.size() / 8)
        self.dial.sliderPressed.connect(lambda:
                            self.dial.setCursor(QCursor(Qt.ClosedHandCursor)))
        self.dial.sliderReleased.connect(lambda:
                            self.dial.setCursor(QCursor(Qt.OpenHandCursor)))
        self.dial.valueChanged.connect(lambda:
                            self.dial.setToolTip(str(self.dial.value())))
        self.dial.valueChanged.connect(lambda: self.di_l.setText(
                    '<h1 style="color:white;">{}'.format(self.dial.value())))
        self.dial.setValue(0)
        self.dial.setMinimum(-999)
        self.dial.setMaximum(999)
        self.dial.setSingleStep(100)
        self.dial.setPageStep(100)
        self.dial.setWrapping(False)
        self.dial.setNotchesVisible(True)

        self.defo = QPushButton(QIcon.fromTheme("media-playback-start"), 'Run')
        self.defo.setMinimumSize(self.defo.size().width(), 50)
        self.defo.clicked.connect(lambda: self.process3.start(
            'play -q -V0 "|rec -q -V0 -n -d -R riaa pitch {} "'
            .format(self.dial.value()) if int(self.dial.value()) != 0 else
            'play -q -V0 "|rec -q -V0 --multi-threaded -n -d -R bend {} "'
            .format(' 3,2500,3 3,-2500,3 ' * 999)))

        self.qq = QPushButton(QIcon.fromTheme("media-playback-stop"), 'Stop')
        self.qq.clicked.connect(self.process3.kill)

        self.die = QPushButton(QIcon.fromTheme("process-stop"), 'Kill')
        self.die.clicked.connect(lambda: call('killall rec', shell=True))

        vboxg5 = QVBoxLayout(self.group5)
        for each_widget in (self.dial, self.defo, self.qq, self.die):
            vboxg5.addWidget(each_widget)
        self.dock5.setWidget(self.group5)

        # configure some widget settings
        must_be_checked((self.nepochoose, self.chckbx1,
                         self.chckbx2, self.chckbx3))
        must_have_tooltip((self.label2, self.label4, self.label6, self.combo0,
            self.nepochoose, self.combo1, self.combo2, self.combo3, self.combo4,
            self.combo5, self.chckbx0, self.chckbx1, self.chckbx2, self.chckbx3,
            self.rec, self.stop, self.defo, self.qq, self.die, self.kill,
            self.button0, self.button1, self.button5))
        must_autofillbackground((self.clock, self.label2, self.label4,
            self.label6, self.nepochoose, self.chckbx0, self.chckbx1,
            self.chckbx2, self.chckbx3))
        must_glow((self.rec, self.dial, self.combo1))
        self.nepomuk_get('testigo')
        if self.auto is True:
            self.go()
Ejemplo n.º 23
0
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        self.process = QProcess()
        self.process.readyReadStandardOutput.connect(self.readOutput)
        self.process.readyReadStandardError.connect(self.readErrors)
        self.process.finished.connect(self._process_finished)
        # self.process.error.connect(self._process_error)

        self.sourceDirectory, self.outputDirectory = None, None

        self.group2 = QGroupBox()
        self.group2.setTitle(' Paths ')
        self.inf = QLineEdit(path.expanduser("~"))
        self.inf.setPlaceholderText(' /full/path/to/directory ')
        self.out, self.fle = QLineEdit(path.expanduser("~")), QLineEdit()
        self.out.setPlaceholderText(' /full/path/to/directory ')
        self.fle.setPlaceholderText(' /full/path/to/single/file ')
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        self.inf.setCompleter(self.completer)
        self.out.setCompleter(self.completer)
        self.fle.setCompleter(self.completer)
        self.open1 = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open1.setCursor(QCursor(Qt.PointingHandCursor))
        self.open1.clicked.connect(lambda: self.inf.setText(str(
            QFileDialog.getExistingDirectory(self.dock, "Open Source Directory",
            path.expanduser("~")))))
        self.open2 = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open2.setCursor(QCursor(Qt.PointingHandCursor))
        self.open2.clicked.connect(lambda: self.out.setText(str(
            QFileDialog.getExistingDirectory(self.dock, "Open Target Directory",
            path.expanduser("~")))))
        self.open3 = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open3.setCursor(QCursor(Qt.PointingHandCursor))
        self.open3.clicked.connect(lambda: self.fle.setText(str(
            QFileDialog.getOpenFileName(self.dock, "Open a Target File...",
            path.expanduser("~"), ';;'.join(['{}(*.{})'.format(e.upper(), e)
                for e in ['py', 'pyw', '*']])))))
        vboxg2 = QVBoxLayout(self.group2)
        for each_widget in (
            QLabel('Source Directory Project:'), self.inf, self.open1,
            QLabel(' Target Directory Outputs: '), self.out, self.open2,
            QLabel(' Source Single File (Optional):'), self.fle, self.open3, ):
            vboxg2.addWidget(each_widget)

        self.group1 = QGroupBox()
        self.group1.setTitle(' Options ')
        self.chckbx1 = QCheckBox(' Inject Twitter Bootstrap CSS3 ')
        self.chckbx1.toggled.connect(self.toggle_styles_group)
        self.chckbx2 = QCheckBox(' Warn all missing references ')
        self.chckbx3 = QCheckBox(' Open Docs when done building ')
        self.chckbx4 = QCheckBox('Save Bash script to reproduce Sphinx Builds')
        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (self.chckbx1, self.chckbx2,
                            self.chckbx3, self.chckbx4):
            vboxg1.addWidget(each_widget)
            each_widget.setChecked(True)

        self.group3 = QGroupBox()
        self.group3.setTitle(' Styles ')
        self.group3.setGraphicsEffect(QGraphicsBlurEffect(self))
        self.group3.graphicsEffect().setEnabled(False)
        self.basecss, self.fontcss = QComboBox(), QComboBox()
        self.basecss.addItems(['slate', 'united', 'spacelab', 'superhero',
            'simplex', 'journal', 'flatly', 'cyborg', 'cosmo', 'cerulean'])
        self.fontcss.addItems(['Ubuntu Light', 'Oxygen', 'Roboto', 'Droid Sans',
            'Open Sans', 'Pacifico', 'Rancho', 'Arvo', 'Fresca', 'Graduate'])
        self.backcss = QComboBox()
        self.backcss.addItems(['shattered', 'retina_wood', 'ricepaper',
            'brickwall', 'sneaker_mesh_fabric', 'diagonales_decalees',
            'noisy_grid', 'pw_pattern', 'escheresque', 'diamond_upholstery'])
        vboxg3 = QVBoxLayout(self.group3)
        for each_widget in (QLabel('<b>Twitter Bootstrap Theme'), self.basecss,
            QLabel('<b>Fonts Family'), self.fontcss,
            QLabel('<b>Background Seamless Tiled Pattern'), self.backcss):
            vboxg3.addWidget(each_widget)

        self.output = QTextEdit('''
        My brain is something more than merely mortal; As time will show.
        - Ada Lovelace ''')
        self.output.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.button = QPushButton('Document My Code')
        self.button.setCursor(QCursor(Qt.PointingHandCursor))
        self.button.setMinimumSize(75, 50)
        self.button.clicked.connect(self.build)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.button.setGraphicsEffect(glow)

        class TransientWidget(QWidget):
            ' persistant widget thingy '
            def __init__(self, widget_list):
                ' init sub class '
                super(TransientWidget, self).__init__()
                vbox = QVBoxLayout(self)
                for each_widget in widget_list:
                    vbox.addWidget(each_widget)

        tw = TransientWidget((self.group2, self.group1, self.group3,
            QLabel(linesep + ' Logs: '), self.output, self.button))
        self.scrollable, self.dock = QScrollArea(), QDockWidget()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(tw)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        ExplorerContainer().addTab(self.dock, "Sphinx")
        QPushButton(QIcon.fromTheme("help-about"), 'About', self.dock
            ).clicked.connect(lambda:
            QMessageBox.information(self.dock, __doc__, HELPMSG))
Ejemplo n.º 24
0
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        self.infile = QLineEdit(path.expanduser("~"))
        self.infile.setPlaceholderText(' /full/path/to/file ')
        self.infile.returnPressed.connect(self.run)
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        self.infile.setCompleter(self.completer)

        self.menu = QMenu('Base64')
        self.menu.aboutToShow.connect(self.build_submenu)
        self.ex_locator = self.locator.get_service('explorer')
        self.ex_locator.add_project_menu(self.menu, lang='all')

        self.open = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open.setCursor(QCursor(Qt.PointingHandCursor))
        self.open.clicked.connect(lambda: self.infile.setText(str(
            QFileDialog.getOpenFileName(self.dock, "Open a File to Encode...",
            path.expanduser("~"), ';;'.join(['{}(*.{})'.format(e.upper(), e)
            for e in ['*', 'jpg', 'png', 'webp', 'svg', 'gif', 'webm']])))))
        self.chckbx1 = QCheckBox('Use basic Caesar Cipher (ROT13)')
        self.chckbx1.setToolTip('Use "string".decode("rot13") to Decipher ! ')
        self.chckbx2 = QCheckBox('Use "data:type/subtype;base64,..."')
        self.chckbx2.setChecked(True)
        self.chckbx3 = QCheckBox('Copy encoded output to Clipboard')
        self.chckbx4 = QCheckBox('Use URL-Safe Base64 Encoder')
        self.combo1 = QComboBox()
        self.combo1.addItems(['Do Not Generate Code', 'Generate CSS embed Code',
            'Generate Python Embed Code', 'Generate HTML embed Code',
            'Generate JS embed Code', 'Generate QML embed Code'])
        self.combo1.currentIndexChanged.connect(self.combo_changed)

        self.output = QTextEdit('''
        We can only see a short distance ahead,
        but we can see plenty there that needs to be done.
        - Alan Turing ''')
        self.output.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.button = QPushButton(QIcon.fromTheme("face-cool"), 'Encode BASE64')
        self.button.setCursor(QCursor(Qt.PointingHandCursor))
        self.button.setMinimumSize(100, 50)
        self.button.clicked.connect(self.run)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.button.setGraphicsEffect(glow)
        glow.setEnabled(True)

        class TransientWidget(QWidget):
            ' persistant widget thingy '
            def __init__(self, widget_list):
                ' init sub class '
                super(TransientWidget, self).__init__()
                vbox = QVBoxLayout(self)
                for each_widget in widget_list:
                    vbox.addWidget(each_widget)

        tw = TransientWidget((QLabel('<i>Encode file as plain text string</i>'),
            QLabel('<b>File to Encode:'), self.infile, self.open, self.chckbx2,
            self.chckbx3, self.chckbx1, self.chckbx4,
            QLabel('<b>Embedding Template Code:'), self.combo1,
            QLabel(' <b>Base64 String Output: '), self.output,
            QLabel('<center><small><i>' + ''.join((__doc__, __version__,
                   __license__, 'by', __author__))), self.button
        ))
        self.scrollable, self.dock = QScrollArea(), QDockWidget()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(tw)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        ExplorerContainer().addTab(self.dock, "Base64")
        self.guimode = QComboBox(self.dock)
        self.guimode.addItems(['Full Mode', 'Simple Mode'])
        self.guimode.currentIndexChanged.connect(self.guimode_change)
Ejemplo n.º 25
0
    def initialize(self, *args, **kwargs):
        ' class init '
        super(Main, self).initialize(*args, **kwargs)
        self.process = QProcess()
        self.process.readyReadStandardOutput.connect(self.readOutput)
        self.process.readyReadStandardError.connect(self.readErrors)
        self.process.finished.connect(self._process_finished)
        self.process.error.connect(self._process_finished)
        # directory auto completer
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.Dirs | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        # menu
        menu = QMenu('VirtualEnv')
        menu.addAction('Make VirtualEnv here', lambda: self.make_virtualenv())
        self.locator.get_service('explorer').add_project_menu(menu, lang='all')

        self.group1 = QGroupBox()
        self.group1.setTitle(' Paths ')
        self.outdir = QLineEdit(path.expanduser("~"))
        self.outdir.setPlaceholderText('Target Directory for Virtualenv files')
        self.outdir.setCompleter(self.completer)
        self.btn1 = QPushButton(QIcon.fromTheme("document-open"), ' Open ')
        self.btn1.clicked.connect(lambda: self.outdir.setText(str(
            QFileDialog.getExistingDirectory(self.dock,
            'Please, Open a Target Directory for the Python VirtualEnv...',
            path.expanduser("~")))))
        self.srcdir, self.prefx = QLineEdit(), QLineEdit()
        self.srcdir.setPlaceholderText(
                    'Extra search path to look for setuptools/distribute/pip')
        self.srcdir.setToolTip('''
        Specify Extra search path to look for setuptools/distribute/pip.
        Defaults to Empty, then the setting is ignored.Defaults are OK.''')
        self.srcdir.setCompleter(self.completer)
        self.btn2 = QPushButton(QIcon.fromTheme("document-open"), ' Open ')
        self.btn2.setToolTip(
            'Specify Extra search path to look for setuptools/distribute/pip')
        self.btn2.clicked.connect(lambda: self.srcdir.setText(str(
            QFileDialog.getExistingDirectory(self.dock,
            'Please, Open a Extra search path to look for setuptools/pip...',
            path.expanduser("~")))))
        self.prefx.setPlaceholderText('Prompt prefix for this environment')
        self.prefx.setToolTip('''
        Specify a custom alternative prompt prefix for this environment.
        Defaults to Empty,this is optional,short prefix are recommended.''')
        self.btn3 = QPushButton(QIcon.fromTheme("face-smile-big"), 'Suggestion')
        self.btn3.setToolTip('Suggest me a Random CLI prompt prefix !')
        self.btn3.clicked.connect(lambda: self.prefx.setText(choice((getuser(),
        'tesla', 'einstein', 'turing', 'ritchie', 'darwin', 'curie', 'planck',
        'lovelace', 'dijsktra', 'galileo', 'schroedinger', 'perlman', 'hopper',
        'newton', 'pasteur', 'maxwell', 'aristotle‎', 'volta', 'mendelev',
        'bohr', 'crick', 'watson', 'archimedes', 'nash', 'fermi', 'dirac',
        'feynman', 'kepler', 'copernicus', 'lorentz', 'faraday', 'heisenberg',
        ))))
        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (
            QLabel(' Target directory dath: '), self.outdir, self.btn1,
            QLabel(' Extra search path: '), self.srcdir, self.btn2,
            QLabel(' CLI Prompt prefix (Optional): '), self.prefx, self.btn3):
            vboxg1.addWidget(each_widget)

        self.group2 = QGroupBox()
        self.group2.setTitle(' Options ')
        self.group2.setCheckable(True)
        self.group2.setGraphicsEffect(QGraphicsBlurEffect(self))
        self.group2.graphicsEffect().setEnabled(False)
        self.group2.toggled.connect(self.toggle_options_group)
        self.qckb1, self.combo1 = QCheckBox(' Use Debug'), QDoubleSpinBox()
        self.qckb2 = QCheckBox(' Clear out the target directory')
        self.qckb3 = QCheckBox(' System-wide Python Packages')
        self.qckb4 = QCheckBox(' Unzip Setuptool or Distribute to virtualenv')
        self.qckb5 = QCheckBox(' Force the use of SetupTools')
        self.qckb6 = QCheckBox(' Never download packages')
        self.qckb7 = QCheckBox(' Delete .PYC files from virtualenv')
        self.qckb8 = QCheckBox(' Open target directory later')
        self.qckb9 = QCheckBox(' Save a LOG file to target later')
        self.qckb10 = QCheckBox(' No install PIP in the new virtualenv')
        self.qckb11 = QCheckBox('Save Bash script to reproduce virtenv later')
        self.chrt = QCheckBox('LOW CPU priority for Backend Process')
        self.combo1.setValue(2.7)
        self.combo1.setMaximum(3.4)
        self.combo1.setMinimum(2.4)
        self.combo1.setDecimals(1)
        self.combo1.setSingleStep(0.1)
        try:
            self.vinfo = QLabel('<small><b> Virtualenv Version: </b>' +
                            getoutput('virtualenv --version', shell=1).strip())
        except:
            self.vinfo = QLabel('Warning: Failed to query Virtualenv Backend!')
        [a.setChecked(True) for a in (self.qckb1, self.qckb4, self.qckb7,
                                self.chrt, self.qckb8, self.qckb9, self.qckb11)]
        vboxg2 = QVBoxLayout(self.group2)
        for each_widget in (self.qckb1, self.qckb2, self.qckb3, self.qckb4,
            self.qckb5, self.qckb6, self.qckb7, self.qckb8, self.qckb9,
            self.qckb10, self.qckb11, QLabel(' Python interpreter version: '),
            self.combo1, QLabel(' Backend CPU priority: '), self.chrt):
            vboxg2.addWidget(each_widget)

        self.button = QPushButton(' Make Virtualenv ')
        self.button.setCursor(QCursor(Qt.PointingHandCursor))
        self.button.setMinimumSize(75, 50)
        self.button.clicked.connect(self.run)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.button.setGraphicsEffect(glow)
        self.output = QTextEdit(''' " Let the future tell the truth,
        and evaluate each one according to his work and accomplishments.
        The present is theirs; the future, for which I really worked, is mine. "
        -Nikola Tesla. ''')

        class TransientWidget(QWidget):
            ' persistant widget thingy '
            def __init__(self, widget_list):
                ' init sub class '
                super(TransientWidget, self).__init__()
                vbox = QVBoxLayout(self)
                for each_widget in widget_list:
                    vbox.addWidget(each_widget)

        tw = TransientWidget((self.group1, self.group2, QLabel('Backend Logs'),
                              self.output, self.vinfo, self.button))
        self.scrollable, self.dock = QScrollArea(), QDockWidget()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(tw)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        ExplorerContainer().addTab(self.dock, "Virtualenv")
        QPushButton(QIcon.fromTheme("help-about"), 'About', self.dock
            ).clicked.connect(lambda:
            QMessageBox.information(self.dock, __doc__, HELPMSG))
Ejemplo n.º 26
0
class Main(plugin.Plugin):
    " Main Class "
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        self.process = QProcess()
        self.process.readyReadStandardOutput.connect(self.readOutput)
        self.process.readyReadStandardError.connect(self.readErrors)
        self.process.finished.connect(self._process_finished)
        # self.process.error.connect(self._process_error)

        self.sourceDirectory, self.outputDirectory = None, None

        self.group2 = QGroupBox()
        self.group2.setTitle(' Paths ')
        self.inf = QLineEdit(path.expanduser("~"))
        self.inf.setPlaceholderText(' /full/path/to/directory ')
        self.out, self.fle = QLineEdit(path.expanduser("~")), QLineEdit()
        self.out.setPlaceholderText(' /full/path/to/directory ')
        self.fle.setPlaceholderText(' /full/path/to/single/file ')
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        self.inf.setCompleter(self.completer)
        self.out.setCompleter(self.completer)
        self.fle.setCompleter(self.completer)
        self.open1 = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open1.setCursor(QCursor(Qt.PointingHandCursor))
        self.open1.clicked.connect(lambda: self.inf.setText(str(
            QFileDialog.getExistingDirectory(self.dock, "Open Source Directory",
            path.expanduser("~")))))
        self.open2 = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open2.setCursor(QCursor(Qt.PointingHandCursor))
        self.open2.clicked.connect(lambda: self.out.setText(str(
            QFileDialog.getExistingDirectory(self.dock, "Open Target Directory",
            path.expanduser("~")))))
        self.open3 = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        self.open3.setCursor(QCursor(Qt.PointingHandCursor))
        self.open3.clicked.connect(lambda: self.fle.setText(str(
            QFileDialog.getOpenFileName(self.dock, "Open a Target File...",
            path.expanduser("~"), ';;'.join(['{}(*.{})'.format(e.upper(), e)
                for e in ['py', 'pyw', '*']])))))
        vboxg2 = QVBoxLayout(self.group2)
        for each_widget in (
            QLabel('Source Directory Project:'), self.inf, self.open1,
            QLabel(' Target Directory Outputs: '), self.out, self.open2,
            QLabel(' Source Single File (Optional):'), self.fle, self.open3, ):
            vboxg2.addWidget(each_widget)

        self.group1 = QGroupBox()
        self.group1.setTitle(' Options ')
        self.chckbx1 = QCheckBox(' Inject Twitter Bootstrap CSS3 ')
        self.chckbx1.toggled.connect(self.toggle_styles_group)
        self.chckbx2 = QCheckBox(' Warn all missing references ')
        self.chckbx3 = QCheckBox(' Open Docs when done building ')
        self.chckbx4 = QCheckBox('Save Bash script to reproduce Sphinx Builds')
        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (self.chckbx1, self.chckbx2,
                            self.chckbx3, self.chckbx4):
            vboxg1.addWidget(each_widget)
            each_widget.setChecked(True)

        self.group3 = QGroupBox()
        self.group3.setTitle(' Styles ')
        self.group3.setGraphicsEffect(QGraphicsBlurEffect(self))
        self.group3.graphicsEffect().setEnabled(False)
        self.basecss, self.fontcss = QComboBox(), QComboBox()
        self.basecss.addItems(['slate', 'united', 'spacelab', 'superhero',
            'simplex', 'journal', 'flatly', 'cyborg', 'cosmo', 'cerulean'])
        self.fontcss.addItems(['Ubuntu Light', 'Oxygen', 'Roboto', 'Droid Sans',
            'Open Sans', 'Pacifico', 'Rancho', 'Arvo', 'Fresca', 'Graduate'])
        self.backcss = QComboBox()
        self.backcss.addItems(['shattered', 'retina_wood', 'ricepaper',
            'brickwall', 'sneaker_mesh_fabric', 'diagonales_decalees',
            'noisy_grid', 'pw_pattern', 'escheresque', 'diamond_upholstery'])
        vboxg3 = QVBoxLayout(self.group3)
        for each_widget in (QLabel('<b>Twitter Bootstrap Theme'), self.basecss,
            QLabel('<b>Fonts Family'), self.fontcss,
            QLabel('<b>Background Seamless Tiled Pattern'), self.backcss):
            vboxg3.addWidget(each_widget)

        self.output = QTextEdit('''
        My brain is something more than merely mortal; As time will show.
        - Ada Lovelace ''')
        self.output.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.button = QPushButton('Document My Code')
        self.button.setCursor(QCursor(Qt.PointingHandCursor))
        self.button.setMinimumSize(75, 50)
        self.button.clicked.connect(self.build)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.button.setGraphicsEffect(glow)

        class TransientWidget(QWidget):
            ' persistant widget thingy '
            def __init__(self, widget_list):
                ' init sub class '
                super(TransientWidget, self).__init__()
                vbox = QVBoxLayout(self)
                for each_widget in widget_list:
                    vbox.addWidget(each_widget)

        tw = TransientWidget((self.group2, self.group1, self.group3,
            QLabel(linesep + ' Logs: '), self.output, self.button))
        self.scrollable, self.dock = QScrollArea(), QDockWidget()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(tw)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        ExplorerContainer().addTab(self.dock, "Sphinx")
        QPushButton(QIcon.fromTheme("help-about"), 'About', self.dock
            ).clicked.connect(lambda:
            QMessageBox.information(self.dock, __doc__, HELPMSG))

    def readOutput(self):
        """Read and append sphinx-build output to the logBrowser"""
        self.output.append(str(self.process.readAllStandardOutput()))

    def readErrors(self):
        """Read and append sphinx-build errors to the logBrowser"""
        self.output.append(self.formatErrorMsg(str(
                                        self.process.readAllStandardError())))

    def formatErrorMsg(self, msg):
        """Format error messages in red color"""
        return self.formatMsg(msg, 'red')

    def formatInfoMsg(self, msg):
        """Format informative messages in blue color"""
        return self.formatMsg(msg, 'green')

    def formatMsg(self, msg, color):
        """Format message with the given color"""
        return '<font color="{}">{}</font>'.format(color, msg)

    def build(self):
        """Main function calling sphinx-build to generate the project"""
        self.output.setText('')
        self.output.append(self.formatInfoMsg(
                            'INFO: OK: Starting at {}'.format(datetime.now())))
        self.button.setDisabled(True)
        self.sourceDirectory = str(self.inf.text()).strip()
        self.outputDirectory = str(self.out.text()).strip()
        if not len(self.sourceDirectory):
            self.output.append(' ERROR: FAIL: Source directory cannot be empty')
        else:
            self.output.append(self.formatInfoMsg(
            'INFO: OK: Source Directory is {}'.format(self.sourceDirectory)))
        if not len(self.outputDirectory):
            self.output.append(' ERROR: FAIL: Output directory cannot be empty')
        else:
            self.output.append(self.formatInfoMsg(
            'INFO: OK: Output Directory is {}'.format(self.outputDirectory)))
        if not(len(self.sourceDirectory) or len(self.outputDirectory)):
            self.button.setDisabled(False)
            return
        self.output.append(self.formatInfoMsg('INFO:OK: Building. Please wait'))

        args = ['-n' if self.chckbx2.isChecked() is True else '',
                '-b', 'html', self.sourceDirectory, self.outputDirectory]
        if len(self.fle.text()):
            args.append(str(self.fle.text()).strip().replace('file:///', '/'))
            self.output.append(self.formatInfoMsg(
                'INFO: OK: Source Single File is {}'.format(self.fle.text())))
        self.output.append(self.formatInfoMsg('INFO:OK: Running sphinx-build!'))

        self.process.start('sphinx-build', args)
        if not self.process.waitForStarted():
            self.output.append(self.formatErrorMsg('ERROR: FAIL: Build Failed'))
            self.output.append(self.formatErrorMsg(
                'ERROR: FAIL: Failed with Arguments: {} '.format(args)))
            self.button.setEnabled(True)
            return
        # write a .sh bash script file on target
        if self.chckbx4.isChecked() is True:
            sh_file = 'build_sphinx_documentation.sh'
            with open(path.join(self.sourceDirectory, sh_file), 'w') as _sh:
                self.output.append(self.formatInfoMsg('''INFO: OK: Writing Bash:
                    {}'''.format(path.join(self.sourceDirectory, sh_file))))
                _sh.write('#!/usr/bin/env bash {}'.format(linesep) +
                          'sphinx-build {}'.format(' '.join(args)))
                _sh.close()
            self.output.append(self.formatInfoMsg('INFO: OK: Bash chmod: 775'))
            try:
                chmod(path.join(self.sourceDirectory, sh_file), 0775)  # Py2
            except:
                chmod(path.join(self.sourceDirectory, sh_file), 0o775)  # Py3
        self.button.setEnabled(True)

    def _process_finished(self):
        """sphinx-build finished sucessfully"""
        self.output.append(self.formatInfoMsg(
                            'INFO: OK: Finished at {}'.format(datetime.now())))
        if self.chckbx1.isChecked() is True:
            with open(path.join(self.outputDirectory, '_static', 'default.css'),
                'a') as f:
                css = CSS3.replace('CSSWEBFONT', str(self.fontcss.currentText())
                      ).replace('CSSBACKGR', str(self.backcss.currentText())
                      ).replace('CSSCUSTOM', str(self.basecss.currentText()))
                f.write(css)
                f.close()
        if self.chckbx3.isChecked() is True:
            call('xdg-open ' + path.join(self.outputDirectory, 'index.html'),
                 shell=True)

    def toggle_styles_group(self):
        ' toggle on or off the styles checkboxes '
        try:
            if self.chckbx1.isChecked() is True:
                self.group3.graphicsEffect().setEnabled(False)
                self.group3.setEnabled(True)
            else:
                self.group3.graphicsEffect().setEnabled(True)
                self.group3.setEnabled(False)
        except:
            pass
Ejemplo n.º 27
0
class Main(plugin.Plugin):
    " Main Class "
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        self.process, self.mainwidget = QProcess(), QTabWidget()
        self.process.readyReadStandardOutput.connect(self.readOutput)
        self.process.readyReadStandardError.connect(self.readErrors)
        self.process.finished.connect(self._process_finished)
        self.process.error.connect(self._process_finished)
        self.mainwidget.tabCloseRequested.connect(lambda:
            self.mainwidget.setTabPosition(1)
            if self.mainwidget.tabPosition() == 0
            else self.mainwidget.setTabPosition(0))
        self.mainwidget.setStyleSheet('QTabBar{font-weight:bold;}')
        self.mainwidget.setMovable(True)
        self.mainwidget.setTabsClosable(True)
        self.dock, self.scrollable = QDockWidget(), QScrollArea()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(self.mainwidget)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        self.locator.get_service('misc').add_widget(self.dock,
                                 QIcon.fromTheme("face-sad"), __doc__)
        self.tab1, self.tab2, self.tab3 = QGroupBox(), QGroupBox(), QGroupBox()
        self.tab4, self.tab5, self.tab6 = QGroupBox(), QGroupBox(), QGroupBox()
        for a, b in ((self.tab1, 'Basics'), (self.tab2, 'Coverage'),
            (self.tab3, 'Extensions'), (self.tab5, 'Regex'),
             (self.tab4, 'Paths'), (self.tab6, 'Run')):
            a.setTitle(b)
            a.setToolTip(b)
            self.mainwidget.addTab(a, QIcon.fromTheme("face-sad"), b)
        QPushButton(QIcon.fromTheme("help-about"), 'About', self.dock
          ).clicked.connect(lambda: QMessageBox.information(self.dock, __doc__,
          ''.join((__doc__, __version__, __license__, 'by', __author__))))

        groupl, groupr, co = QWidget(), QWidget(), QGroupBox()
        self.qckb1 = QCheckBox('Open target directory later')
        self.qckb2 = QCheckBox('Save a LOG file to target later')
        self.qckb3 = QCheckBox('Verbose operation')
        self.qckb4 = QCheckBox('Force Stop on Error')
        self.qckb5 = QCheckBox('Scan Executable files for Tests')
        vboxgl, vboxgr = QVBoxLayout(groupl), QVBoxLayout(groupr)
        for a in (self.qckb1, self.qckb2, self.qckb3, self.qckb4, self.qckb5):
            vboxgl.addWidget(a)
            a.setToolTip(a.text())
        self.qckb6 = QCheckBox('No Byte Compile to .PYC or Delete .PYC later')
        self.qckb7 = QCheckBox('Dont touch sys.path when running tests')
        self.qckb8 = QCheckBox('Traverse all paths of a package')
        self.qckb9 = QCheckBox('Dont capture STDOUT, print STDOUT on the fly')
        self.qckb10 = QCheckBox('Clear all Logging handlers')
        for a in (self.qckb6, self.qckb7, self.qckb8, self.qckb9, self.qckb10):
            vboxgr.addWidget(a)
            a.setToolTip(a.text())
        vboxcon, self.framew = QHBoxLayout(co), QComboBox()
        [vboxcon.addWidget(a) for a in (groupl, groupr)]
        self.chrt = QCheckBox('LOW CPU priority for Backend Process')
        self.framew.addItems(['nosetests', 'PyTest', 'DocTest', 'Unittest',
                              'Django_Test', 'Django-Nose', 'None'])
        self.framew.currentIndexChanged.connect(lambda:  #FIXME refactor for 3
            QMessageBox.information(self.dock, __doc__, '<b>Only Nose for now'))
        self.framew.currentIndexChanged.connect(lambda:  #FIXME refactor for 3
            self.framew.setCurrentIndex(0))
        vboxg1 = QVBoxLayout(self.tab1)
        for each_widget in (QLabel('<b>Framework'), self.framew, self.chrt, co):
            vboxg1.addWidget(each_widget)

        self.t2ck1, self.t2sp1 = QCheckBox('Activate Coverage'), QSpinBox()
        self.t2ck2 = QCheckBox('Erase previously collected Coverage before run')
        self.t2ck3 = QCheckBox('Include all tests modules in Coverage reports')
        self.t2ck4 = QCheckBox('Include all python files on working directory')
        self.t2ck5 = QCheckBox('Produce HTML Coverage reports information')
        self.t2ck6 = QCheckBox('Include Branch Coverage in Coverage reports')
        self.t2sp1.setRange(10, 90)
        self.t2sp1.setValue(75)
        vboxg2 = QVBoxLayout(self.tab2)
        for each_widget in (QLabel('<b>Min Percentage'), self.t2sp1, self.t2ck1,
            self.t2ck2, self.t2ck3, self.t2ck4, self.t2ck5, self.t2ck6):
            vboxg2.addWidget(each_widget)

        groupi, groupd, vbxg3 = QGroupBox(), QGroupBox(), QHBoxLayout(self.tab3)
        vboxgi, vboxgd = QVBoxLayout(groupi), QVBoxLayout(groupd)
        self.t3ck1 = QCheckBox('Activate DocTest to find and run doctests')
        self.t3ck2 = QCheckBox('Look for any doctests in tests modules too')
        self.t3ck3 = QCheckBox('Activate isolation (Do Not use with Coverage!)')
        self.t3ck4 = QCheckBox('Use Detailed Errors, evaluate failed asserts')
        for a in (self.t3ck1, self.t3ck2, self.t3ck3, self.t3ck4):
            vboxgi.addWidget(a)
            a.setToolTip(a.text())
        self.t3ck5 = QCheckBox('Disable special handling of SkipTest exception')
        self.t3ck6 = QCheckBox('Run the tests that failed in the last test run')
        self.t3ck7 = QCheckBox('Use AllModules, Collect tests from all modules')
        self.t3ck8 = QCheckBox('Collect tests names only, do Not run any tests')
        for a in (self.t3ck5, self.t3ck6, self.t3ck7, self.t3ck8):
            vboxgd.addWidget(a)
            a.setToolTip(a.text())
        [vbxg3.addWidget(a) for a in (groupi, groupd)]

        self.t4le1, self.t4le2 = QLineEdit(), QLineEdit(path.expanduser("~"))
        self.t4le1.setCompleter(self.completer)
        self.t4le2.setCompleter(self.completer)
        self.t4le1.setPlaceholderText(' /full/path/to/a/folder/ ')
        self.t4le2.setPlaceholderText(' /full/path/to/a/folder/ ')
        le1b = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        le1b.setMinimumSize(50, 50)
        le1b.clicked.connect(lambda: self.t4le1.setText(
            QFileDialog.getExistingDirectory(None, '', path.expanduser("~"))))
        le2b = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        le2b.clicked.connect(lambda: self.t4le2.setText(
            QFileDialog.getExistingDirectory(None, '', path.expanduser("~"))))
        vboxg4 = QVBoxLayout(self.tab4)
        for a in (QLabel('<b>Directory to look for Tests'), self.t4le1, le1b,
            QLabel('<b>Directory to generate HTML Coverage'), self.t4le2, le2b):
            vboxg4.addWidget(a)
            a.setToolTip(a.text())

        self.t5le1 = QLineEdit(r'(?:^|[\b_\./-])[Tt]est')
        self.t5le2 = QLineEdit()
        self.t5le3, vboxg5 = QLineEdit(), QVBoxLayout(self.tab5)
        r = QPushButton('Reset')
        r.clicked.connect(lambda: self.t5le1.setText(r'(?:^|[\b_\./-])[Tt]est'))
        for a in (QLabel('<b>Matching Name Regex to be test'), self.t5le1, r,
            QLabel('<b>Force Include Regex Tests'), self.t5le2,
            QLabel('<b>Force Exclude Regex Tests'), self.t5le3):
            vboxg5.addWidget(a)
            a.setToolTip(a.text())

        self.output = QTextEdit(''' Engineering is the art of making what you
            want from things you can get.    -Dhobi''')
        self.runbtn = QPushButton(QIcon.fromTheme("face-sad"), 'Start Testing!')
        self.runbtn.setMinimumSize(75, 50)
        self.runbtn.clicked.connect(self.run)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.runbtn.setGraphicsEffect(glow)
        self.kbt = QPushButton(QIcon.fromTheme("application-exit"), 'Kill')
        self.kbt.clicked.connect(lambda: self.process.kill())
        vboxg6 = QVBoxLayout(self.tab6)
        for each_widget in (QLabel('Logs'), self.output, self.runbtn, self.kbt):
            vboxg6.addWidget(each_widget)
        [a.setChecked(True) for a in (self.chrt, self.qckb2, self.qckb3,
                                      self.qckb10, self.t2ck1, self.t2ck2,
                                      self.t2ck5, self.t3ck1, self.t3ck4)]
        self.mainwidget.setCurrentIndex(4)

    def readOutput(self):
        """Read and append output to the logBrowser"""
        self.output.append(str(self.process.readAllStandardOutput()))

    def readErrors(self):
        """Read and append errors to the logBrowser"""
        self.output.append(str(self.process.readAllStandardError()))

    def run(self):
        """Main function calling vagrant to generate the vm"""
        if not len(self.t4le1.text()):
            QMessageBox.information(self.dock, __doc__,
                '<b style="color:red">ERROR: Target Folder can not be Empty !')
            return
        self.output.clear()
        self.output.append('INFO: OK: Starting at {}'.format(datetime.now()))
        self.runbtn.setDisabled(True)
        #nose = True if self.framew.currentText() in 'nosetests' else False
        cmd = ' '.join(('chrt -i 0' if self.chrt.isChecked() else '',
            # tab 1
            self.framew.currentText(),
            '--verbose' if self.qckb3.isChecked() else '--quiet',
            '--stop' if self.qckb4.isChecked() else '',
            '--exe' if self.qckb5.isChecked() else '--noexe',
            '--no-byte-compile' if self.qckb6.isChecked() else '',
            '--no-path-adjustment' if self.qckb7.isChecked() else '',
            '--traverse-namespace' if self.qckb8.isChecked() else '',
            '--nocapture' if self.qckb9.isChecked() else '',
            '--logging-clear-handlers' if self.qckb10.isChecked() else '',
            # tab 2
            '--with-coverage' if self.t2ck1.isChecked() else '',
            '--cover-erase' if self.t2ck2.isChecked() else '',
            '--cover-tests' if self.t2ck3.isChecked() else '',
            '--cover-inclusive' if self.t2ck4.isChecked() else '',
            '--cover-html' if self.t2ck5.isChecked() else '--cover-xml',
            '--cover-branches' if self.t2ck6.isChecked() else '',
            '--cover-min-percentage={}'.format(self.t2sp1.value()),
            # tab 3
            '--with-doctest' if self.t3ck1.isChecked() else '',
            '--doctest-tests' if self.t3ck2.isChecked() else '',
            '--with-isolation' if self.t3ck3.isChecked() else '',
            '--detailed-errors' if self.t3ck4.isChecked() else '',
            '--no-skip' if self.t3ck5.isChecked() else '',
            '--failed' if self.t3ck6.isChecked() else '',
            '--all-modules' if self.t3ck7.isChecked() else '',
            '--collect-only' if self.t3ck8.isChecked() else '',
            # tab 4
            '--where="{}"'.format(self.t4le1.text()),
            '--cover-html-dir="{}"'.format(self.t4le2.text()) if self.t2ck5.isChecked() else '--cover-xml-file={}'.format(path.join(self.t4le2.text(), 'coverage_ninja.xml')),
            # tab 5
            '--match="{}"'.format(self.t5le1.text().encode('utf-8')) if len(self.t5le1.text()) else '',
            '--include="{}"'.format(self.t5le2.text()) if len(self.t5le2.text()) else '',
            '--exclude="{}"'.format(self.t5le3.text()) if len(self.t5le3.text()) else '',
        ))
        self.output.append('INFO: OK: Command: {}'.format(cmd))
        with open(path.join(self.t4le2.text(), 'tests_run_ninja.sh'), 'w') as f:
            self.output.append('INFO: OK : Writing tests_run_ninja.sh')
            f.write('#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\n' + cmd)
        try:
            chmod(path.join(self.t4le2.text(), 'tests_run_ninja.sh'), 0775)
        except:
            chmod(path.join(self.t4le2.text(), 'tests_run_ninja.sh'), 0o775)
        self.output.append('INFO: OK: Running Tests !')
        self.process.start(cmd)
        if not self.process.waitForStarted():
            self.output.append('ERROR: FAIL: Unkown Error !')
            self.runbtn.setEnabled(True)
            return
        self.runbtn.setEnabled(True)

    def _process_finished(self):
        """finished sucessfully"""
        self.output.append('INFO: OK: Finished at {}'.format(datetime.now()))
        if self.qckb2.isChecked() is True:
            with open(path.join(self.t4le2.text(), 'test_ninja.log'), 'w') as f:
                self.output.append('INFO: OK: Writing .LOG')
                f.write(self.output.toPlainText())
        if self.qckb1.isChecked() is True:
            self.output.append('INFO:Opening Target Folder')
            try:
                startfile(self.t4le2.text())
            except:
                Popen(["xdg-open", self.t4le2.text()])

    def finish(self):
        ' clear when finish '
        self.process.kill()
Ejemplo n.º 28
0
class Main(plugin.Plugin):
    ' main class for plugin '
    def initialize(self, *args, **kwargs):
        ' class init '
        super(Main, self).initialize(*args, **kwargs)
        self.process = QProcess()
        self.process.readyReadStandardOutput.connect(self.readOutput)
        self.process.readyReadStandardError.connect(self.readErrors)
        self.process.finished.connect(self._process_finished)
        self.process.error.connect(self._process_finished)
        # directory auto completer
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.Dirs | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        # menu
        menu = QMenu('VirtualEnv')
        menu.addAction('Make VirtualEnv here', lambda: self.make_virtualenv())
        self.locator.get_service('explorer').add_project_menu(menu, lang='all')

        self.group1 = QGroupBox()
        self.group1.setTitle(' Paths ')
        self.outdir = QLineEdit(path.expanduser("~"))
        self.outdir.setPlaceholderText('Target Directory for Virtualenv files')
        self.outdir.setCompleter(self.completer)
        self.btn1 = QPushButton(QIcon.fromTheme("document-open"), ' Open ')
        self.btn1.clicked.connect(lambda: self.outdir.setText(str(
            QFileDialog.getExistingDirectory(self.dock,
            'Please, Open a Target Directory for the Python VirtualEnv...',
            path.expanduser("~")))))
        self.srcdir, self.prefx = QLineEdit(), QLineEdit()
        self.srcdir.setPlaceholderText(
                    'Extra search path to look for setuptools/distribute/pip')
        self.srcdir.setToolTip('''
        Specify Extra search path to look for setuptools/distribute/pip.
        Defaults to Empty, then the setting is ignored.Defaults are OK.''')
        self.srcdir.setCompleter(self.completer)
        self.btn2 = QPushButton(QIcon.fromTheme("document-open"), ' Open ')
        self.btn2.setToolTip(
            'Specify Extra search path to look for setuptools/distribute/pip')
        self.btn2.clicked.connect(lambda: self.srcdir.setText(str(
            QFileDialog.getExistingDirectory(self.dock,
            'Please, Open a Extra search path to look for setuptools/pip...',
            path.expanduser("~")))))
        self.prefx.setPlaceholderText('Prompt prefix for this environment')
        self.prefx.setToolTip('''
        Specify a custom alternative prompt prefix for this environment.
        Defaults to Empty,this is optional,short prefix are recommended.''')
        self.btn3 = QPushButton(QIcon.fromTheme("face-smile-big"), 'Suggestion')
        self.btn3.setToolTip('Suggest me a Random CLI prompt prefix !')
        self.btn3.clicked.connect(lambda: self.prefx.setText(choice((getuser(),
        'tesla', 'einstein', 'turing', 'ritchie', 'darwin', 'curie', 'planck',
        'lovelace', 'dijsktra', 'galileo', 'schroedinger', 'perlman', 'hopper',
        'newton', 'pasteur', 'maxwell', 'aristotle‎', 'volta', 'mendelev',
        'bohr', 'crick', 'watson', 'archimedes', 'nash', 'fermi', 'dirac',
        'feynman', 'kepler', 'copernicus', 'lorentz', 'faraday', 'heisenberg',
        ))))
        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (
            QLabel(' Target directory dath: '), self.outdir, self.btn1,
            QLabel(' Extra search path: '), self.srcdir, self.btn2,
            QLabel(' CLI Prompt prefix (Optional): '), self.prefx, self.btn3):
            vboxg1.addWidget(each_widget)

        self.group2 = QGroupBox()
        self.group2.setTitle(' Options ')
        self.group2.setCheckable(True)
        self.group2.setGraphicsEffect(QGraphicsBlurEffect(self))
        self.group2.graphicsEffect().setEnabled(False)
        self.group2.toggled.connect(self.toggle_options_group)
        self.qckb1, self.combo1 = QCheckBox(' Use Debug'), QDoubleSpinBox()
        self.qckb2 = QCheckBox(' Clear out the target directory')
        self.qckb3 = QCheckBox(' System-wide Python Packages')
        self.qckb4 = QCheckBox(' Unzip Setuptool or Distribute to virtualenv')
        self.qckb5 = QCheckBox(' Force the use of SetupTools')
        self.qckb6 = QCheckBox(' Never download packages')
        self.qckb7 = QCheckBox(' Delete .PYC files from virtualenv')
        self.qckb8 = QCheckBox(' Open target directory later')
        self.qckb9 = QCheckBox(' Save a LOG file to target later')
        self.qckb10 = QCheckBox(' No install PIP in the new virtualenv')
        self.qckb11 = QCheckBox('Save Bash script to reproduce virtenv later')
        self.chrt = QCheckBox('LOW CPU priority for Backend Process')
        self.combo1.setValue(2.7)
        self.combo1.setMaximum(3.4)
        self.combo1.setMinimum(2.4)
        self.combo1.setDecimals(1)
        self.combo1.setSingleStep(0.1)
        try:
            self.vinfo = QLabel('<small><b> Virtualenv Version: </b>' +
                            getoutput('virtualenv --version', shell=1).strip())
        except:
            self.vinfo = QLabel('Warning: Failed to query Virtualenv Backend!')
        [a.setChecked(True) for a in (self.qckb1, self.qckb4, self.qckb7,
                                self.chrt, self.qckb8, self.qckb9, self.qckb11)]
        vboxg2 = QVBoxLayout(self.group2)
        for each_widget in (self.qckb1, self.qckb2, self.qckb3, self.qckb4,
            self.qckb5, self.qckb6, self.qckb7, self.qckb8, self.qckb9,
            self.qckb10, self.qckb11, QLabel(' Python interpreter version: '),
            self.combo1, QLabel(' Backend CPU priority: '), self.chrt):
            vboxg2.addWidget(each_widget)

        self.button = QPushButton(' Make Virtualenv ')
        self.button.setCursor(QCursor(Qt.PointingHandCursor))
        self.button.setMinimumSize(75, 50)
        self.button.clicked.connect(self.run)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.button.setGraphicsEffect(glow)
        self.output = QTextEdit(''' " Let the future tell the truth,
        and evaluate each one according to his work and accomplishments.
        The present is theirs; the future, for which I really worked, is mine. "
        -Nikola Tesla. ''')

        class TransientWidget(QWidget):
            ' persistant widget thingy '
            def __init__(self, widget_list):
                ' init sub class '
                super(TransientWidget, self).__init__()
                vbox = QVBoxLayout(self)
                for each_widget in widget_list:
                    vbox.addWidget(each_widget)

        tw = TransientWidget((self.group1, self.group2, QLabel('Backend Logs'),
                              self.output, self.vinfo, self.button))
        self.scrollable, self.dock = QScrollArea(), QDockWidget()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(tw)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        ExplorerContainer().addTab(self.dock, "Virtualenv")
        QPushButton(QIcon.fromTheme("help-about"), 'About', self.dock
            ).clicked.connect(lambda:
            QMessageBox.information(self.dock, __doc__, HELPMSG))

    def readOutput(self):
        """Read and append sphinx-build output to the logBrowser"""
        self.output.append(str(self.process.readAllStandardOutput()).strip())

    def readErrors(self):
        """Read and append sphinx-build errors to the logBrowser"""
        self.output.append(self.formatErrorMsg(str(
                                        self.process.readAllStandardError())))

    def formatErrorMsg(self, msg):
        """Format error messages in red color"""
        return self.formatMsg(msg, 'red')

    def formatInfoMsg(self, msg):
        """Format informative messages in blue color"""
        return self.formatMsg(msg, 'green')

    def formatMsg(self, msg, color):
        """Format message with the given color"""
        return '<font color="{}">{}</font>'.format(color, msg)

    def make_virtualenv(self):
        ' make virtualenv from contextual sub menu '
        self.outdir.setText(self.ex_locator.get_current_project_item().path)
        self.run()

    def run(self):
        ' run the actions '
        self.output.clear()
        self.output.append(self.formatInfoMsg(
                            'INFO: OK: Starting at {}'.format(datetime.now())))
        self.button.setDisabled(True)
        # Parse Values
        arg0 = '' if self.qckb10.isChecked() is False else '--no-pip '
        arg1 = '--quiet ' if self.qckb1.isChecked() is False else '--verbose '
        arg2 = '' if self.qckb2.isChecked() is False else '--clear '
        arg3 = '' if self.qckb3.isChecked() is False else '--system-site-packages '
        arg4 = '' if self.qckb4.isChecked() is False else '--unzip-setuptools '
        arg5 = '' if self.qckb5.isChecked() is False else '--setuptools '
        arg6 = '' if self.qckb6.isChecked() is False else '--never-download '
        # if the target is empty return
        if not len(str(self.outdir.text()).strip()):
            self.output.append(self.formatErrorMsg('ERROR: FAIL: Target empty'))
            self.button.setEnabled(True)
            return
        else:
            self.output.append(self.formatInfoMsg(
            'INFO: OK: Output Directory is {}'.format(self.outdir.text())))
        # prefix
        prf = str(self.prefx.text()).upper().strip().replace(' ', '')
        arg10 = '' if prf is '' else '--prompt="{}_" '.format(prf)
        self.output.append(self.formatInfoMsg('INFO: Prefix: {}'.format(arg10)))
        # extra search dir
        src = str(self.srcdir.text()).strip()
        arg11 = '' if src is '' else '--extra-search-dir="{}" '.format(src)
        self.output.append(self.formatInfoMsg(' INFO: Extra: {}'.format(arg11)))
        self.output.append(self.formatInfoMsg(
            ' INFO: OK: Write Logs ?: {} '.format(self.qckb9.isChecked())))
        self.output.append(self.formatInfoMsg(
            ' INFO: OK: Open Directory ?: {} '.format(self.qckb8.isChecked())))
        # run the subprocesses
        cmd = '{}virtualenv {}{}{}{}{}{}{}-p python{} {}{} {}'.format(
            'chrt --verbose -i 0 ' if self.chrt.isChecked() is True else '',
            arg0, arg1, arg2, arg3, arg4, arg5, arg6,
            self.combo1.value(), arg11, arg10, str(self.outdir.text()).strip())
        self.output.append(self.formatInfoMsg('INFO:OK:Command:{}'.format(cmd)))
        self.process.start(cmd)
        if not self.process.waitForStarted():
            self.output.append(self.formatErrorMsg(' ERROR: FAIL: Meh. '))
            self.output.append(self.formatErrorMsg(
                'ERROR: FAIL: Failed with Arguments: {} '.format(cmd)))
            self.button.setEnabled(True)
            return
         # write a .sh bash script file on target
        if self.qckb11.isChecked() is True:
            sh_file = 'create_virtualenv.sh'
            with open(path.join(str(self.outdir.text()), sh_file), 'w') as _sh:
                self.output.append(self.formatInfoMsg('''INFO: OK: Writing Bash:
                    {}'''.format(path.join(str(self.outdir.text()), sh_file))))
                _sh.write('#!/usr/bin/env bash' + linesep + cmd)
                _sh.close()
            self.output.append(self.formatInfoMsg('INFO: OK: Bash chmod: 775'))
            try:
                chmod(path.join(str(self.outdir.text()), sh_file), 0775)  # Py2
            except:
                chmod(path.join(str(self.outdir.text()), sh_file), 0o775)  # Py3
        self.readOutput()
        self.readErrors()
        self.button.setEnabled(True)

    def _process_finished(self):
        """ finished sucessfully """
        self.output.append(self.formatInfoMsg(
                            'INFO: OK: Finished at {}'.format(datetime.now())))
        # remove all *.PYC bytecode
        if self.qckb7.isChecked() is True:
            self.output.append(self.formatInfoMsg(' INFO: OK: Removing *.PYC '))
            self.output.append(self.formatInfoMsg(' INFO: This takes a moment'))
            [remove(path.join(root, f)) for root, f in list(itertools.chain(*
            [list(itertools.product([root], files))
            for root, dirs, files in walk(str(self.outdir.text()).strip())]))
            if f.endswith(('.pyc', '.PYC')) and not f.startswith('.')]
        # write a .log file on target
        if self.qckb9.isChecked() is True:
            log_file = 'virtualenv_gui.log'
            with open(path.join(str(self.outdir.text()), log_file), 'w') as log:
                self.output.append(self.formatInfoMsg('''INFO: OK: Writing Logs:
                    {}'''.format(path.join(str(self.outdir.text()), log_file))))
                log.write(self.output.toPlainText())
                log.close()
        # open target dir
        if self.qckb8.isChecked() is True:
            try:
                startfile(str(self.outdir.text()))
            except:
                Popen(["xdg-open", str(self.outdir.text())])
        self.output.selectAll()
        self.output.setFocus()

    def toggle_options_group(self):
        ' toggle on off the options group '
        if self.group2.isChecked() is True:
            [a.setChecked(True) for a in (self.qckb1, self.qckb4, self.qckb7,
                                self.chrt, self.qckb8, self.qckb9, self.qckb11)]
            self.combo1.setValue(2.7)
            self.group2.graphicsEffect().setEnabled(False)
        else:
            [a.setChecked(False) for a in (self.qckb1, self.qckb4, self.qckb7,
                                self.chrt, self.qckb8, self.qckb9, self.qckb11)]
            self.group2.graphicsEffect().setEnabled(True)

    def finish(self):
        ' clear when finish '
        self.process.kill()
Ejemplo n.º 29
0
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        self.process, self.mainwidget = QProcess(), QTabWidget()
        self.process.readyReadStandardOutput.connect(self.readOutput)
        self.process.readyReadStandardError.connect(self.readErrors)
        self.process.finished.connect(self._process_finished)
        self.process.error.connect(self._process_finished)
        self.mainwidget.tabCloseRequested.connect(lambda:
            self.mainwidget.setTabPosition(1)
            if self.mainwidget.tabPosition() == 0
            else self.mainwidget.setTabPosition(0))
        self.mainwidget.setStyleSheet('QTabBar{font-weight:bold;}')
        self.mainwidget.setMovable(True)
        self.mainwidget.setTabsClosable(True)
        self.dock, self.scrollable = QDockWidget(), QScrollArea()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(self.mainwidget)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        self.locator.get_service('misc').add_widget(self.dock,
                                 QIcon.fromTheme("face-sad"), __doc__)
        self.tab1, self.tab2, self.tab3 = QGroupBox(), QGroupBox(), QGroupBox()
        self.tab4, self.tab5, self.tab6 = QGroupBox(), QGroupBox(), QGroupBox()
        for a, b in ((self.tab1, 'Basics'), (self.tab2, 'Coverage'),
            (self.tab3, 'Extensions'), (self.tab5, 'Regex'),
             (self.tab4, 'Paths'), (self.tab6, 'Run')):
            a.setTitle(b)
            a.setToolTip(b)
            self.mainwidget.addTab(a, QIcon.fromTheme("face-sad"), b)
        QPushButton(QIcon.fromTheme("help-about"), 'About', self.dock
          ).clicked.connect(lambda: QMessageBox.information(self.dock, __doc__,
          ''.join((__doc__, __version__, __license__, 'by', __author__))))

        groupl, groupr, co = QWidget(), QWidget(), QGroupBox()
        self.qckb1 = QCheckBox('Open target directory later')
        self.qckb2 = QCheckBox('Save a LOG file to target later')
        self.qckb3 = QCheckBox('Verbose operation')
        self.qckb4 = QCheckBox('Force Stop on Error')
        self.qckb5 = QCheckBox('Scan Executable files for Tests')
        vboxgl, vboxgr = QVBoxLayout(groupl), QVBoxLayout(groupr)
        for a in (self.qckb1, self.qckb2, self.qckb3, self.qckb4, self.qckb5):
            vboxgl.addWidget(a)
            a.setToolTip(a.text())
        self.qckb6 = QCheckBox('No Byte Compile to .PYC or Delete .PYC later')
        self.qckb7 = QCheckBox('Dont touch sys.path when running tests')
        self.qckb8 = QCheckBox('Traverse all paths of a package')
        self.qckb9 = QCheckBox('Dont capture STDOUT, print STDOUT on the fly')
        self.qckb10 = QCheckBox('Clear all Logging handlers')
        for a in (self.qckb6, self.qckb7, self.qckb8, self.qckb9, self.qckb10):
            vboxgr.addWidget(a)
            a.setToolTip(a.text())
        vboxcon, self.framew = QHBoxLayout(co), QComboBox()
        [vboxcon.addWidget(a) for a in (groupl, groupr)]
        self.chrt = QCheckBox('LOW CPU priority for Backend Process')
        self.framew.addItems(['nosetests', 'PyTest', 'DocTest', 'Unittest',
                              'Django_Test', 'Django-Nose', 'None'])
        self.framew.currentIndexChanged.connect(lambda:  #FIXME refactor for 3
            QMessageBox.information(self.dock, __doc__, '<b>Only Nose for now'))
        self.framew.currentIndexChanged.connect(lambda:  #FIXME refactor for 3
            self.framew.setCurrentIndex(0))
        vboxg1 = QVBoxLayout(self.tab1)
        for each_widget in (QLabel('<b>Framework'), self.framew, self.chrt, co):
            vboxg1.addWidget(each_widget)

        self.t2ck1, self.t2sp1 = QCheckBox('Activate Coverage'), QSpinBox()
        self.t2ck2 = QCheckBox('Erase previously collected Coverage before run')
        self.t2ck3 = QCheckBox('Include all tests modules in Coverage reports')
        self.t2ck4 = QCheckBox('Include all python files on working directory')
        self.t2ck5 = QCheckBox('Produce HTML Coverage reports information')
        self.t2ck6 = QCheckBox('Include Branch Coverage in Coverage reports')
        self.t2sp1.setRange(10, 90)
        self.t2sp1.setValue(75)
        vboxg2 = QVBoxLayout(self.tab2)
        for each_widget in (QLabel('<b>Min Percentage'), self.t2sp1, self.t2ck1,
            self.t2ck2, self.t2ck3, self.t2ck4, self.t2ck5, self.t2ck6):
            vboxg2.addWidget(each_widget)

        groupi, groupd, vbxg3 = QGroupBox(), QGroupBox(), QHBoxLayout(self.tab3)
        vboxgi, vboxgd = QVBoxLayout(groupi), QVBoxLayout(groupd)
        self.t3ck1 = QCheckBox('Activate DocTest to find and run doctests')
        self.t3ck2 = QCheckBox('Look for any doctests in tests modules too')
        self.t3ck3 = QCheckBox('Activate isolation (Do Not use with Coverage!)')
        self.t3ck4 = QCheckBox('Use Detailed Errors, evaluate failed asserts')
        for a in (self.t3ck1, self.t3ck2, self.t3ck3, self.t3ck4):
            vboxgi.addWidget(a)
            a.setToolTip(a.text())
        self.t3ck5 = QCheckBox('Disable special handling of SkipTest exception')
        self.t3ck6 = QCheckBox('Run the tests that failed in the last test run')
        self.t3ck7 = QCheckBox('Use AllModules, Collect tests from all modules')
        self.t3ck8 = QCheckBox('Collect tests names only, do Not run any tests')
        for a in (self.t3ck5, self.t3ck6, self.t3ck7, self.t3ck8):
            vboxgd.addWidget(a)
            a.setToolTip(a.text())
        [vbxg3.addWidget(a) for a in (groupi, groupd)]

        self.t4le1, self.t4le2 = QLineEdit(), QLineEdit(path.expanduser("~"))
        self.t4le1.setCompleter(self.completer)
        self.t4le2.setCompleter(self.completer)
        self.t4le1.setPlaceholderText(' /full/path/to/a/folder/ ')
        self.t4le2.setPlaceholderText(' /full/path/to/a/folder/ ')
        le1b = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        le1b.setMinimumSize(50, 50)
        le1b.clicked.connect(lambda: self.t4le1.setText(
            QFileDialog.getExistingDirectory(None, '', path.expanduser("~"))))
        le2b = QPushButton(QIcon.fromTheme("folder-open"), 'Open')
        le2b.clicked.connect(lambda: self.t4le2.setText(
            QFileDialog.getExistingDirectory(None, '', path.expanduser("~"))))
        vboxg4 = QVBoxLayout(self.tab4)
        for a in (QLabel('<b>Directory to look for Tests'), self.t4le1, le1b,
            QLabel('<b>Directory to generate HTML Coverage'), self.t4le2, le2b):
            vboxg4.addWidget(a)
            a.setToolTip(a.text())

        self.t5le1 = QLineEdit(r'(?:^|[\b_\./-])[Tt]est')
        self.t5le2 = QLineEdit()
        self.t5le3, vboxg5 = QLineEdit(), QVBoxLayout(self.tab5)
        r = QPushButton('Reset')
        r.clicked.connect(lambda: self.t5le1.setText(r'(?:^|[\b_\./-])[Tt]est'))
        for a in (QLabel('<b>Matching Name Regex to be test'), self.t5le1, r,
            QLabel('<b>Force Include Regex Tests'), self.t5le2,
            QLabel('<b>Force Exclude Regex Tests'), self.t5le3):
            vboxg5.addWidget(a)
            a.setToolTip(a.text())

        self.output = QTextEdit(''' Engineering is the art of making what you
            want from things you can get.    -Dhobi''')
        self.runbtn = QPushButton(QIcon.fromTheme("face-sad"), 'Start Testing!')
        self.runbtn.setMinimumSize(75, 50)
        self.runbtn.clicked.connect(self.run)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.runbtn.setGraphicsEffect(glow)
        self.kbt = QPushButton(QIcon.fromTheme("application-exit"), 'Kill')
        self.kbt.clicked.connect(lambda: self.process.kill())
        vboxg6 = QVBoxLayout(self.tab6)
        for each_widget in (QLabel('Logs'), self.output, self.runbtn, self.kbt):
            vboxg6.addWidget(each_widget)
        [a.setChecked(True) for a in (self.chrt, self.qckb2, self.qckb3,
                                      self.qckb10, self.t2ck1, self.t2ck2,
                                      self.t2ck5, self.t3ck1, self.t3ck4)]
        self.mainwidget.setCurrentIndex(4)
Ejemplo n.º 30
0
    def setupUi(self, Lekhonee):
        Lekhonee.setObjectName("Lekhonee")
        Lekhonee.resize(1001, 586)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(":/pixmaps/lekhonee.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        Lekhonee.setWindowIcon(icon)
        self.centralwidget = QtGui.QWidget(Lekhonee)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout_5 = QtGui.QGridLayout(self.centralwidget)
        self.gridLayout_5.setObjectName("gridLayout_5")
        self.verticalLayout = QtGui.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.hboxlayout = QtGui.QHBoxLayout()
        self.hboxlayout.setObjectName("hboxlayout")
        self.label = QtGui.QLabel(self.centralwidget)
        self.label.setObjectName("label")
        self.hboxlayout.addWidget(self.label)
        self.titleTxt = QtGui.QLineEdit(self.centralwidget)
        self.titleTxt.setObjectName("titleTxt")
        self.hboxlayout.addWidget(self.titleTxt)
        self.commentCheckBox = QtGui.QCheckBox(self.centralwidget)
        self.commentCheckBox.setChecked(True)
        self.commentCheckBox.setObjectName("commentCheckBox")
        self.hboxlayout.addWidget(self.commentCheckBox)
        self.verticalLayout.addLayout(self.hboxlayout)
        self.hboxlayout1 = QtGui.QHBoxLayout()
        self.hboxlayout1.setObjectName("hboxlayout1")
        self.boldBttn = QtGui.QPushButton(self.centralwidget)
        font = QtGui.QFont()
        font.setWeight(75)
        font.setBold(True)
        self.boldBttn.setFont(font)
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap(":/icons/bold.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.boldBttn.setIcon(icon1)
        self.boldBttn.setIconSize(QtCore.QSize(20, 20))
        self.boldBttn.setObjectName("boldBttn")
        self.hboxlayout1.addWidget(self.boldBttn)
        self.italicBttn = QtGui.QPushButton(self.centralwidget)
        font = QtGui.QFont()
        font.setWeight(50)
        font.setItalic(True)
        font.setBold(False)
        self.italicBttn.setFont(font)
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap(":/icons/italic.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.italicBttn.setIcon(icon2)
        self.italicBttn.setIconSize(QtCore.QSize(20, 20))
        self.italicBttn.setObjectName("italicBttn")
        self.hboxlayout1.addWidget(self.italicBttn)
        self.linkBttn = QtGui.QPushButton(self.centralwidget)
        self.linkBttn.setObjectName("linkBttn")
        self.hboxlayout1.addWidget(self.linkBttn)
        self.imageBttn = QtGui.QPushButton(self.centralwidget)
        icon3 = QtGui.QIcon()
        icon3.addPixmap(QtGui.QPixmap(":/icons/insert-image.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.imageBttn.setIcon(icon3)
        self.imageBttn.setIconSize(QtCore.QSize(20, 20))
        self.imageBttn.setObjectName("imageBttn")
        self.hboxlayout1.addWidget(self.imageBttn)
        spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
        self.hboxlayout1.addItem(spacerItem)
        self.oldPostBttn = QtGui.QPushButton(self.centralwidget)
        self.oldPostBttn.setCheckable(True)
        self.oldPostBttn.setObjectName("oldPostBttn")
        self.hboxlayout1.addWidget(self.oldPostBttn)
        self.stateBttn = QtGui.QPushButton(self.centralwidget)
        self.stateBttn.setObjectName("stateBttn")
        self.hboxlayout1.addWidget(self.stateBttn)
        self.verticalLayout.addLayout(self.hboxlayout1)
        self.stack = QtGui.QStackedWidget(self.centralwidget)
        self.stack.setObjectName("stack")
        self.page = QtGui.QWidget()
        self.page.setObjectName("page")
        self.gridLayout = QtGui.QGridLayout(self.page)
        self.gridLayout.setObjectName("gridLayout")
        self.blogTxt = KTextEdit(self.page)
        self.blogTxt.setObjectName("blogTxt")
        self.gridLayout.addWidget(self.blogTxt, 0, 0, 1, 1)
        self.stack.addWidget(self.page)
        self.page_2 = QtGui.QWidget()
        self.page_2.setObjectName("page_2")
        self.gridLayout_2 = QtGui.QGridLayout(self.page_2)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.webView = QtWebKit.QWebView(self.page_2)
        self.webView.setUrl(QtCore.QUrl("about:blank"))
        self.webView.setObjectName("webView")
        self.gridLayout_2.addWidget(self.webView, 0, 0, 1, 1)
        self.stack.addWidget(self.page_2)
        self.page_3 = QtGui.QWidget()
        self.page_3.setObjectName("page_3")
        self.gridLayout_4 = QtGui.QGridLayout(self.page_3)
        self.gridLayout_4.setObjectName("gridLayout_4")
        self.entryList = QtGui.QListWidget(self.page_3)
        self.entryList.setObjectName("entryList")
        self.gridLayout_4.addWidget(self.entryList, 0, 0, 1, 1)
        self.stack.addWidget(self.page_3)
        self.verticalLayout.addWidget(self.stack)
        self.uploadframe = QtGui.QFrame(self.centralwidget)
        self.uploadframe.setFrameShape(QtGui.QFrame.StyledPanel)
        self.uploadframe.setFrameShadow(QtGui.QFrame.Plain)
        self.uploadframe.setObjectName("uploadframe")
        self.gridLayout_3 = QtGui.QGridLayout(self.uploadframe)
        self.gridLayout_3.setObjectName("gridLayout_3")
        self.horizontalLayout_3 = QtGui.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.fileTxt = QtGui.QLineEdit(self.uploadframe)
        self.fileTxt.setObjectName("fileTxt")
        self.horizontalLayout_3.addWidget(self.fileTxt)
        self.selectUploadBttn = QtGui.QPushButton(self.uploadframe)
        self.selectUploadBttn.setObjectName("selectUploadBttn")
        self.horizontalLayout_3.addWidget(self.selectUploadBttn)
        self.gridLayout_3.addLayout(self.horizontalLayout_3, 0, 0, 1, 1)
        self.horizontalLayout_2 = QtGui.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.uploadCancelBttn = QtGui.QPushButton(self.uploadframe)
        self.uploadCancelBttn.setObjectName("uploadCancelBttn")
        self.horizontalLayout_2.addWidget(self.uploadCancelBttn)
        spacerItem1 = QtGui.QSpacerItem(328, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem1)
        self.uploadBttn = QtGui.QPushButton(self.uploadframe)
        self.uploadBttn.setObjectName("uploadBttn")
        self.horizontalLayout_2.addWidget(self.uploadBttn)
        self.gridLayout_3.addLayout(self.horizontalLayout_2, 1, 0, 1, 1)
        self.verticalLayout.addWidget(self.uploadframe)
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.spellCheckBox = QtGui.QCheckBox(self.centralwidget)
        self.spellCheckBox.setObjectName("spellCheckBox")
        self.horizontalLayout.addWidget(self.spellCheckBox)
        self.tagsTxt = QtGui.QLineEdit(self.centralwidget)
        self.tagsTxt.setObjectName("tagsTxt")
        self.horizontalLayout.addWidget(self.tagsTxt)
        spacerItem2 = QtGui.QSpacerItem(38, 28, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem2)
        self.draftBttn = QtGui.QPushButton(self.centralwidget)
        icon4 = QtGui.QIcon()
        icon4.addPixmap(QtGui.QPixmap(":/icons/draft.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.draftBttn.setIcon(icon4)
        self.draftBttn.setIconSize(QtCore.QSize(20, 20))
        self.draftBttn.setObjectName("draftBttn")
        self.horizontalLayout.addWidget(self.draftBttn)
        self.publishBttn = QtGui.QPushButton(self.centralwidget)
        icon5 = QtGui.QIcon()
        icon5.addPixmap(QtGui.QPixmap(":/icons/internet.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.publishBttn.setIcon(icon5)
        self.publishBttn.setIconSize(QtCore.QSize(20, 20))
        self.publishBttn.setObjectName("publishBttn")
        self.horizontalLayout.addWidget(self.publishBttn)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.gridLayout_5.addLayout(self.verticalLayout, 0, 0, 1, 1)
        self.vboxlayout = QtGui.QVBoxLayout()
        self.vboxlayout.setObjectName("vboxlayout")
        spacerItem3 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
        self.vboxlayout.addItem(spacerItem3)
        self.label_2 = QtGui.QLabel(self.centralwidget)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.label_2.sizePolicy().hasHeightForWidth())
        self.label_2.setSizePolicy(sizePolicy)
        self.label_2.setObjectName("label_2")
        self.vboxlayout.addWidget(self.label_2)
        self.categoryList = QtGui.QListWidget(self.centralwidget)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.categoryList.sizePolicy().hasHeightForWidth())
        self.categoryList.setSizePolicy(sizePolicy)
        self.categoryList.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
        self.categoryList.setObjectName("categoryList")
        self.vboxlayout.addWidget(self.categoryList)
        self.getCategoriesBttn = QtGui.QPushButton(self.centralwidget)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.getCategoriesBttn.sizePolicy().hasHeightForWidth())
        self.getCategoriesBttn.setSizePolicy(sizePolicy)
        icon6 = QtGui.QIcon()
        icon6.addPixmap(QtGui.QPixmap(":/icons/get-arrow.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.getCategoriesBttn.setIcon(icon6)
        self.getCategoriesBttn.setIconSize(QtCore.QSize(20, 20))
        self.getCategoriesBttn.setObjectName("getCategoriesBttn")
        self.vboxlayout.addWidget(self.getCategoriesBttn)
        self.addCategoryTxt = QtGui.QLineEdit(self.centralwidget)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.addCategoryTxt.sizePolicy().hasHeightForWidth())
        self.addCategoryTxt.setSizePolicy(sizePolicy)
        self.addCategoryTxt.setObjectName("addCategoryTxt")
        self.vboxlayout.addWidget(self.addCategoryTxt)
        self.addCategoryBttn = QtGui.QPushButton(self.centralwidget)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.addCategoryBttn.sizePolicy().hasHeightForWidth())
        self.addCategoryBttn.setSizePolicy(sizePolicy)
        self.addCategoryBttn.setObjectName("addCategoryBttn")
        self.vboxlayout.addWidget(self.addCategoryBttn)
        self.gridLayout_5.addLayout(self.vboxlayout, 0, 1, 1, 1)
        self.serverTabs = QtGui.QTabWidget(self.centralwidget)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.serverTabs.sizePolicy().hasHeightForWidth())
        self.serverTabs.setSizePolicy(sizePolicy)
        self.serverTabs.setObjectName("serverTabs")
        self.tab = QtGui.QWidget()
        self.tab.setObjectName("tab")
        self.gridLayout_6 = QtGui.QGridLayout(self.tab)
        self.gridLayout_6.setObjectName("gridLayout_6")
        self.addPageBttn = QtGui.QPushButton(self.tab)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.addPageBttn.sizePolicy().hasHeightForWidth())
        self.addPageBttn.setSizePolicy(sizePolicy)
        icon7 = QtGui.QIcon()
        icon7.addPixmap(QtGui.QPixmap(":/icons/addpage.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.addPageBttn.setIcon(icon7)
        self.addPageBttn.setIconSize(QtCore.QSize(20, 20))
        self.addPageBttn.setObjectName("addPageBttn")
        self.gridLayout_6.addWidget(self.addPageBttn, 0, 0, 1, 1)
        self.serverTabs.addTab(self.tab, "")
        self.tab_2 = QtGui.QWidget()
        self.tab_2.setObjectName("tab_2")
        self.serverTabs.addTab(self.tab_2, "")
        self.gridLayout_5.addWidget(self.serverTabs, 1, 0, 1, 1)
        Lekhonee.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(Lekhonee)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1001, 28))
        self.menubar.setObjectName("menubar")
        self.menu_File = QtGui.QMenu(self.menubar)
        self.menu_File.setObjectName("menu_File")
        self.menu_Edit = QtGui.QMenu(self.menubar)
        self.menu_Edit.setObjectName("menu_Edit")
        self.menuHTML_Tags = QtGui.QMenu(self.menubar)
        self.menuHTML_Tags.setObjectName("menuHTML_Tags")
        Lekhonee.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(Lekhonee)
        self.statusbar.setObjectName("statusbar")
        Lekhonee.setStatusBar(self.statusbar)
        self.action_Open = QtGui.QAction(Lekhonee)
        icon8 = QtGui.QIcon()
        icon8.addPixmap(QtGui.QPixmap(":/icons/document-open.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.action_Open.setIcon(icon8)
        self.action_Open.setObjectName("action_Open")
        self.action_Save = QtGui.QAction(Lekhonee)
        icon9 = QtGui.QIcon()
        icon9.addPixmap(QtGui.QPixmap(":/icons/document-save.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.action_Save.setIcon(icon9)
        self.action_Save.setObjectName("action_Save")
        self.actionBold = QtGui.QAction(Lekhonee)
        self.actionBold.setIcon(icon1)
        self.actionBold.setObjectName("actionBold")
        self.actionItalic = QtGui.QAction(Lekhonee)
        self.actionItalic.setIcon(icon2)
        self.actionItalic.setObjectName("actionItalic")
        self.actionUnderline = QtGui.QAction(Lekhonee)
        icon10 = QtGui.QIcon()
        icon10.addPixmap(QtGui.QPixmap(":/icons/underline.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionUnderline.setIcon(icon10)
        self.actionUnderline.setObjectName("actionUnderline")
        self.actionSuperscript = QtGui.QAction(Lekhonee)
        icon11 = QtGui.QIcon()
        icon11.addPixmap(QtGui.QPixmap(":/icons/superscript.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionSuperscript.setIcon(icon11)
        self.actionSuperscript.setObjectName("actionSuperscript")
        self.actionSubscript = QtGui.QAction(Lekhonee)
        icon12 = QtGui.QIcon()
        icon12.addPixmap(QtGui.QPixmap(":/icons/subscript.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionSubscript.setIcon(icon12)
        self.actionSubscript.setObjectName("actionSubscript")
        self.actionInsert_Image = QtGui.QAction(Lekhonee)
        self.actionInsert_Image.setIcon(icon3)
        self.actionInsert_Image.setObjectName("actionInsert_Image")
        self.actionInsert_link = QtGui.QAction(Lekhonee)
        self.actionInsert_link.setObjectName("actionInsert_link")
        self.actionIn_FireFox = QtGui.QAction(Lekhonee)
        self.actionIn_FireFox.setObjectName("actionIn_FireFox")
        self.actionIn_Konqueror = QtGui.QAction(Lekhonee)
        icon13 = QtGui.QIcon()
        icon13.addPixmap(QtGui.QPixmap(":/icons/konqueror.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionIn_Konqueror.setIcon(icon13)
        self.actionIn_Konqueror.setObjectName("actionIn_Konqueror")
        self.actionPrevious_Entries = QtGui.QAction(Lekhonee)
        self.actionPrevious_Entries.setEnabled(False)
        self.actionPrevious_Entries.setObjectName("actionPrevious_Entries")
        self.actionPreferences = QtGui.QAction(Lekhonee)
        icon14 = QtGui.QIcon()
        icon14.addPixmap(QtGui.QPixmap(":/icons/configure.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionPreferences.setIcon(icon14)
        self.actionPreferences.setObjectName("actionPreferences")
        self.action_Quit = QtGui.QAction(Lekhonee)
        icon15 = QtGui.QIcon()
        icon15.addPixmap(QtGui.QPixmap(":/icons/application-exit.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.action_Quit.setIcon(icon15)
        self.action_Quit.setObjectName("action_Quit")
        self.action_New = QtGui.QAction(Lekhonee)
        icon16 = QtGui.QIcon()
        icon16.addPixmap(QtGui.QPixmap(":/icons/document-new.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.action_New.setIcon(icon16)
        self.action_New.setObjectName("action_New")
        self.action_Help = QtGui.QAction(Lekhonee)
        self.action_Help.setEnabled(False)
        self.action_Help.setObjectName("action_Help")
        self.actionAbout_Chotha = QtGui.QAction(Lekhonee)
        icon17 = QtGui.QIcon()
        icon17.addPixmap(QtGui.QPixmap("../../../../../../usr/share/pixmaps/chotha.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionAbout_Chotha.setIcon(icon17)
        self.actionAbout_Chotha.setObjectName("actionAbout_Chotha")
        self.actionLast_Entry = QtGui.QAction(Lekhonee)
        self.actionLast_Entry.setObjectName("actionLast_Entry")
        self.actionLekhonee_msg = QtGui.QAction(Lekhonee)
        self.actionLekhonee_msg.setCheckable(True)
        self.actionLekhonee_msg.setChecked(True)
        self.actionLekhonee_msg.setObjectName("actionLekhonee_msg")
        self.actionOld_Posts = QtGui.QAction(Lekhonee)
        self.actionOld_Posts.setObjectName("actionOld_Posts")
        self.actionUpload_File = QtGui.QAction(Lekhonee)
        self.actionUpload_File.setObjectName("actionUpload_File")
        self.menu_File.addAction(self.action_New)
        self.menu_File.addAction(self.action_Open)
        self.menu_File.addAction(self.action_Save)
        self.menu_File.addAction(self.action_Quit)
        self.menu_Edit.addAction(self.actionLast_Entry)
        self.menu_Edit.addAction(self.actionLekhonee_msg)
        self.menu_Edit.addAction(self.actionUpload_File)
        self.menu_Edit.addAction(self.actionPreferences)
        self.menuHTML_Tags.addAction(self.actionBold)
        self.menuHTML_Tags.addAction(self.actionItalic)
        self.menuHTML_Tags.addAction(self.actionUnderline)
        self.menuHTML_Tags.addSeparator()
        self.menuHTML_Tags.addAction(self.actionSuperscript)
        self.menuHTML_Tags.addAction(self.actionSubscript)
        self.menuHTML_Tags.addSeparator()
        self.menuHTML_Tags.addAction(self.actionInsert_Image)
        self.menuHTML_Tags.addAction(self.actionInsert_link)
        self.menubar.addAction(self.menu_File.menuAction())
        self.menubar.addAction(self.menu_Edit.menuAction())
        self.menubar.addAction(self.menuHTML_Tags.menuAction())

        self.retranslateUi(Lekhonee)
        self.stack.setCurrentIndex(0)
        self.serverTabs.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(Lekhonee)
        Lekhonee.setTabOrder(self.titleTxt, self.commentCheckBox)
        Lekhonee.setTabOrder(self.commentCheckBox, self.publishBttn)
        Lekhonee.setTabOrder(self.publishBttn, self.draftBttn)
        Lekhonee.setTabOrder(self.draftBttn, self.boldBttn)
        Lekhonee.setTabOrder(self.boldBttn, self.italicBttn)
        Lekhonee.setTabOrder(self.italicBttn, self.linkBttn)
        Lekhonee.setTabOrder(self.linkBttn, self.stateBttn)
        Lekhonee.setTabOrder(self.stateBttn, self.categoryList)
Ejemplo n.º 31
0
class Main(plugin.Plugin):
    " Main Class "
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)

        self.desktop, self.project, menu = '', '', QMenu('Vagrant')
        menu.addAction('UP', lambda: self.vagrant_c('up'))
        menu.addAction('HALT', lambda: self.vagrant_c('halt'))
        menu.addAction('RELOAD', lambda: self.vagrant_c('reload'))
        menu.addAction('STATUS', lambda: self.vagrant_c('status'))
        menu.addAction('SUSPEND', lambda: self.vagrant_c('suspend'))
        menu.addAction('RESUME', lambda: self.vagrant_c('resume'))
        menu.addAction('PROVISION', lambda: self.vagrant_c('provision'))
        menu.addAction('PACKAGE', lambda: self.vagrant_c('package'))
        menu.addAction('INIT', lambda: self.vagrant_c('init'))
        menu.addSeparator()
        menu.addAction('DESTROY (!!!)', lambda: self.vagrant_c('destroy'))
        self.locator.get_service('explorer').add_project_menu(menu, lang='all')

        self.process = QProcess()
        self.process.readyReadStandardOutput.connect(self.readOutput)
        self.process.readyReadStandardError.connect(self.readErrors)
        self.process.finished.connect(self._process_finished)
        self.process.error.connect(self._process_finished)

        # Proxy support, by reading http_proxy os env variable
        proxy_url = QUrl(environ.get('http_proxy', ''))
        QNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.HttpProxy
            if str(proxy_url.scheme()).startswith('http')
            else QNetworkProxy.Socks5Proxy, proxy_url.host(), proxy_url.port(),
                 proxy_url.userName(), proxy_url.password())) \
            if 'http_proxy' in environ else None

        self.mainwidget = QTabWidget()
        self.mainwidget.tabCloseRequested.connect(lambda:
            self.mainwidget.setTabPosition(1)
            if self.mainwidget.tabPosition() == 0
            else self.mainwidget.setTabPosition(0))
        self.mainwidget.setStyleSheet('QTabBar{font-weight:bold;}')
        self.mainwidget.setMovable(True)
        self.mainwidget.setTabsClosable(True)

        self.dock, self.scrollable = QDockWidget(), QScrollArea()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(self.mainwidget)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)

        self.locator.get_service('misc').add_widget(self.dock,
                                 QIcon.fromTheme("virtualbox"), __doc__)

        self.tab1, self.tab2, self.tab3 = QGroupBox(), QGroupBox(), QGroupBox()
        self.tab4, self.tab5, self.tab6 = QGroupBox(), QGroupBox(), QGroupBox()
        for a, b in ((self.tab1, 'Basics'), (self.tab2, 'General Options'),
            (self.tab3, 'VM Package Manager'), (self.tab4, 'VM Provisioning'),
            (self.tab5, 'VM Desktop GUI'), (self.tab6, 'Run')):
            a.setTitle(b)
            a.setToolTip(b)
            self.mainwidget.addTab(a, QIcon.fromTheme("virtualbox"), b)

        QPushButton(QIcon.fromTheme("help-about"), 'About', self.dock
        ).clicked.connect(lambda: QMessageBox.information(self.dock, __doc__,
        HELPMSG))

        self.vmname = QLineEdit(self.get_name())
        self.vmname.setPlaceholderText('type_your_VM_name_here_without_spaces')
        self.vmname.setToolTip('Type VM name, no spaces or special characters')
        self.target = QLabel('<b>Vagrant Target Folder: ' +
                             path.join(BASE, self.vmname.text()))
        self.vmname.textChanged.connect(lambda: self.target.setText(
            '<b>Vagrant Target Folder: ' + path.join(BASE, self.vmname.text())))
        self.btn1 = QPushButton(QIcon.fromTheme("face-smile-big"), 'Suggestion')
        self.btn1.setToolTip('Suggest me a Random VM name !')
        self.btn1.clicked.connect(lambda: self.vmname.setText(self.get_name()))
        self.vmcode, self.vmarch = QComboBox(), QComboBox()
        self.vmcode.addItems(['saucy', 'raring', 'quantal', 'precise'])
        self.vmarch.addItems(['x86_64 (amd64) 64-Bits', 'x86 (i386) 32-Bits'])
        vboxg1 = QVBoxLayout(self.tab1)
        for each_widget in (QLabel('<b>Name for VM'), self.vmname, self.btn1,
            QLabel('<b>Choose Ubuntu Codename for the VM:</b>'), self.vmcode,
            QLabel('<b>Choose Architecture for VM:'), self.vmarch, self.target):
            vboxg1.addWidget(each_widget)

        self.chrt = QCheckBox('LOW CPU priority for Backend Process')
        self.chttps = QComboBox()
        self.chttps.addItems(['https', 'http'])
        try:
            self.vinfo1 = QLabel('''<b> Vagrant Backend Version: </b> {},
                <b> VirtualBox Backend Version: </b> {}. '''.format(
                getoutput('vagrant --version', shell=1).strip(),
                getoutput('vboxmanage --version', shell=1).strip()))
        except:
            self.vinfo1 = QLabel('<b>Warning: Failed to query Vagrant Backend!')
        self.qckb1 = QCheckBox(' Open target directory later')
        self.qckb1.setToolTip('Open the target directory when finished')
        self.qckb2 = QCheckBox(' Save a LOG file to target later')
        self.qckb2.setToolTip('Save a read-only .LOG file to target')
        self.qckb3 = QCheckBox(' NO run Headless Mode, use a Window')
        self.qckb3.setToolTip('Show the VM on a Window GUI instead of Headless')
        self.cpu, self.ram = QSpinBox(), QSpinBox()
        self.cpu.setRange(25, 99)
        self.cpu.setValue(99)
        self.ram.setRange(512, 4096)
        self.ram.setValue(1024)
        vboxg2 = QVBoxLayout(self.tab2)
        for each_widget in (self.qckb1, self.qckb2, self.qckb3, self.chrt,
            QLabel('<b>Max CPU Limit for VM:</b>'), self.cpu,
            QLabel('<b>Max RAM Limit for VM:</b>'), self.ram,
            QLabel('<b>Download Protocol Type:</b>'), self.chttps, self.vinfo1):
            vboxg2.addWidget(each_widget)

        self.qckb10 = QCheckBox('Run apt-get update on the created VM')
        self.qckb11 = QCheckBox('Run apt-get dist-upgrade on the created VM')
        self.qckb12 = QCheckBox('Run apt-get check on the created VM')
        self.qckb12 = QCheckBox('Run apt-get clean on the created VM')
        self.qckb13 = QCheckBox('Run apt-get autoremove on the created VM')
        self.qckb14 = QCheckBox('Try to Fix Broken packages if any on the VM')
        self.aptproxy, self.portredirect = QLineEdit(), QLineEdit('8000, 9000')
        self.aptproxy.setPlaceholderText(' user:password@proxyaddress:port ')
        vboxg3 = QVBoxLayout(self.tab3)
        for each_widget in (self.qckb10, self.qckb11, self.qckb12, self.qckb13,
            self.qckb14,
            QLabel('<b>Network Proxy for apt-get on the VM'), self.aptproxy,
            QLabel('<b>Network Port Redirects for the VM'), self.portredirect):
            vboxg3.addWidget(each_widget)

        self.aptpkg = QTextEdit('build-essential git python-pip vim mc wget')
        self.aptppa, self.pippkg = QLineEdit(), QTextEdit('virtualenv yolk')
        self.aptppa.setPlaceholderText(' ppa:ninja-ide-developers/daily ')
        self.requirements = QLineEdit()
        self.requirements.setPlaceholderText(' /full/path/to/requirements.txt ')
        self.requirements.setCompleter(self.completer)
        vboxg4 = QVBoxLayout(self.tab4)
        for each_widget in (QLabel('<b>Custom APT Ubuntu package'), self.aptpkg,
            QLabel('<b>Custom APT Ubuntu PPA:</b>      '), self.aptppa,
            QLabel('<b>Custom PIP Python packages:</b> '), self.pippkg,
            QLabel('<b>Custom PIP Python requirements: '), self.requirements):
            vboxg4.addWidget(each_widget)

        self.buttonGroup = QButtonGroup()
        self.buttonGroup.buttonClicked[QAbstractButton].connect(self.get_de_pkg)
        vboxg5 = QVBoxLayout(self.tab5)
        for i, d in enumerate(('Ubuntu Unity', 'KDE Plasma', 'LXDE', 'XFCE')):
            button = QPushButton(d)
            button.setCheckable(True)
            button.setMinimumSize(75, 50)
            button.setToolTip(d)
            vboxg5.addWidget(button)
            self.buttonGroup.addButton(button)

        self.output = QTextEdit('''
        We have persistent objects, they are called files.  -Ken Thompson. ''')
        self.runbtn = QPushButton(QIcon.fromTheme("media-playback-start"),
            'Start Vagrant Instrumentation Now !')
        self.runbtn.setMinimumSize(75, 50)
        self.runbtn.clicked.connect(self.build)
        glow = QGraphicsDropShadowEffect(self)
        glow.setOffset(0)
        glow.setBlurRadius(99)
        glow.setColor(QColor(99, 255, 255))
        self.runbtn.setGraphicsEffect(glow)
        self.stopbt = QPushButton(QIcon.fromTheme("media-playback-stop"),
            'Stop Vagrant')
        self.stopbt.clicked.connect(lambda: self.process.stop())
        self.killbt = QPushButton(QIcon.fromTheme("application-exit"),
            'Force Kill Vagrant')
        self.killbt.clicked.connect(lambda: self.process.kill())
        vboxg6 = QVBoxLayout(self.tab6)
        for each_widget in (QLabel('<b>Multiprocess Output Logs'), self.output,
            self.runbtn, self.stopbt, self.killbt):
            vboxg6.addWidget(each_widget)

        [a.setChecked(True) for a in (self.qckb1, self.qckb2, self.qckb3,
            self.qckb10, self.qckb11, self.qckb12, self.qckb13, self.qckb14,
            self.chrt)]
        self.mainwidget.setCurrentIndex(5)

    def get_de_pkg(self, button):
        ' get package from desktop name '
        if button.text() in 'Ubuntu Unity':
            self.desktop = 'ubuntu-desktop'
        elif button.text() in 'KDE Plasma':
            self.desktop = 'kubuntu-desktop'
        elif button.text() in 'LXDE':
            self.desktop = 'lubuntu-desktop'
        else:
            self.desktop = 'xubuntu-desktop'
        return self.desktop

    def get_name(self):
        ' return a random name of stars, planets and moons of solar system '
        return choice((getuser(), 'sun', 'mercury', 'venus', 'earth', 'mars',
            'neptun', 'ceres', 'pluto', 'haumea', 'makemake', 'eris', 'moon',
            'saturn', 'europa', 'ganymede', 'callisto', 'mimas', 'enceladus',
            'tethys', 'dione', 'rhea', 'titan', 'iapetus', 'miranda', 'ariel',
            'umbriel', 'titania', 'oberon', 'triton', 'charon', 'orcus', 'io',
            'ixion', 'varuna', 'quaoar', 'sedna', 'methone', 'jupiter', ))

    def readOutput(self):
        """Read and append output to the logBrowser"""
        self.output.append(str(self.process.readAllStandardOutput()))

    def readErrors(self):
        """Read and append errors to the logBrowser"""
        self.output.append(self.formatErrorMsg(str(
                                        self.process.readAllStandardError())))

    def formatErrorMsg(self, msg):
        """Format error messages in red color"""
        return self.formatMsg(msg, 'red')

    def formatInfoMsg(self, msg):
        """Format informative messages in blue color"""
        return self.formatMsg(msg, 'green')

    def formatMsg(self, msg, color):
        """Format message with the given color"""
        return '<font color="{}">{}</font>'.format(color, msg)

    def build(self):
        """Main function calling vagrant to generate the vm"""
        self.output.setText('')
        self.output.append(self.formatInfoMsg('INFO:{}'.format(datetime.now())))
        self.runbtn.setDisabled(True)
        base = path.join(BASE, self.vmname.text())
        try:
            self.output.append(self.formatInfoMsg('INFO: Dir: {}'.format(base)))
            makedirs(base)
        except:
            self.output.append(self.formatErrorMsg('ERROR:Target Folder Exist'))
        self.output.append(self.formatInfoMsg('INFO: Changed {}'.format(base)))
        chdir(base)
        try:
            self.output.append(self.formatInfoMsg('INFO:Removing Vagrant file'))
            remove(path.join(base, 'Vagrantfile'))
        except:
            self.output.append(self.formatErrorMsg('ERROR:Remove Vagrant file'))
        self.output.append(self.formatInfoMsg(' INFO: OK: Runing Vagrant Init'))
        cmd1 = getoutput('chrt --verbose -i 0 vagrant init', shell=True)
        self.output.append(self.formatInfoMsg('INFO:OK:Completed Vagrant Init'))
        self.output.append(self.formatInfoMsg('INFO: Command: {}'.format(cmd1)))
        cfg = CONFIG.format(self.vmname.text(), self.vmname.text(),
            self.chttps.currentText(), self.vmcode.currentText(),
            self.vmcode.currentText(),
            'amd64' if self.vmarch.currentIndex() is 0 else 'i386',
            '\n'.join(([
            '    config.vm.network :forwarded_port, host: {}, guest: {}'.format(
                a, a) for a in str(self.portredirect.text()).split(',')])),
            VBOXGUI.format(self.ram.value(), self.cpu.value())
                if self.qckb3.isChecked() is True else '')
        self.output.append(self.formatInfoMsg('INFO:OK:Config: {}'.format(cfg)))
        with open(path.join(base, 'Vagrantfile'), 'w') as f:
            f.write(cfg)
            self.output.append(self.formatInfoMsg('INFO: Writing Vagrantfile'))
            f.close()
        proxy = APTGET_PROXY.format(self.aptproxy.text(), self.aptproxy.text(),
            self.aptproxy.text(), self.aptproxy.text(), self.aptproxy.text(),
            self.aptproxy.text())
        prv = '\n'.join(('#!/usr/bin/env bash', '# -*- coding: utf-8 -*-',
        linesep * 2, "PS1='\[\e[1;32m\][\u@\h \W]\$\[\e[0m\] ' ; HISTSIZE=5000",
        '# Vagrant Bootstrap Provisioning generated by Vagrant Ninja!', linesep,
        proxy if len(self.aptproxy.text()) >= 5 else '',
        'add-apt-repository -s -y {}'.format(str(self.aptppa.text()).strip()),
        'apt-get -V -u -m -y update' if self.qckb10.isChecked() is True else '',
        'apt-get -y -m dist-upgrade' if self.qckb11.isChecked() is True else '',
        'apt-get -y -m autoremove' if self.qckb11.isChecked() is True else '',
        'apt-get -y clean' if self.qckb11.isChecked() is True else '',
        'dpkg --configure -a' if self.qckb11.isChecked() is True else '',
        'apt-get -y -f install' if self.qckb11.isChecked() is True else '',
        'apt-get -y check' if self.qckb11.isChecked() is True else '',
        'apt-get -y --force-yes install {}'.format(self.aptpkg.toPlainText()),
        'pip install --verbose {}'.format(self.pippkg.toPlainText()),
        'pip install --verbose -r {}'.format(self.requirements.text()),
        'apt-get -y --force-yes -m install {}'.format(self.desktop), linesep,
        'git config --global user.name "{}"'.format(getuser()),
        'git config --global color.branch auto',
        'git config --global color.diff auto',
        'git config --global color.interactive auto',
        'git config --global color.status auto',
        'git config --global credential.helper cache',
        'git config --global user.email "{}@gmail.com"'.format(getuser()),
        'git config --global push.default simple',
        'ufw status ; service ufw stop ; ufw disable ; swapoff --verbose --all',
        'export LANGUAGE=en_US.UTF-8', 'export LANG=en_US.UTF-8',
        'export LC_ALL=en_US.UTF-8', 'locale-gen en_US.UTF-8',
        'dpkg-reconfigure locales', ))
        self.output.append(self.formatInfoMsg('INFO:OK:Script: {}'.format(prv)))
        with open(path.join(base, 'bootstrap.sh'), 'w') as f:
            f.write(prv)
            self.output.append(self.formatInfoMsg('INFO: Writing bootstrap.sh'))
            f.close()
        try:
            chmod('bootstrap.sh', 0775)  # Py2
            self.output.append(self.formatInfoMsg('INFO: bootstrap.sh is 775'))
        except:
            chmod('bootstrap.sh', 0o775)  # Py3
            self.output.append(self.formatInfoMsg('INFO: bootstrap.sh is o775'))
        self.output.append(self.formatInfoMsg(''' INFO: OK:
        Vagrant Up needs time, depends on your Internet Connection Speed !'''))
        self.output.append(self.formatInfoMsg('INFO: OK: Running Vagrant Up !'))
        self.process.start('{}vagrant up'.format('chrt --verbose -i 0 '
            if self.chrt.isChecked() is True else ''))
        if not self.process.waitForStarted():
            self.output.append(self.formatErrorMsg('ERROR: FAIL: Vagrant Fail'))
            self.runbtn.setEnabled(True)
            return
        self.runbtn.setEnabled(True)
        chdir(path.expanduser("~"))

    def _process_finished(self):
        """finished sucessfully"""
        self.output.append(self.formatInfoMsg('INFO:{}'.format(datetime.now())))
        if self.qckb2.isChecked() is True:
            LOG_FILE = path.join(BASE, self.vmname.text(), 'vagrant_ninja.log')
            with open(LOG_FILE, 'w') as f:
                self.output.append(self.formatInfoMsg('INFO: OK: Writing .LOG'))
                f.write(self.output.toPlainText())
                f.close()
        if self.qckb1.isChecked() is True:
            self.output.append(self.formatInfoMsg('INFO:Opening Target Folder'))
            try:
                startfile(BASE)
            except:
                Popen(["xdg-open", BASE])
        chdir(path.expanduser("~"))

    def vagrant_c(self, option):
        ' run the choosed menu option, kind of quick-mode '
        self.output.setText('')
        self.output.append(self.formatInfoMsg('INFO:{}'.format(datetime.now())))
        self.runbtn.setDisabled(True)
        chdir(path.abspath(
          self.locator.get_service('explorer').get_current_project_item().path))
        self.process.start('chrt --verbose -i 0 vagrant {}'.format(option))
        if not self.process.waitForStarted():
            self.output.append(self.formatErrorMsg('ERROR: FAIL: Vagrant Fail'))
            self.runbtn.setEnabled(True)
            return
        self.runbtn.setEnabled(True)
        self.output.append(self.formatInfoMsg('INFO:{}'.format(datetime.now())))
        chdir(path.expanduser("~"))

    def finish(self):
        ' clear when finish '
        self.process.kill()
Ejemplo n.º 32
0
    def prepareConfigDialog(self):
        """Prepare the Configuration Dialog."""
        self.bcolor, self.dialog = QColor(), KDialog()
        self.dialog.setWindowTitle(__package__ + "Settings")
        self.layBox = QGridLayout(self.dialog.mainWidget())
        self.title = KTitleWidget(self.dialog)
        self.title.setText(__doc__ + " !")
        self.title.setAutoHideTimeout(3000)
        self.FontButton = KFontRequester(self.dialog)
        self.tfont = QFont(QVariant(self.configurations.readEntry("TextFont",
                           QVariant(QFont()))))
        self.FontButton.setFont(self.tfont)
        self.ColorButton = KColorButton(self.dialog)
        self.tcolor = QColor(self.configurations.readEntry("TextColor",
                             QColor("#000").name()))
        self.ColorButton.setColor(self.tcolor)
        self.BColorButton = KColorButton(self.dialog)
        # button to update the DB via sudo updatedb

        self.UpdateDB = KPushButton("Update Database", self.dialog,
                                    clicked=lambda: self.update_db())
        self.UpdateDB.setToolTip("Database is Updated every Reboot and Daily!")
        self.Histor = KPushButton("Delete my History", self.dialog,
                                  clicked=delete_my_history)
        self.Histor.setToolTip("History is Deleted every Reboot !")
        # list of banned words separated by spaces
        self.banned = KTextEdit(self.dialog)
        self.banned.setPlainText(self.configurations.readEntry(
            "Banned", "sex p**n drugs suicide decapitate religion").toString())
        # set the colors
        cg = KConfig("kdeglobals")
        color = cg.group("Colors:View").readEntry(
            "BackgroundAlternate").split(",")
        self.bcolor = QColor(int(color[0]), int(color[1]), int(color[2]))
        self.BColorButton.setColor(self.bcolor)
        self.history_file_path_field = KLineEdit(HISTORY_FILE_PATH)
        self.history_file_path_field.setDisabled(True)
        self.python_file_path_field = KLineEdit(__file__)
        self.python_file_path_field.setDisabled(True)
        self.kill_baloo = QCheckBox("Disable Baloo")
        self.kill_baloo.setToolTip("Enable/Disable Desktop Search Indexing")
        self.kill_baloo.stateChanged.connect(lambda: call(
            DISABLE_BALOO_CMD.format(str(
                not self.kill_baloo.isChecked()).lower()), shell=True))
        self.kill_baloo.stateChanged.connect(lambda: QMessageBox.information(
            self.dialog, __doc__, """
            <b>Indexing Disabled, Baloo is Dead !
            """ if self.kill_baloo.isChecked() else """
            <b>Indexing Enabled, Baloo is Running !"""))
        self.updatez = KPushButton("Check for Updates", self.dialog,
                                   clicked=lambda: self.check_for_updates())
        self.updatez.setToolTip("Check for Pylou updates from the internet")
        self.home_sweet_home = QCheckBox("Only Search Home")
        self.home_sweet_home.setToolTip("Only Search on my Home folders")
        self.home_sweet_home.setChecked(
            bool(self.configurations.readEntry("Home", True)))
        # pack all widgets
        self.layBox.addWidget(self.title, 0, 1)
        self.layBox.addWidget(QLabel("Font"), 1, 0)
        self.layBox.addWidget(self.FontButton, 1, 1)
        self.layBox.addWidget(QLabel("Text Color"), 2, 0)
        self.layBox.addWidget(self.ColorButton, 2, 1)
        self.layBox.addWidget(QLabel("Alternate Color"), 3, 0)
        self.layBox.addWidget(self.BColorButton, 3, 1)
        self.layBox.addWidget(QLabel(), 4, 0)
        self.layBox.addWidget(QLabel("Mainteniance"), 5, 0)
        self.layBox.addWidget(self.UpdateDB, 5, 1)
        self.layBox.addWidget(QLabel("Privacy"), 6, 0)
        self.layBox.addWidget(self.Histor, 6, 1)
        self.layBox.addWidget(QLabel("History file"), 7, 0)
        self.layBox.addWidget(self.history_file_path_field, 7, 1)
        self.layBox.addWidget(QLabel(__package__ + "file"), 8, 0)
        self.layBox.addWidget(self.python_file_path_field, 8, 1)
        self.layBox.addWidget(QLabel("Banned Words"), 9, 0)
        self.layBox.addWidget(self.banned, 9, 1)
        self.layBox.addWidget(QLabel("SelfUpdating"), 10, 0)
        self.layBox.addWidget(self.updatez, 10, 1)
        self.layBox.addWidget(QLabel("<b>Disable Indexing"), 12, 0)
        self.layBox.addWidget(self.kill_baloo, 12, 1)
        self.layBox.addWidget(QLabel("Search Paths"), 13, 0)
        self.layBox.addWidget(self.home_sweet_home, 13, 1)
        # button box on the bottom
        self.dialog.setButtons(KDialog.ButtonCodes(
            KDialog.ButtonCode(KDialog.Ok | KDialog.Cancel | KDialog.Apply)))
        # connect
        self.dialog.applyClicked.connect(self.configAccepted)
        self.dialog.okClicked.connect(self.configAccepted)
Ejemplo n.º 33
0
class Main(plugin.Plugin):
    " Main Class "
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)

        # directory auto completer
        self.completer = QCompleter(self)
        self.dirs = QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)

        # tab widget
        self.mainwidget = QTabWidget()
        self.mainwidget.setToolTip(__doc__)
        self.mainwidget.setTabShape(QTabWidget.Triangular)
        self.mainwidget.setMovable(True)
        self.mainwidget.setTabsClosable(True)
        self.mainwidget.tabCloseRequested.connect(lambda:
            self.mainwidget.setTabPosition(1)
            if self.mainwidget.tabPosition() == 0
            else self.mainwidget.setTabPosition(0))
        self.dock1 = QDockWidget()
        self.dock2 = QDockWidget()
        for indx, a in enumerate((self.dock1, self.dock2)):
            a.setWindowModality(Qt.NonModal)
            a.setWindowOpacity(0.9)
            a.setWindowTitle('Semantic Files' if indx == 0 else 'Simple Query')
            a.setStyleSheet('QDockWidget::title{text-align:center;}')
            self.mainwidget.addTab(a, QIcon.fromTheme("nepomuk"),
                             'Semantic Files' if indx == 0 else 'Simple Query')

        QPushButton(QIcon.fromTheme("help-about"), 'Help About', self.dock1
          ).clicked.connect(lambda:
          QMessageBox.information(self.dock1, __doc__, HELPMSG))

        # Group of widgets for each tab
        self.group1 = QGroupBox()
        self.filename = QLineEdit()
        self.filename.setPlaceholderText('/full/path/to/one_file.py')
        self.filename.setCompleter(self.completer)
        self.filebttn = QPushButton(QIcon.fromTheme("folder-open"), 'Open File')
        self.filebttn.clicked.connect(lambda: self.filename.setText(str(
            QFileDialog.getOpenFileName(self.mainwidget,
            " Please, open a .py file to add Semantics ", path.expanduser("~"),
            ';;'.join(['(*.{}) {}'.format(e, e.upper()) for e in ['*', 'py']])))
        ))

        self.group1a = QGroupBox()
        self.filetag = QLineEdit()
        self.filetag.setPlaceholderText('Type a short Tag for the choosen File')
        self.filelbl = QLineEdit()
        self.filelbl.setPlaceholderText('Type a descriptive Label for the Tag')
        self.filedsc = QLineEdit()
        self.filedsc.setPlaceholderText('Type a large and detailed Description')
        self.filerat = KRatingWidget()
        self.filerat.setToolTip('Set a File Rating')
        vboxg1a = QHBoxLayout(self.group1a)
        for each_widget in (QLabel('<b>File Tag'), self.filetag,
            QLabel('<b>Tag Label'), self.filelbl,
            QLabel('<b>Description'), self.filedsc,
            QLabel('<b>File Rating'), self.filerat):
            vboxg1a.addWidget(each_widget)

        self.nepobtn = QPushButton(QIcon.fromTheme("nepomuk"), 'Add Semantics')
        self.nepobtn.setMinimumSize(self.nepobtn.size().width(), 50)
        self.nepobtn.clicked.connect(lambda: self.nepomuk_set(
            str(self.filename.text()).strip(), str(self.filetag.text()).strip(),
            str(self.filelbl.text()).strip(), str(self.filedsc.text()).strip()))
        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (
            QLabel('<b>Choose a File'), self.filename, self.filebttn,
            self.group1a, self.nepobtn):
            vboxg1.addWidget(each_widget)

        self.group2 = QGroupBox()
        self.group2.setTitle('Sorry!, this Tab is not Ready yet...')
        QLabel('<b style="color:red;"><i>Not Ready Yet!', self.dock2)
        self.search = QLineEdit()
        self.search.setPlaceholderText('Type to Query...')
        self.srcbtn = QPushButton(QIcon.fromTheme("folder-open"), 'Query')
        self.result = QTextEdit()
        self.srcbtn.clicked.connect(lambda:
            self.nepomuk_get(str(self.search.text()).strip().lower()))
        vboxg2 = QVBoxLayout(self.group2)
        for each_widget in (
            QLabel('<b>Type for a Semantic Query'), self.search, self.srcbtn,
            QLabel('<b>Semantic Query Results'), self.result):
            vboxg2.addWidget(each_widget)

        # pack the group of widgets on the gui
        self.dock1.setWidget(self.group1)
        self.dock2.setWidget(self.group2)

        # pack the plugin on ninja-ide gui
        self.locator.get_service('misc').add_widget(
                        self.mainwidget, QIcon.fromTheme("nepomuk"), __doc__)

        def must_have_tooltip(widget_list):
            ' widget tuple passed as argument should have tooltips '
            for each_widget in widget_list:
                try:
                    each_widget.setToolTip(each_widget.text())
                except:
                    each_widget.setToolTip(each_widget.currentText())
                finally:
                    each_widget.setCursor(QCursor(Qt.PointingHandCursor))

        def must_glow(widget_list):
            ' apply an glow effect to the widget '
            for glow, each_widget in enumerate(widget_list):
                try:
                    if each_widget.graphicsEffect() is None:
                        glow = QGraphicsDropShadowEffect(self)
                        glow.setOffset(0)
                        glow.setBlurRadius(99)
                        glow.setColor(QColor(99, 255, 255))
                        each_widget.setGraphicsEffect(glow)
                        # glow.setEnabled(False)
                        try:
                            each_widget.clicked.connect(lambda:
                            each_widget.graphicsEffect().setEnabled(True)
                            if each_widget.graphicsEffect().isEnabled() is False
                            else each_widget.graphicsEffect().setEnabled(False))
                        except:
                            each_widget.sliderPressed.connect(lambda:
                            each_widget.graphicsEffect().setEnabled(True)
                            if each_widget.graphicsEffect().isEnabled() is False
                            else each_widget.graphicsEffect().setEnabled(False))
                except:
                    pass

        must_have_tooltip((self.filebttn, self.nepobtn, self.srcbtn, ))
        must_glow((self.nepobtn, self.srcbtn, ))

    def nepomuk_set(self, file_tag=None, __tag='', _label='', _description=''):
        ' Quick and Easy Nepomuk Taggify for Files '
        print((''' INFO: Semantic Desktop Experience is Tagging Files :
              {}, {}, {}, {})'''.format(file_tag, __tag, _label, _description)))
        if Nepomuk.ResourceManager.instance().init() is 0:
            fle = Nepomuk.Resource(KUrl(QFileInfo(file_tag).absoluteFilePath()))
            _tag = Nepomuk.Tag(__tag)
            _tag.setLabel(_label)
            fle.addTag(_tag)
            fle.setRating(int(self.filerat.rating()))
            fle.setDescription(_description)
            print(([str(a.label()) for a in fle.tags()], fle.description()))
            return ([str(a.label()) for a in fle.tags()], fle.description())
        else:
            print(" ERROR: FAIL: Nepomuk is not running ! ")

    def nepomuk_get(self, query_to_search):
        ' Quick and Easy Nepomuk Query for Files '
        print((''' INFO: Semantic Desktop Experience is Quering Files :
              {} '''.format(query_to_search)))
        results = []
        nepo = Nepomuk.Query.QueryServiceClient()
        nepo.desktopQuery("hasTag:{}".format(query_to_search))

        def _query(data):
            ''' ('filename.ext', 'file description', ['list', 'of', 'tags']) '''
            print(([str(a.resource().genericLabel()) for a in data][0],
                   [str(a.resource().description()) for a in data][0],
            [str(a.label()) for a in iter([a.resource().tags() for a in data][0]
            )]))
            self.result.append(str(
                ([str(a.resource().genericLabel()) for a in data][0],
                 [str(a.resource().description()) for a in data][0],
            [str(a.label()) for a in iter([a.resource().tags() for a in data][0]
            )],
            )))
        nepo.newEntries.connect(_query)
        nepo.finishedListing.connect(lambda: nepo.newEntries.disconnect)
        return results