예제 #1
0
class OWCodeViewer(OWWidget):
    name = "Code Viewer"
    description = "Display"
    icon = "icons/Code.svg"
    priority = 10
    keywords = ["source", "code", "display", "programming"]
    directory = ""

    show_configuration = False

    class Inputs:
        data = Input("Source Code", Orange.data.Table)

    #class Outputs:
    #    sample = Output("Sampled Data", Orange.data.Table)

    want_main_area = False

    def __init__(self):
        super().__init__()

        # GUI
        box = gui.widgetBox(self.controlArea, "Info")
        self.infoLabel = gui.widgetLabel(box, '')

        #self.display_no_source_selected()

        self.code_editor = CodeEditorTextEdit()
        self.controlArea.layout().addWidget(self.code_editor)

        self.configMoreButton = QPushButton("Configuration")
        self.configMoreButton.setCheckable(True)
        self.configMoreButton.clicked.connect(
            self.switch_configuration_visibility)
        self.controlArea.layout().addWidget(self.configMoreButton)

        self.configurationBox = gui.widgetBox(self.controlArea,
                                              "Configuration")
        gui.lineEdit(self.configurationBox,
                     self,
                     'directory',
                     'Source Directory',
                     callback=self.directory_changed)
        self.refresh_configuration_box()

        #Test data
        #self.directory = "C:\\Code\\samples\\juliet-test-suite\\"
        #self.set_data(Table("orangecode/test.csv"))

    def switch_configuration_visibility(self, e):
        self.show_configuration = not (self.show_configuration)
        self.refresh_configuration_box()

    def refresh_configuration_box(self):
        if (self.show_configuration):
            self.configMoreButton.setText("Configuration <<")
            self.configurationBox.show()
        else:
            self.configMoreButton.setText("Configuration >>")
            self.configurationBox.hide()

    @Inputs.data
    def set_data(self, dataset):
        if dataset is not None:
            if (len(dataset) < 1):
                self.display_no_source_selected()
            else:
                #import code
                #code.interact(local=dict(globals(), **locals()))
                self.process_line(dataset[0])
        else:
            self.display_no_source_selected()

    def directory_changed(self):
        self.code_editor.setPlainText("")
        self.update_source_file()

    def process_line(self, line):
        """
        The extraction is based on values to avoid manual configuration.
        """

        self.source_file = ""
        self.source_line = -1

        #code.interact(local=locals())

        all_attributes_index = []

        #Guessing based on values
        for var in itertools.chain(line.domain.attributes, line.domain.metas):
            i = line.domain.index(var.name)
            #print("{} -> {}".format(var.name,i))
            all_attributes_index.append(i)

        for attribute_index in all_attributes_index:
            try:
                line[attribute_index]
            except IndexError:
                print("More attributes than values on line {}".format(line))
                continue

            if (line[attribute_index] is not None):
                val = line[attribute_index].value
                if type(val) is str:
                    val_parts = val.split(":")
                    if (len(val_parts) == 2):
                        if (val_parts[1].isnumeric()):
                            self.source_file = val_parts[0]
                            self.source_line = int(val_parts[1])

        self.update_source_file()

    def update_source_file(self):
        if (self.source_file != ""):
            #Update highlighter
            filename, extension = os.path.splitext(self.source_file)
            self.code_editor.set_highlighter(extension)

            try:
                with open(self.directory + "/" + self.source_file,
                          'r') as file:
                    code = file.read()
                    self.code_editor.setPlainText(code)

                self.display_source_file()
            except IOError:
                _, err, _ = sys.exc_info()
                self.display_error(str(err))
        else:
            self.display_no_source_selected()
            return
        if (self.source_line != -1):
            #print(self.source_line)
            block = self.code_editor.document().findBlockByLineNumber(
                self.source_line - 1)
            self.code_editor.setTextCursor(QTextCursor(block))
            self.code_editor.moveCursor(QTextCursor.EndOfBlock)

    def is_source_file(self, value):
        #print(value.__class__.__name__)
        if not (isinstance(value, str)):
            return False
        for extension in [
                '.java', '.c', '.cpp', '.py', '.js', '.ruby', '.jsp'
        ]:
            if (value.endswith(extension)):
                return True
        return False

    # Information display
    def display_no_source_selected(self):
        self.infoLabel.setText('No source file selected')

    def display_file_not_found(self):
        self.infoLabel.setText('Source file not found')

    def display_error(self, message):
        self.infoLabel.setText('An error has occured: ' + message)

    def display_source_file(self):
        filename = self.source_file.split("/")[-1].split("\\")[-1]
        line = ("" if self.source_line == -1 else " ~ Line: <b>" +
                str(self.source_line) + "</b>")

        self.infoLabel.setText("Source file: <b>{}</b> {}".format(
            filename, line))
예제 #2
0
class OSK(QWidget):
    def __init__(self, rWidget=None):
        super(OSK, self).__init__()
        self.showFullScreen()
        self._rWidget = rWidget
        self.layout = QVBoxLayout(self)
        self.currentText = QLabel(self)
        self.currentText.setAlignment(Qt.AlignCenter)
        if rWidget is not None:
            self.currentText.setText(rWidget.text())
        self.layout.addWidget(self.currentText)
        keyLayout = [['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-'],
                     ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'],
                     ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'],
                     ['z', 'x', 'c', 'v', 'b', 'n', 'm']]
        for l in keyLayout:
            panel = QWidget(self)
            panel.layout = QHBoxLayout(panel)
            for key in l:
                button = OSKKey(key, self, parent=self)
                panel.layout.addWidget(button)
            self.layout.addWidget(panel)
        contolPanel = QWidget(self)
        contolPanel.layout = QHBoxLayout(contolPanel)
        self._shift = QPushButton('Shift', self)
        self._shift.setCheckable(True)
        self._shift.setFixedWidth(150)
        contolPanel.layout.addWidget(self._shift)
        spaceBar = OSKKey('space', self, parent=self)
        spaceBar.rKey = ' '
        spaceBar.setFixedWidth(2 * self.window().geometry().width() / 3)
        contolPanel.layout.addWidget(spaceBar)
        bkspc = OSKKey('delete', self, parent=self)
        bkspc.rKey = '<<'
        contolPanel.layout.addWidget(bkspc)
        self.layout.addWidget(contolPanel)
        self.closeButton = QPushButton("OK", self)
        self.closeButton.clicked.connect(self.__closeButtonAction)
        self.layout.addWidget(self.closeButton)

    def onClick(self, key):
        if self.rWidget is not None:
            if key == '<<':
                self.rWidget.setText(self.rWidget.text()[:-1])
            elif self._shift.isChecked():
                self.rWidget.setText(self.rWidget.text() + key.upper())
                self._shift.setChecked(False)
            else:
                self.rWidget.setText(self.rWidget.text() + key)
            self.currentText.setText(self.rWidget.text())

    def __closeButtonAction(self):
        self.parent().hide()

    @property
    def rWidget(self):
        return self._rWidget

    @rWidget.setter
    def rWidget(self, value):
        if not isinstance(value, QWidget) and value is not None:
            raise TypeError(
                "Supplied return Widget is not of type QWidget: %s" %
                type(value).__name__)
        else:
            self._rWidget = value
            self.currentText.setText(value.text())
예제 #3
0
class ControlButton(ControlBase):
    def __init__(self, *args, **kwargs):
        self._checkable = kwargs.get('checkable', False)
        super(ControlButton, self).__init__(*args, **kwargs)

        default = kwargs.get('default', None)
        if default: self.value = default

    def init_form(self):
        self._form = QPushButton()
        self._form.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self._form.setCheckable(self._checkable)
        self.label = self._label
        self._form.setToolTip(self.help)

    def click(self):
        self._form.click()

    def load_form(self, data, path=None):
        pass

    def save_form(self, data, path=None):
        pass

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

    @property
    def label(self):
        return ControlBase.label.fget(self)

    @label.setter
    def label(self, value):
        ControlBase.label.fset(self, value)
        self._form.setText(self._label)

    @property
    def icon(self):
        return self._form.icon()

    @icon.setter
    def icon(self, value):
        if isinstance(value, (str, bytes)):
            self._form.setIcon(QIcon(value))
        else:
            self._form.setIcon(value)

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

    @property
    def value(self):
        return None

    @value.setter
    def value(self, value):
        try:
            self._form.clicked.disconnect()  # ignore previous signals if any
        except TypeError as err:
            # http://stackoverflow.com/questions/21586643/pyqt-widget-connect-and-disconnect
            pass
        self._form.clicked[bool].connect(value)

    @property
    def checked(self):
        return self._form.isChecked()

    @checked.setter
    def checked(self, value):
        self._form.setChecked(value)