Example #1
0
class Main(plugin.Plugin):
    " dock Class "
    def initialize(self):
        " Init Class dock "
        self.dock = QDockWidget()
        self.dock.setFeatures(QDockWidget.DockWidgetFloatable |
                              QDockWidget.DockWidgetMovable)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.boton = QPushButton(QIcon.fromTheme("document-open-recent"),
                                 'Edit Track', self.dock)
        self.boton.setToolTip('Edit iCal: {}'.format(TRACK_FILE))
        try:
            self.factory = KPluginLoader("ktimetrackerpart").factory()
            self.part = self.factory.create(self)
            self.part.setReadWrite(True)
            self.part.closeUrl()
            self.part.openUrl(KUrl(str(TRACK_FILE)))
            self.boton.clicked.connect(lambda:
                            call('xdg-open {}'.format(TRACK_FILE), shell=True))
            self.dock.setWidget(self.part.widget())
        except:
            self.dock.setWidget(QLabel(""" <center> <h3>ಠ_ಠ<br>
            ERROR: Please, install kTimeTracker and PyKDE ! </h3><br>
            <br><i> (Sorry, cant embed non-Qt Apps). </i><center>"""))
        self.misc = self.locator.get_service('misc')
        self.misc.add_widget(self.dock, QIcon.fromTheme("user-away"), __doc__)
Example #2
0
class Main(plugin.Plugin):
    " dock Class "
    def initialize(self):
        " Init Class dock "
        self.dock = QDockWidget()
        self.dock.setFeatures(QDockWidget.DockWidgetFloatable |
                              QDockWidget.DockWidgetMovable)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.boton = QPushButton(QIcon.fromTheme("media-eject"),
                                 ' Open Media ', self.dock)
        try:
            self.factory = KPluginLoader("dragonpart").factory()
            self.part = self.factory.create(self)
            self.boton.clicked.connect(lambda: self.part.openUrl(KUrl(str(
                QFileDialog.getOpenFileName(self.dock, ' Open Media File ',
                path.expanduser("~"), ';;'.join(['(*.{})'.format(e) for e in
                ['ogv', 'webm', 'avi', 'mpg', 'mpeg', '3gp', 'wmv', 'mp3',
                'asf', 'dat', 'flv', 'flac', 'ogg', 'mkv', 'mov', 'swf', 'wav',
                'rm', 'm4v', 'aaf', 'mp4', 'raw', '*']]))))))
            self.dock.setWidget(self.part.widget())
        except:
            self.dock.setWidget(QLabel(""" <center> <h3>ಠ_ಠ<br>
            ERROR: Please, install Dragon Player and PyKDE ! </h3><br>
            <br><i> (Sorry, cant embed non-Qt Apps). </i>><center>"""))
        self.misc = self.locator.get_service('misc')
        self.misc.add_widget(self.dock,
                            QIcon.fromTheme("applications-multimedia"), __doc__)
Example #3
0
class Main(plugin.Plugin):
    " dock Class "
    def initialize(self):
        " Init Class dock "
        self.dock = QDockWidget()
        self.dock.setFeatures(QDockWidget.DockWidgetFloatable |
                              QDockWidget.DockWidgetMovable)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.open = QAction(QIcon.fromTheme("document-open"), 'Open DIFF', self)
        self.diff = QAction(QIcon.fromTheme("document-new"), 'Make DIFF', self)
        self.diff.triggered.connect(self.run_gui_and_get_results)
        self.save = QAction(QIcon.fromTheme("document-save"), 'Save DIFF', self)
        self.save.triggered.connect(self.save_a_diff)
        self.patc = QAction(QIcon.fromTheme("document-edit"), 'PATCH it!', self)
        self.patc.triggered.connect(lambda: QMessageBox.information(self.dock,
            __doc__, ' Sorry. This Feature is not ready yet !, thank you... '))
        QToolBar(self.dock).addActions((self.open, self.diff,
                                        self.save, self.patc))
        try:
            self.factory = KPluginLoader("komparepart").factory()
            self.part = self.factory.create(self)
            self.dock.setWidget(self.part.widget())
            self.open.triggered.connect(lambda: self.part.openUrl(KUrl(str(
                QFileDialog.getOpenFileName(self.dock, ' Open a DIFF file ',
                                        path.expanduser("~"), ';;(*.diff)')))))
        except:
            self.dock.setWidget(QLabel(""" <center> <h3>ಠ_ಠ<br>
            ERROR: Please, install Kompare and PyKDE ! </h3><br>
            <br><i> (Sorry, cant embed non-Qt Apps). </i><center>"""))

        self.misc = self.locator.get_service('misc')
        self.misc.add_widget(self.dock,
                                QIcon.fromTheme("edit-select-all"), __doc__)

    def run_gui_and_get_results(self):
        ' run_gui_and_get_results '
        gui = Diff_GUI()
        if gui.diff_path is not None and path.isfile(gui.diff_path) is True:
            self.part.openUrl(KUrl(str(gui.diff_path)))
        return gui.diff_path

    def save_a_diff(self):
        ' save a diff '
        out_file = path.abspath(str(QFileDialog.getSaveFileName(self.dock,
                   'Save a Diff file', path.expanduser("~"), ';;(*.diff)')))
        inp_file = file(str(QUrl(
               self.part.url()).toString()).replace('file://', ''), 'r').read()
        end_file = file(out_file, 'w')
        end_file.write(inp_file)
        end_file.close()
Example #4
0
class Main(plugin.Plugin):
    " dock Class "

    def initialize(self):
        " Init Class dock "
        self.dock = QDockWidget()
        self.dock.setFeatures(QDockWidget.DockWidgetFloatable
                              | QDockWidget.DockWidgetMovable)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.boton = QAction(QIcon.fromTheme("list-add"), 'Open', self)
        self.saver = QAction(QIcon.fromTheme("document-save"), 'Save', self)
        self.apiss = QAction(QIcon.fromTheme("help"), 'Python API Help', self)
        QToolBar(self.dock).addActions((self.boton, self.saver, self.apiss))
        try:
            self.factory = KPluginLoader("kigpart").factory()
            self.part = self.factory.create(self)
            self.part.setReadWrite(True)
            self.boton.triggered.connect(lambda: self.part.openUrl(
                KUrl(
                    str(
                        QFileDialog.getOpenFileName(
                            self.dock, ' Open Geometry Plot ',
                            path.expanduser("~"), ';;'.join([
                                '(*.{})'.format(e)
                                for e in ['fig', 'kig', 'kigz', 'seg', 'fgeo']
                            ]))))))
            self.saver.triggered.connect(lambda: self.part.saveAs(
                KUrl(
                    str(
                        QFileDialog.getSaveFileName(
                            self.dock, ' Save Geometry Plot ',
                            path.expanduser("~"), ';;'.join([
                                '(*.{})'.format(e)
                                for e in ['kig', 'kigz', 'fig']
                            ]))))))
            self.apiss.triggered.connect(lambda: open_new_tab(
                'http://edu.kde.org/kig/manual/scripting-api/classObject.html')
                                         )
            self.dock.setWidget(self.part.widget())
        except:
            self.dock.setWidget(
                QLabel(""" <center> <h3>ಠ_ಠ<br>
            ERROR: Please, install KIG and PyKDE ! </h3><br>
            <br><i> (Sorry, cant embed non-Qt Apps). </i><center>"""))
        self.misc = self.locator.get_service('misc')
        self.misc.add_widget(self.dock,
                             QIcon.fromTheme("accessories-calculator"),
                             __doc__)
Example #5
0
class Terminal(plugin.Plugin):
    " Terminal Class "
    def initialize(self):
        " Init Class Terminal "
        self.terminal = QDockWidget()
        self.terminal.setFeatures(QDockWidget.DockWidgetFloatable |
                                  QDockWidget.DockWidgetMovable)
        self.terminal.setWindowTitle(__doc__)
        self.terminal.setStyleSheet('QDockWidget::title{text-align: center;}')
        try:
            self.factory = KPluginLoader("libkonsolepart").factory()
            self.terminal.setWidget(self.factory.create(self).widget())
        except:
            self.terminal.setWidget(QLabel(""" <center> <h3>ಠ_ಠ<br>
            ERROR: Please, install Konsole Terminal and PyKDE ! </h3><br>
            <br><i> (Sorry, cant embed non-Qt Terminal Apps). </i><center>"""))
        self.misc = self.locator.get_service('misc')
        self.misc.add_widget(self.terminal,
                               QIcon.fromTheme("utilities-terminal"), __doc__)
Example #6
0
class Main(plugin.Plugin):
    " dock Class "
    def initialize(self):
        " Init Class dock "
        self.dock = QDockWidget()
        self.dock.setFeatures(QDockWidget.DockWidgetFloatable |
                              QDockWidget.DockWidgetMovable)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.boton = QAction(QIcon.fromTheme("list-add"), 'Open', self)
        self.saver = QAction(QIcon.fromTheme("document-save"), 'Save', self)
        self.apiss = QAction(QIcon.fromTheme("help"), 'Python API Help', self)
        QToolBar(self.dock).addActions((self.boton, self.saver, self.apiss))
        try:
            self.factory = KPluginLoader("kigpart").factory()
            self.part = self.factory.create(self)
            self.part.setReadWrite(True)
            self.boton.triggered.connect(lambda: self.part.openUrl(KUrl(str(
                QFileDialog.getOpenFileName(self.dock, ' Open Geometry Plot ',
                path.expanduser("~"),
                ';;'.join(['(*.{})'.format(e) for e in ['fig', 'kig', 'kigz',
                                                        'seg', 'fgeo']]))))))
            self.saver.triggered.connect(lambda: self.part.saveAs(KUrl(str(
                QFileDialog.getSaveFileName(self.dock, ' Save Geometry Plot ',
                path.expanduser("~"),
                ';;'.join(['(*.{})'.format(e) for e in ['kig', 'kigz', 'fig']])
            )))))
            self.apiss.triggered.connect(lambda: open_new_tab(
                'http://edu.kde.org/kig/manual/scripting-api/classObject.html'))
            self.dock.setWidget(self.part.widget())
        except:
            self.dock.setWidget(QLabel(""" <center> <h3>ಠ_ಠ<br>
            ERROR: Please, install KIG and PyKDE ! </h3><br>
            <br><i> (Sorry, cant embed non-Qt Apps). </i><center>"""))
        self.misc = self.locator.get_service('misc')
        self.misc.add_widget(self.dock,
                            QIcon.fromTheme("accessories-calculator"), __doc__)
Example #7
0
class Main(plugin.Plugin):
    " dock Class "

    def initialize(self):
        " Init Class dock "
        self.dock = QDockWidget()
        self.dock.setFeatures(QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet("QDockWidget::title{text-align: center;}")
        self.scrollable = QScrollArea()
        self.dock.setWidget(self.scrollable)
        try:
            self.factory = KPluginLoader("klinkstatuspart").factory()
            self.scrollable.setWidget(self.factory.create(self).widget())
        except:
            self.scrollable.setWidget(
                QLabel(
                    """ <center> <h3>ಠ_ಠ<br>
            ERROR: Please, install KLinkCheck and PyKDE ! </h3><br>
            <br><i> (Sorry, cant embed non-Qt Apps). </i><center>"""
                )
            )
        self.misc = self.locator.get_service("misc")
        self.misc.add_widget(self.dock, QIcon.fromTheme("insert-link"), __doc__)
Example #8
0
class Main(plugin.Plugin):
    " Main Class "
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        self.chooser, self.process = QComboBox(), QProcess()
        self.chooser.addItems([' Ubuntu Unity QuickList .desktop ',
                               ' KDE Plasma MetaData .desktop ',
                               ' FreeDesktop Standard .desktop '])
        self.chooser.currentIndexChanged.connect(self.on_index_changed)
        self.chooser.setToolTip('Select a target .desktop file format')

        # Standard FreeDesktop
        self.group1 = QGroupBox()
        self.group1.setTitle(' Standard ')
        self.ledVersion, self.ledCategories = QDoubleSpinBox(), QComboBox()
        self.ledVersion.setMinimum(0.1)
        self.ledVersion.setMaximum(999.9)
        self.ledVersion.setValue(1.0)
        self.ledVersion.setDecimals(1)
        self.ledType, self.ledName = QLineEdit('Application'), QLineEdit('App')
        self.ledGenericName = QLineEdit('Generic App')
        self.ledComment, self.ledIcon = QLineEdit('App'), QLineEdit('icon.svg')
        self.ledCategories.addItems(['Python Programming Language',
            'Development', 'Ruby', 'C++', 'Amateur Radio', 'Communication',
            'Cross Platform', 'Databases', 'Debug', 'Documentation', 'Editors',
            'Education', 'Electronics', 'Email', 'Embebed Devices', 'Fonts',
            'GNOME Desktop Environment', 'GNU R Statistical System',
            'GObject Introspection Data', 'Games and Amusement',
            'Gnustep Desktop Environtment', 'Graphics',
            'Haskell Programming Language',
            'Internationalization and Localization', 'Internet',
            'Interpreted Computer Languages', 'KDE Software Compilation',
            'Kernel and Modules', 'Libraries', 'Libraries - Development',
            'Libraries - Old', 'Lisp Programming Language', 'Localization',
            'Mathematics', 'Meta Packages', 'Miscelaneous - Graphical',
            'Miscelaneous - Text Based', 'Mono/CLI Infraestructure',
            'Multimedia', 'Networking', 'Newsgroups',
            'OCaml Programming Language', 'PHP Programming Language',
            'Perl Programming Language', 'Ruby Programming Language',
            'Science', 'Shells', 'System Administration', 'TeX Authoring',
            'Utilities', 'Version Control Systems', 'Video Software',
            'Web Servers', 'Word Processing', 'Xfce Desktop Environment',
            'Zope/Plone Environment'])

        self.ledExec, self.ledTryExec = QLineEdit('myapp'), QLineEdit('myapp')
        self.ledMymeType = QLineEdit('application/x-desktop')
        self.ledTerminal = QComboBox()
        self.ledTerminal.addItems(['False', 'True'])
        self.ledActions = QLineEdit('Next;Previous')
        self.ledOnlyShowIn = QLineEdit('Unity;KDE')
        self.ledNotShowIn = QLineEdit('Gnome2')
        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (QLabel('Version'), self.ledVersion, QLabel('Type'),
            self.ledType, QLabel('Name'), self.ledName, QLabel('GenericName'),
            self.ledGenericName, QLabel('Comment'), self.ledComment,
            QLabel('Icon'), self.ledIcon, QLabel('Categories'),
            self.ledCategories, QLabel('Exec'), self.ledExec, QLabel('TryExec'),
            self.ledTryExec, QLabel('MymeType'), self.ledMymeType,
            QLabel('Terminal'), self.ledTerminal, QLabel('Actions'),
            self.ledActions, QLabel('OnlyShowIn'), self.ledOnlyShowIn,
            QLabel('NotShowIn'), self.ledNotShowIn):
            vboxg1.addWidget(each_widget)

        # KDE Plasma
        self.group2 = QGroupBox()
        self.group2.setTitle(' KDE Plasma ')
        self.group2.setGraphicsEffect(QGraphicsBlurEffect(self))
        self.ledEncoding, self.ledXPlasmaAPI = QComboBox(), QComboBox()
        self.ledEncoding.addItems(['UTF-8', 'ISO-8859-1'])
        self.ledServiceType = QLineEdit('Plasma/Applet')
        self.ledXPlasmaAPI.addItems([
                        'Python', 'Javascript', 'Ruby', 'C++', 'HTML5', 'QML'])
        self.ledXPlasmaMainScript = QLineEdit('path/to/your/code.py')
        self.ledXKDEPluginInfoAuthor = QLineEdit(getuser())
        self.ledXKDEPluginInfoEmail = QLineEdit(getuser() + '@gmail.com')
        self.ledXKDEPluginInfoName = QLineEdit('Hello-World')
        self.ledXKDEPluginInfoVersion = QLineEdit('1.0')
        self.ledXKDEPluginInfoWebsite = QLineEdit('http:plasma.kde.org')
        self.ledXKDEPluginInfoCategory = QComboBox()
        self.ledXKDEPluginInfoCategory.addItems(['Application Launchers',
            'Accessibility', 'Astronomy', 'Date and Time',
            'Development Tools', 'Education', 'Environment', 'Examples',
            'File System', 'Fun and Games', 'Graphics', 'Language', 'Mapping',
            'Multimedia', 'Online Services', 'System Information', 'Utilities',
            'Windows and Tasks', 'Miscelaneous'])
        self.ledXKDEPluginInfoDepends = QLineEdit()
        self.ledXKDEPluginInfoLicense = QLineEdit('GPL')
        self.ledXKDEPluginInfoEnabledByDefault = QComboBox()
        self.ledXKDEPluginInfoEnabledByDefault.addItems(['True', 'False'])
        vboxg2 = QVBoxLayout(self.group2)
        for each_widget in (
            QLabel('Encoding'), self.ledEncoding,
            QLabel('ServiceType'), self.ledServiceType,
            QLabel('X-Plasma-API'), self.ledXPlasmaAPI,
            QLabel('X-Plasma-MainScript'), self.ledXPlasmaMainScript,
            QLabel('X-KDE-PluginInfo-Author'), self.ledXKDEPluginInfoAuthor,
            QLabel('X-KDE-PluginInfo-Email'), self.ledXKDEPluginInfoEmail,
            QLabel('X-KDE-PluginInfo-Name'), self.ledXKDEPluginInfoName,
            QLabel('X-KDE-PluginInfo-Version'), self.ledXKDEPluginInfoVersion,
            QLabel('X-KDE-PluginInfo-Website'), self.ledXKDEPluginInfoWebsite,
            QLabel('X-KDE-PluginInfo-Category'), self.ledXKDEPluginInfoCategory,
            QLabel('X-KDE-PluginInfo-Depends'), self.ledXKDEPluginInfoDepends,
            QLabel('X-KDE-PluginInfo-License'), self.ledXKDEPluginInfoLicense,
            QLabel('X-KDE-PluginInfo-EnabledByDefault'),
            self.ledXKDEPluginInfoEnabledByDefault):
            vboxg2.addWidget(each_widget)

        # Ubuntu Unity
        self.ledXAyatanaDesktopShortcuts = QLineEdit('Next;Previous')

        self.checkbox1 = QCheckBox('Open .desktop file when done')
        self.checkbox2 = QCheckBox('Make .desktop file Executable')
        [a.setChecked(True) for a in (self.checkbox1, self.checkbox2)]

        self.button = QPushButton(' Make .Desktop File ! ')
        self.button.setMinimumSize(100, 50)
        self.button.clicked.connect(self.writeFile)
        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((self.chooser, self.group1, self.group2,
            QLabel('X-Ayatana-Desktop-Shortcuts'),
            self.ledXAyatanaDesktopShortcuts, QLabel(''),
            self.checkbox1, self.checkbox2, self.button))
        self.dock, self.scrollable = QDockWidget(), QScrollArea()
        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, "DotDesktop")
        QPushButton(QIcon.fromTheme("help-about"), 'About', self.dock
          ).clicked.connect(lambda: QMessageBox.information(self.dock, __doc__,
          ''.join((__doc__, __version__, __license__, 'by', __author__))))

    def writeFile(self):
        ' write the .desktop file to disk '

        UNITY = ''.join(a for a in iter((
        'OnlyShowIn=', str(self.ledOnlyShowIn.text()), linesep,
        'NotShowIn=', str(self.ledNotShowIn.text()), linesep,
        'X-Ayatana-Desktop-Shortcuts=',
        str(self.ledXAyatanaDesktopShortcuts.text()), linesep)))

        PLASMA = ''.join(a for a in iter((
        'OnlyShowIn=', str(self.ledOnlyShowIn.text()), linesep,
        'NotShowIn=', str(self.ledNotShowIn.text()), linesep,
        'Encoding=', str(self.ledEncoding.currentText()), linesep,
        'ServiceTypes=', str(self.ledServiceType.text()), linesep,
        'X-Plasma-API=', str(self.ledXPlasmaAPI.currentText()), linesep,
        'X-Plasma-MainScript=', str(self.ledXPlasmaMainScript.text()), linesep,
        'X-KDE-PluginInfo-Author=', str(self.ledXKDEPluginInfoAuthor.text()),
        linesep,
        'X-KDE-PluginInfo-Email=', str(self.ledXKDEPluginInfoEmail.text()),
        linesep,
        'X-KDE-PluginInfo-Name=', str(self.ledXKDEPluginInfoName.text()),
        linesep,
        'X-KDE-PluginInfo-Version=', str(self.ledXKDEPluginInfoVersion.text()),
        linesep,
        'X-KDE-PluginInfo-Website=', str(self.ledXKDEPluginInfoWebsite.text()),
        linesep,
        'X-KDE-PluginInfo-Category=',
        str(self.ledXKDEPluginInfoCategory.currentText()), linesep,
        'X-KDE-PluginInfo-Depends=', str(self.ledXKDEPluginInfoDepends.text()),
        linesep,
        'X-KDE-PluginInfo-License=', str(self.ledXKDEPluginInfoLicense.text()),
        linesep,
        'X-KDE-PluginInfo-EnabledByDefault=',
        str(self.ledXKDEPluginInfoEnabledByDefault.currentText()), linesep)))

        BASE = ''.join(a for a in iter((
        '[Desktop Entry]', linesep,
        'Version=', str(self.ledVersion.value()), linesep,
        'Type=', str(self.ledType.text()), linesep,
        'Name=', str(self.ledName.text()), linesep,
        'Comment=', str(self.ledComment.text()), linesep,
        'TryExec=', str(self.ledTryExec.text()), linesep,
        'Exec=', str(self.ledExec.text()), linesep,
        'Icon=', str(self.ledIcon.text()), linesep,
        'MimeType=', str(self.ledMymeType.text()), linesep,
        'Actions=', str(self.ledActions.text()), linesep,
        'Terminal=', str(self.ledTerminal.currentText()), linesep)))

        ACTIONS * len(str(self.ledActions.text()).lower().strip().split(';'))

        fnm = str(QFileDialog.getSaveFileName(self.dock, '', '', "(*.desktop)"))
        with open(fnm, 'w') as f:
            if self.chooser.currentIndex() is 0 and fnm is not '':
                f.write(''.join(a for a in iter((BASE, UNITY, ACTIONS))))
            elif self.chooser.currentIndex() is 1 and fnm is not '':
                f.write(''.join(a for a in iter((BASE, PLASMA))))
            elif fnm is not '':
                f.write(BASE)

        if self.checkbox2.isChecked() and fnm is not '':
            try:
                chmod(fnm, 0775)  # Py2
            except:
                chmod(fnm, 0o775)  # Py3

        if self.checkbox1.isChecked() and fnm is not '':
            self.process.start('ninja-ide ' + fnm)
            if not self.process.waitForStarted():
                print((" ERROR: FAIL: {} failed!".format(fnm)))
                return

    def on_index_changed(self):
        ' enable disable the qgroupbox if needed '
        if self.chooser.currentIndex() is 1:
            self.group2.graphicsEffect().setEnabled(False)
            self.group2.setEnabled(True)
        else:
            self.group2.graphicsEffect().setEnabled(True)
            self.group2.setEnabled(False)
        if self.chooser.currentIndex() is 0:
            self.ledXAyatanaDesktopShortcuts.setEnabled(True)
        else:
            self.ledXAyatanaDesktopShortcuts.setEnabled(False)
Example #9
0
class Main(plugin.Plugin):
    " dock Class "

    def initialize(self):
        " Init Class dock "
        self.dock = QDockWidget()
        self.dock.setFeatures(QDockWidget.DockWidgetFloatable
                              | QDockWidget.DockWidgetMovable)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.open = QAction(QIcon.fromTheme("document-open"), 'Open DIFF',
                            self)
        self.diff = QAction(QIcon.fromTheme("document-new"), 'Make DIFF', self)
        self.diff.triggered.connect(self.run_gui_and_get_results)
        self.save = QAction(QIcon.fromTheme("document-save"), 'Save DIFF',
                            self)
        self.save.triggered.connect(self.save_a_diff)
        self.patc = QAction(QIcon.fromTheme("document-edit"), 'PATCH it!',
                            self)
        self.patc.triggered.connect(lambda: QMessageBox.information(
            self.dock, __doc__,
            ' Sorry. This Feature is not ready yet !, thank you... '))
        QToolBar(self.dock).addActions(
            (self.open, self.diff, self.save, self.patc))
        try:
            self.factory = KPluginLoader("komparepart").factory()
            self.part = self.factory.create(self)
            self.dock.setWidget(self.part.widget())
            self.open.triggered.connect(lambda: self.part.openUrl(
                KUrl(
                    str(
                        QFileDialog.getOpenFileName(
                            self.dock, ' Open a DIFF file ',
                            path.expanduser("~"), ';;(*.diff)')))))
        except:
            self.dock.setWidget(
                QLabel(""" <center>
            <h3>ಠ_ಠ<br> ERROR: Please, install Kompare App ! </h3><br>
            <br><i> (Sorry, cant embed non-Qt Apps). </i><center>"""))

        self.misc = self.locator.get_service('misc')
        self.misc.add_widget(self.dock, QIcon.fromTheme("edit-select-all"),
                             __doc__)

    def run_gui_and_get_results(self):
        ' run_gui_and_get_results '
        gui = Diff_GUI()
        if gui.diff_path is not None and path.isfile(gui.diff_path) is True:
            self.part.openUrl(KUrl(str(gui.diff_path)))
        return run_gui.diff_path

    def save_a_diff(self):
        ' save a diff '
        out_file = path.abspath(
            str(
                QFileDialog.getSaveFileName(self.dock, 'Save a Diff file',
                                            path.expanduser("~"),
                                            ';;(*.diff)')))
        inp_file = file(
            str(QUrl(self.part.url()).toString()).replace('file://', ''),
            'r').read()
        end_file = file(out_file, 'w')
        end_file.write(inp_file)
        end_file.close()
Example #10
0
class Main(plugin.Plugin):
    " Main Class "
    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))

    def run(self):
        ' run the string replacing '
        if self.source.currentText() == 'Local File':
            with open(path.abspath(str(self.infile.text()).strip()), 'r') as f:
                txt = f.read()
        elif self.source.currentText() == 'Remote URL':
            txt = urlopen(str(self.inurl.text()).strip()).read()
        elif  self.source.currentText() == 'Clipboard':
            txt = str(self.output.toPlainText()) if str(self.output.toPlainText()) is not '' else str(QApplication.clipboard().text())
        else:
            txt = self.editor_s.get_text()
        self.output.clear()
        self.befor.setMaximum(len(txt) + 10)
        self.after.setMaximum(len(txt) + 10)
        self.befor.setValue(len(txt))
        txt = txt.lower() if self.chckbx1.isChecked() is True else txt
        txt = condense_style(txt) if self.ckhtml0.isChecked() is True else txt
        txt = condense_script(txt) if self.ckhtml0.isChecked() is True else txt
        txt = condense_doctype(txt) if self.ckhtml1.isChecked() is True else txt
        txt = condense_href_src(txt) if self.ckhtml2 is True else txt
        txt = clean_unneeded_tags(txt) if self.ckhtml4.isChecked() is True else txt
        txt = condense_doc_ready(txt) if self.ckjs1.isChecked() is True else txt
        txt = jsmin(txt) if self.ckjs0.isChecked() is True else txt
        txt = remove_comments(txt) if self.ckcss1.isChecked() is True else txt
        txt = condense_whitespace(txt) if self.ckcss10.isChecked() is True else txt
        txt = remove_empty_rules(txt) if self.ckcss4.isChecked() is True else txt
        txt = remove_unnecessary_whitespace(txt) if self.ckcss2.isChecked() is True else txt
        txt = remove_unnecessary_semicolons(txt) if self.ckcss3.isChecked() is True else txt
        txt = condense_zero_units(txt) if self.ckcss6.isChecked() is True else txt
        txt = condense_multidimensional_zeros(txt) if self.ckcss7.isChecked() is True else txt
        txt = condense_floating_points(txt) if self.ckcss8.isChecked() is True else txt
        txt = normalize_rgb_colors_to_hex(txt) if self.ckcss5.isChecked() is True else txt
        txt = condense_hex_colors(txt) if self.ckcss9.isChecked() is True else txt
        txt = wrap_css_lines(txt, 80) if self.ckcss12.isChecked() is True else txt
        txt = condense_semicolons(txt) if self.ckcss11.isChecked() is True else txt
        txt = condense_font_weight(txt) if self.ckcss13.isChecked() is True else txt
        txt = condense_std_named_colors(txt) if self.ckcss14.isChecked() is True else txt
        # txt = condense_xtra_named_colors(txt) if self.ckcss14.isChecked() is True else txt  # FIXME
        txt = condense_percentage_values(txt) if self.ckcss16.isChecked() is True else txt
        txt = condense_pixel_values(txt) if self.ckcss17.isChecked() is True else txt
        txt = remove_url_quotes(txt) if self.ckcss18.isChecked() is True else txt
        txt = add_encoding(txt) if self.ckcss19.isChecked() is True else txt
        txt = " ".join(txt.strip().split()) if self.chckbx2.isChecked() is True else txt
        self.after.setValue(len(txt))
        self.output.setPlainText(txt)
        self.output.show()
        self.output.setFocus()
        self.output.selectAll()

    def on_source_changed(self):
        ' do something when the desired source has changed '
        if self.source.currentText() == 'Local File':
            self.open.show()
            self.infile.show()
            self.inurl.hide()
            self.output.hide()
        elif  self.source.currentText() == 'Remote URL':
            self.inurl.show()
            self.open.hide()
            self.infile.hide()
            self.output.hide()
        elif  self.source.currentText() == 'Clipboard':
            self.output.show()
            self.open.hide()
            self.infile.hide()
            self.inurl.hide()
            self.output.setText(QApplication.clipboard().text())
        else:
            self.output.show()
            self.open.hide()
            self.infile.hide()
            self.inurl.hide()
            self.output.setText(self.editor_s.get_text())

    def toggle_css_group(self):
        ' toggle on or off the css checkboxes '
        if self.group1.isChecked() is True:
            [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.group1.graphicsEffect().setEnabled(False)
        else:
            [a.setChecked(False) 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.group1.graphicsEffect().setEnabled(True)

    def toggle_html_group(self):
        ' toggle on or off the css checkboxes '
        if self.group2.isChecked() is True:
            [a.setChecked(True) for a in iter((self.ckhtml0, self.ckhtml1,
                                               self.ckhtml2, self.ckhtml4))]
            self.group2.graphicsEffect().setEnabled(False)
        else:
            [a.setChecked(False) for a in iter((self.ckhtml0, self.ckhtml1,
                                                self.ckhtml2, self.ckhtml4))]
            self.group2.graphicsEffect().setEnabled(True)
Example #11
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()
Example #12
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()
Example #13
0
class filexplorerPluginMain(plugin.Plugin):
    ' main class for plugin '
    def initialize(self, *args, **kwargs):
        ' class init '
        global CONFIG_DIR
        ec = ExplorerContainer()
        super(filexplorerPluginMain, self).initialize(*args, **kwargs)

        self.dock = QDockWidget()
        self.dock.setAllowedAreas(Qt.LeftDockWidgetArea |
                                  Qt.RightDockWidgetArea)
        self.dock.setFeatures(QDockWidget.DockWidgetFloatable |
                              QDockWidget.DockWidgetMovable)
        self.dock.setWindowTitle("fileXplorer")
        self.dock.setStyleSheet('QDockWidget::title { text-align: center; }')

        # search for the truth
        self.srch = QLineEdit()
        #self.srch.resize(self.srch.size().height(), self.dock.size().width())
        self.srch.setPlaceholderText(' Search for Python files Local or PyPI ')
        self.srch.returnPressed.connect(self.search)

        # Disk Usage Bar
        self.hdbar = QProgressBar()
        if sys.platform != 'win32':
            self.hdbar.setMaximum(statvfs(HOME).f_blocks *
                statvfs(HOME).f_frsize / 1024 / 1024 / 1024)
            self.hdbar.setValue(statvfs(HOME).f_bfree *
                statvfs(HOME).f_frsize / 1024 / 1024 / 1024)
        self.hdbar.setToolTip(str(self.hdbar.value()) + '% Total Disk Use ')
        #self.hdbar.setStyleSheet('''QProgressBar{background-color:
        #QLinearGradient(spread:pad,x1:0,y1:0,x2:1,y2:1,stop:0 rgba(255,0,0,99),
        #stop:1 rgba(9,255,9,200));color:#fff;border:none;border-radius:9px;}
        #QProgressBar::chunk{background-color:QLinearGradient(spread:pad,y1:0,
        #x1:0,y2:1,x2:0.27,stop:0 rgb(0,0,0),stop:1 rgb(9,99,255));padding:0;
        #border:none;border-radius:9px;height:9px;margin:1px;}''')

        self.model = QDirModel()
        self.fileView = QColumnView(self.dock)
        self.fileView.setAlternatingRowColors(True)
        # self.fileView.setFont(QFont(self.fileView.font().setBold(True)))
        self.fileView.setIconSize(QSize(32, 32))
        self.fileView.setModel(self.model)
        self.fileView.updatePreviewWidget.connect(self.runfile)

        self.sli = QSlider()
        self.sli.setRange(16, 128)
        self.sli.setValue(32)
        self.sli.setToolTip('Icon Size: 32 px. Move Slider to change.')
        self.sli.setOrientation(Qt.Horizontal)
        self.sli.valueChanged.connect(lambda: self.fileView.setIconSize(
            QSize(self.sli.value(), self.sli.value())))
        self.sli.sliderReleased.connect(lambda:
            self.sli.setToolTip('Icon Size: ' + str(self.sli.value())))

        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.srch, self.dock, self.sli, self.hdbar))
        ec.addTab(tw, "fileXplorer")

        ####

        self.process = QProcess()
        self.process.finished.connect(self.processFinished)

        self.preview = QLabel(self.fileView)
        self.preview.setTextFormat(0)
        self.preview.setStyleSheet('QLabel{font-size:9px;}')
        self.preview.setAutoFillBackground(True)
        self.fileView.setPreviewWidget(self.preview)
        self.dock.setWidget(self.fileView)

        # take a shot
        self.pic = QAction(QIcon.fromTheme("camera-photo"), 'Screenshot', self)
        self.pic.triggered.connect(lambda: QPixmap.grabWindow(
            QApplication.desktop().winId()).save(QFileDialog.getSaveFileName(
            self.dock, " Save Screenshot As ... ", HOME, ';;(*.png)')))

        # copy time
        self.tim = QAction(QIcon.fromTheme("user-away"),
                           'Date and Time to Clipboard', self)
        self.tim.triggered.connect(lambda: QApplication.clipboard().setText(
            datetime.now().strftime(" %A %B %d-%m-%Y %H:%M:%S %p ")))

        # color chooser
        self.cl = QAction(QIcon.fromTheme("applications-graphics"),
                          'Color Chooser to Clipboard', self)
        self.cl.triggered.connect(lambda: QApplication.clipboard().setText(
            '{}'.format(QColorDialog.getColor().name())))

        # icon chooser
        self.icn = QAction(QIcon.fromTheme("insert-image"),
                          'Icon Chooser to Clipboard', self)
        self.icn.triggered.connect(self.iconChooser)

        # tool bar with actions
        QToolBar(self.dock).addActions((self.cl, self.icn, self.tim, self.pic))

        self.textBrowser = QTextBrowser(self.dock)
        self.textBrowser.setAutoFillBackground(True)
        self.textBrowser.setGeometry(self.dock.geometry())
        self.textBrowser.hide()

    def processFinished(self):
        ' print info of finished processes '
        print(" INFO: OK: QProcess finished . . . ")

    def search(self):
        ' function to search python files '
        # get search results of python filenames local or remote
        pypi_url = 'http://pypi.python.org/pypi'
        # pypi query
        pypi = xmlrpclib.ServerProxy(pypi_url, transport=ProxyTransport())
        try:
            pypi_query = pypi.search({'name': str(self.srch.text()).lower()})
            pypi_fls = list(set(['pypi.python.org/pypi/' + a['name'] +
                   ' | pip install ' + a['name'] for a in pypi_query]))
        except:
            pypi_fls = '<b> ERROR: Internet not available! ಠ_ಠ </b>'
        s_out = ('<br> <br> <br> <h3> Search Local Python files: </h3> <hr> ' +
        # Jedi list comprehension for LOCAL search
        str(["{}/{}".format(root, f) for root, f in list(itertools.chain(*
            [list(itertools.product([root], files))
            for root, dirs, files in walk(str(
            QFileDialog.getExistingDirectory(self.dock,
            'Open Directory to Search', path.expanduser("~"))))]))
            if f.endswith(('.py', '.pyw', '.pth')) and not f.startswith('.')
            and str(self.srch.text()).lower().strip() in f]
        ).replace(',', '<br>') + '<hr><h3> Search PyPI Python files: </h3>' +
        # wraped pypi query REMOTE search
        str(pypi_fls).replace(',', '<br>') + '<hr>Auto-Proxy:ON,DoNotTrack:ON')
        # print(s_out)
        try:
            call('notify-send fileXplorer Searching...', shell=True)
        except:
            pass
        self.srch.clear()
        self.textBrowser.setGeometry(self.dock.geometry())
        self.textBrowser.setHtml(s_out)
        self.textBrowser.show()
        tmr = QTimer(self.fileView)
        tmr.timeout.connect(self.textBrowser.hide)
        tmr.start(20000)

    def iconChooser(self):
        ' Choose a Icon and copy it to clipboard '
        #
        from .std_icon_naming import std_icon_naming as a
        #
        prv = QDialog(self.dock)
        prv.setWindowFlags(Qt.FramelessWindowHint)
        prv.setAutoFillBackground(True)
        prv.setGeometry(self.fileView.geometry())
        table = QTableWidget(prv)
        table.setColumnCount(1)
        table.setRowCount(len(a))
        table.verticalHeader().setVisible(True)
        table.horizontalHeader().setVisible(False)
        table.setShowGrid(True)
        table.setIconSize(QSize(128, 128))
        for index, icon in enumerate(a):
            item = QTableWidgetItem(QIcon.fromTheme(icon), '')
            # item.setData(Qt.UserRole, '')
            item.setToolTip(icon)
            table.setItem(index, 0, item)
        table.clicked.connect(lambda: QApplication.clipboard().setText(
          'QtGui.QIcon.fromTheme("{}")'.format(table.currentItem().toolTip())))
        table.doubleClicked.connect(prv.close)
        table.resizeColumnsToContents()
        table.resizeRowsToContents()
        QLabel('<h3> <br> 1 Click Copy, 2 Clicks Close </h3>', table)
        table.resize(prv.size())
        prv.exec_()

    def runfile(self, index):
        ' run the choosed file '
        s = str(file(self.model.filePath(index), 'r').read().strip())
        f = str(self.model.filePath(index))
        # ctime is NOT crossplatform,metadata change on *nix,creation on Window
        # http://docs.python.org/library/os.path.html#os.path.getctime
        m = ''.join((f, N, str(path.getsize(f) / 1024), ' Kilobytes', N,
            str(len(file(f, 'r').readlines())), ' Lines', N,
            str(len(s.replace(N, ''))), ' Characters', N,
            str(len([a for a in sub('[^a-zA-Z0-9 ]', '', s).split(' ')
                if a != ''])), ' Words', N,
            str(len([a for a in s if a in punctuation])), ' Punctuation', N,
            oct(stat(f).st_mode)[-3:], ' Permissions', N,
            time.ctime(path.getatime(f)), ' Accessed', N,
            time.ctime(path.getmtime(f)), ' Modified', N,
            'Owner: ', str(self.model.fileInfo(index).owner()), N,
            'Is Writable: ', str(self.model.fileInfo(index).isWritable()), N,
            'Is Executable: ', str(self.model.fileInfo(index).isExecutable()),
            N, 'Is Hidden: ', str(self.model.fileInfo(index).isHidden()), N,
            'Is SymLink: ', str(self.model.fileInfo(index).isSymLink()), N,
            'File Extension: ', str(self.model.fileInfo(index).suffix())
        ))
        #print(m)
        self.preview.setToolTip(m)
        self.preview.setText(s)
        self.preview.resize(self.preview.size().width(),
                            self.dock.size().height())
        self.process.start('xdg-open {}'.format(f))
        if not self.process.waitForStarted():
            print((" ERROR: Process {} Failed ! ".format(str(f))))
            return