def __init__(self): super(Demo, self).__init__() self.code_editor = CodeEditor(self) self.code_editor.setup_editor( language = "python", font = QFont("Courier New") ) run_sc = QShortcut(QKeySequence("F5"), self, self.run) self.shell = InternalShell(self, {"demo":self}, multithreaded = False, max_line_count = 3000, font = QFont("Courier new", 10), message='caonima' ) self.dict_editor = DictEditorWidget(self, {}) self.dict_editor.editor.set_filter(self.filter_namespace) self.dict_editor.set_data(self.shell.interpreter.namespace) vbox = QVBoxLayout() vbox.addWidget(self.code_editor) vbox.addWidget(self.shell) hbox = QHBoxLayout() hbox.addWidget(self.dict_editor) hbox.addLayout(vbox) self.setLayout(hbox) self.resize(800, 600)
def construct_editor(text): app = qapplication() editor = CodeEditor(parent=None) editor.setup_editor(language='Python') editor.set_text(text) cursor = editor.textCursor() cursor.movePosition(QTextCursor.End) editor.setTextCursor(cursor) return editor
def __init__(self, parent): QWidget.__init__(self, parent) font = QFont(get_family(MONOSPACE), 10, QFont.Normal) info_icon = QLabel() icon = get_std_icon("MessageBoxInformation").pixmap(24, 24) info_icon.setPixmap(icon) info_icon.setFixedWidth(32) info_icon.setAlignment(Qt.AlignTop) self.service_status_label = QLabel() self.service_status_label.setWordWrap(True) self.service_status_label.setAlignment(Qt.AlignTop) self.service_status_label.setFont(font) self.desc_label = QLabel() self.desc_label.setWordWrap(True) self.desc_label.setAlignment(Qt.AlignTop) self.desc_label.setFont(font) self.group_desc = QGroupBox("Description", self) layout = QHBoxLayout() layout.addWidget(info_icon) layout.addWidget(self.desc_label) layout.addStretch() layout.addWidget(self.service_status_label) self.group_desc.setLayout(layout) self.editor = CodeEditor(self) self.editor.setup_editor(linenumbers=True, font=font) self.editor.setReadOnly(False) self.group_code = QGroupBox("Source code", self) layout = QVBoxLayout() layout.addWidget(self.editor) self.group_code.setLayout(layout) self.enable_button = QPushButton(get_icon("apply.png"), "Enable", self) self.save_button = QPushButton(get_icon("filesave.png"), "Save", self) self.disable_button = QPushButton(get_icon("delete.png"), "Disable", self) self.refresh_button = QPushButton(get_icon("restart.png"), "Refresh", self) hlayout = QHBoxLayout() hlayout.addWidget(self.save_button) hlayout.addWidget(self.enable_button) hlayout.addWidget(self.disable_button) hlayout.addWidget(self.refresh_button) vlayout = QVBoxLayout() vlayout.addWidget(self.group_desc) vlayout.addWidget(self.group_code) self.html_window = HTMLWindow() vlayout.addWidget(self.html_window) vlayout.addLayout(hlayout) self.setLayout(vlayout) self.current_file = None
class Demo(QWidget): def __init__(self): super(Demo, self).__init__() self.code_editor = CodeEditor(self) self.code_editor.setup_editor( language = "python", font = QFont("Courier New") ) run_sc = QShortcut(QKeySequence("F5"), self, self.run) self.shell = InternalShell(self, {"demo":self}, multithreaded = False, max_line_count = 3000, font = QFont("Courier new", 10), message='caonima' ) self.dict_editor = DictEditorWidget(self, {}) self.dict_editor.editor.set_filter(self.filter_namespace) self.dict_editor.set_data(self.shell.interpreter.namespace) vbox = QVBoxLayout() vbox.addWidget(self.code_editor) vbox.addWidget(self.shell) hbox = QHBoxLayout() hbox.addWidget(self.dict_editor) hbox.addLayout(vbox) self.setLayout(hbox) self.resize(800, 600) def filter_namespace(self, data): result = {} support_types = [np.ndarray, int, float, str, tuple, dict, list] for key, value in data.items(): if not key.startswith("__") and type(value) in support_types: result[key] = value return result def run(self): code = str(self.code_editor.toPlainText()) namespace = self.shell.interpreter.namespace exec (code,namespace ) self.dict_editor.set_data(namespace)
def __init__(self, parent): QWidget.__init__(self, parent) font = QFont(get_family(MONOSPACE), 10, QFont.Normal) info_icon = QLabel() icon = get_std_icon('MessageBoxInformation').pixmap(24, 24) info_icon.setPixmap(icon) info_icon.setFixedWidth(32) info_icon.setAlignment(Qt.AlignTop) self.desc_label = QLabel() self.desc_label.setWordWrap(True) self.desc_label.setAlignment(Qt.AlignTop) self.desc_label.setFont(font) group_desc = QGroupBox(_("Description"), self) layout = QHBoxLayout() layout.addWidget(info_icon) layout.addWidget(self.desc_label) group_desc.setLayout(layout) self.editor = CodeEditor(self) self.editor.setup_editor(linenumbers=True, font=font) self.editor.setReadOnly(True) group_code = QGroupBox(_("Source code"), self) layout = QVBoxLayout() layout.addWidget(self.editor) group_code.setLayout(layout) self.run_button = QPushButton(get_icon("apply.png"), _("Run this script"), self) self.quit_button = QPushButton(get_icon("exit.png"), _("Quit"), self) hlayout = QHBoxLayout() hlayout.addWidget(self.run_button) hlayout.addStretch() hlayout.addWidget(self.quit_button) vlayout = QVBoxLayout() vlayout.addWidget(group_desc) vlayout.addWidget(group_code) vlayout.addLayout(hlayout) self.setLayout(vlayout)
def setupUi(self): self.setWindowTitle('Edit filter') #self.resize(400, 300) self.signatureLabel = QLabel(self) self.signatureLabel.setText('def filter(block):') font = QFont('Some font that does not exist') font.setStyleHint(font.TypeWriter, font.PreferDefault) self.editor = CodeEditor() self.editor.setup_editor(linenumbers=False, language='py', scrollflagarea=False, codecompletion_enter=True, font=font, highlight_current_line=False, occurence_highlighting=False) self.editor.set_text('return True') self.editor.setCursor(Qt.IBeamCursor) self.onExceptionCheckBox = QCheckBox(self) self.onExceptionCheckBox.setText('True on exception') self.onExceptionCheckBox.setToolTip('Determines if the filter will be admit items if there is an exception during its execution') self.filterTypeComboBox = QComboBox(self) self.filterTypeComboBox.addItem('Block') self.filterTypeComboBox.addItem('Segment') self.filterTypeComboBox.addItem('Recording Channel Group') self.filterTypeComboBox.addItem('Recording Channel') self.filterTypeComboBox.addItem('Unit') self.filterGroupComboBox = QComboBox(self) self.nameLineEdit = QLineEdit() self.dialogButtonBox = QDialogButtonBox(self) self.dialogButtonBox.setAutoFillBackground(False) self.dialogButtonBox.setOrientation(Qt.Horizontal) self.dialogButtonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) self.dialogButtonBox.setCenterButtons(True) gridLayout = QGridLayout(self) gridLayout.addWidget(self.signatureLabel, 0, 0, 1, 2) gridLayout.addWidget(self.editor, 1, 0, 1, 2) gridLayout.addWidget(self.onExceptionCheckBox, 2,0, 1, 2) gridLayout.addWidget(QLabel('Type:', self), 3, 0) gridLayout.addWidget(self.filterTypeComboBox, 3, 1) gridLayout.addWidget(QLabel('Group:', self), 4, 0) gridLayout.addWidget(self.filterGroupComboBox, 4, 1) gridLayout.addWidget(QLabel('Name:', self), 5, 0) gridLayout.addWidget(self.nameLineEdit, 5, 1) gridLayout.addWidget(self.dialogButtonBox, 6, 0, 1, 2) self.connect(self.dialogButtonBox, SIGNAL('accepted()'), self.accept) self.connect(self.dialogButtonBox, SIGNAL('rejected()'), self.reject) self.connect(self.filterTypeComboBox, SIGNAL('currentIndexChanged(int)'), self.on_filterTypeComboBox_currentIndexChanged)
def __init__(self, parent=None): super(MyWidget, self).__init__(parent) self.resize(1000, 1000) layout = QtGui.QVBoxLayout() editor = CodeEditor(self) self.connect( editor, QtCore.SIGNAL('modificationChanged(bool)'), lambda state: self.modification_changed(state, editor_id=id(editor))) self.index = 0 self.btn1 = QtGui.QPushButton() layout.addWidget(self.btn1) layout.addWidget(editor) self.setLayout(layout)
def _init_python_tab(self): # Console ns = {'current': self.provider, 'selections': self.selections} cmds = """ from __future__ import division import scipy as sp import numpy as np import matplotlib.pyplot as plt import guiqwt import guiqwt.pyplot as guiplt import guidata import spykeutils import spykeviewer plt.ion() """.split('\n') self.console = InternalShell(self.consoleDock, namespace=ns, multithreaded=False, commands=cmds, max_line_count=1000) self.consoleDock.setWidget(self.console) self.console.clear_terminal() # Variable browser self.browser = NamespaceBrowser(self.variableExplorerDock) self.browser.set_shellwidget(self.console) self.browser.setup(check_all=True, exclude_private=True, exclude_uppercase=False, exclude_capitalized=False, exclude_unsupported=True, excluded_names=[], truncate=False, minmax=False, collvalue=False, remote_editing=False, inplace=False, autorefresh=False) self.variableExplorerDock.setWidget(self.browser) # History self.history = CodeEditor(self.historyDock) self.history.setup_editor(linenumbers=False, language='py', scrollflagarea=False) self.history.setReadOnly(True) self.history.set_text('\n'.join(self.console.history)) self.history.set_cursor_position('eof') self.historyDock.setWidget(self.history) self.console.connect(self.console, SIGNAL("refresh()"), self._append_python_history)
def setupUi(self): self.setWindowTitle('Edit filter') #self.resize(400, 300) self.signatureLabel = QLabel(self) self.signatureLabel.setText('def filter(block):') font = QFont('Some font that does not exist') font.setStyleHint(font.TypeWriter, font.PreferDefault) self.editor = CodeEditor(self) self.editor.setup_editor(linenumbers=False, language='py', scrollflagarea=False, codecompletion_enter=True, font=font, highlight_current_line=False, occurence_highlighting=False) self.editor.setCursor(Qt.IBeamCursor) self.editor.horizontalScrollBar().setCursor(Qt.ArrowCursor) self.editor.verticalScrollBar().setCursor(Qt.ArrowCursor) self.editor.set_text('return True') self.onExceptionCheckBox = QCheckBox(self) self.onExceptionCheckBox.setText('True on exception') self.onExceptionCheckBox.setToolTip('Determines if the filter will ' 'admit items if there is an ' 'exception during its execution') self.combinedCheckBox = QCheckBox(self) self.combinedCheckBox.setText('Combined filter') self.combinedCheckBox.setToolTip('Determines if the filter operates ' 'on single items (return True or ' 'False) or lists of items (return a ' 'list of items to be admitted)') self.filterTypeComboBox = QComboBox(self) self.filterTypeComboBox.addItem('Block') self.filterTypeComboBox.addItem('Segment') self.filterTypeComboBox.addItem('Recording Channel Group') self.filterTypeComboBox.addItem('Recording Channel') self.filterTypeComboBox.addItem('Unit') self.filterGroupComboBox = QComboBox(self) self.nameLineEdit = QLineEdit() self.dialogButtonBox = QDialogButtonBox(self) self.dialogButtonBox.setAutoFillBackground(False) self.dialogButtonBox.setOrientation(Qt.Horizontal) self.dialogButtonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.dialogButtonBox.setCenterButtons(True) gridLayout = QGridLayout(self) gridLayout.addWidget(self.signatureLabel, 0, 0, 1, 4) gridLayout.addWidget(self.editor, 1, 0, 1, 4) gridLayout.addWidget(self.onExceptionCheckBox, 2, 2, 1, 1) gridLayout.addWidget(self.combinedCheckBox, 2, 3, 1, 1) gridLayout.addWidget(QLabel('Type:', self), 2, 0) gridLayout.addWidget(self.filterTypeComboBox, 2, 1) gridLayout.addWidget(QLabel('Group:', self), 3, 0) gridLayout.addWidget(self.filterGroupComboBox, 3, 1, 1, 3) gridLayout.addWidget(QLabel('Name:', self), 4, 0) gridLayout.addWidget(self.nameLineEdit, 4, 1, 1, 3) gridLayout.addWidget(self.dialogButtonBox, 5, 0, 1, 4) self.connect(self.dialogButtonBox, SIGNAL('accepted()'), self.accept) self.connect(self.dialogButtonBox, SIGNAL('rejected()'), self.reject) self.combinedCheckBox.stateChanged.connect(self.combined_state_changed) self.connect(self.filterTypeComboBox, SIGNAL('currentIndexChanged(int)'), self.on_filterTypeComboBox_currentIndexChanged)
def __init__(self, parent): QWidget.__init__(self, parent) font = QFont(get_family(MONOSPACE), 10, QFont.Normal) info_icon = QLabel() icon = get_std_icon('MessageBoxInformation').pixmap(24, 24) info_icon.setPixmap(icon) info_icon.setFixedWidth(32) info_icon.setAlignment(Qt.AlignTop) self.service_status_label = QLabel() self.service_status_label.setWordWrap(True) self.service_status_label.setAlignment(Qt.AlignTop) self.service_status_label.setFont(font) self.desc_label = QLabel() self.desc_label.setWordWrap(True) self.desc_label.setAlignment(Qt.AlignTop) self.desc_label.setFont(font) self.group_desc = QGroupBox("Description", self) layout = QHBoxLayout() layout.addWidget(info_icon) layout.addWidget(self.desc_label) layout.addStretch() layout.addWidget(self.service_status_label) self.group_desc.setLayout(layout) self.editor = CodeEditor(self) self.editor.setup_editor(linenumbers=True, font=font) self.editor.setReadOnly(False) self.group_code = QGroupBox("Source code", self) layout = QVBoxLayout() layout.addWidget(self.editor) self.group_code.setLayout(layout) self.enable_button = QPushButton(get_icon("apply.png"), "Enable", self) self.save_button = QPushButton(get_icon("filesave.png"), "Save", self) self.disable_button = QPushButton(get_icon("delete.png"), "Disable", self) self.refresh_button = QPushButton(get_icon("restart.png"), "Refresh", self) hlayout = QHBoxLayout() hlayout.addWidget(self.save_button) hlayout.addWidget(self.enable_button) hlayout.addWidget(self.disable_button) hlayout.addWidget(self.refresh_button) vlayout = QVBoxLayout() vlayout.addWidget(self.group_desc) vlayout.addWidget(self.group_code) self.html_window = HTMLWindow() vlayout.addWidget(self.html_window) vlayout.addLayout(hlayout) self.setLayout(vlayout) self.current_file = None
class PropertiesWidget(QWidget): def __init__(self, parent): QWidget.__init__(self, parent) font = QFont(get_family(MONOSPACE), 10, QFont.Normal) info_icon = QLabel() icon = get_std_icon('MessageBoxInformation').pixmap(24, 24) info_icon.setPixmap(icon) info_icon.setFixedWidth(32) info_icon.setAlignment(Qt.AlignTop) self.service_status_label = QLabel() self.service_status_label.setWordWrap(True) self.service_status_label.setAlignment(Qt.AlignTop) self.service_status_label.setFont(font) self.desc_label = QLabel() self.desc_label.setWordWrap(True) self.desc_label.setAlignment(Qt.AlignTop) self.desc_label.setFont(font) self.group_desc = QGroupBox("Description", self) layout = QHBoxLayout() layout.addWidget(info_icon) layout.addWidget(self.desc_label) layout.addStretch() layout.addWidget(self.service_status_label) self.group_desc.setLayout(layout) self.editor = CodeEditor(self) self.editor.setup_editor(linenumbers=True, font=font) self.editor.setReadOnly(False) self.group_code = QGroupBox("Source code", self) layout = QVBoxLayout() layout.addWidget(self.editor) self.group_code.setLayout(layout) self.enable_button = QPushButton(get_icon("apply.png"), "Enable", self) self.save_button = QPushButton(get_icon("filesave.png"), "Save", self) self.disable_button = QPushButton(get_icon("delete.png"), "Disable", self) self.refresh_button = QPushButton(get_icon("restart.png"), "Refresh", self) hlayout = QHBoxLayout() hlayout.addWidget(self.save_button) hlayout.addWidget(self.enable_button) hlayout.addWidget(self.disable_button) hlayout.addWidget(self.refresh_button) vlayout = QVBoxLayout() vlayout.addWidget(self.group_desc) vlayout.addWidget(self.group_code) self.html_window = HTMLWindow() vlayout.addWidget(self.html_window) vlayout.addLayout(hlayout) self.setLayout(vlayout) self.current_file = None def set_status(self): self.refresh_button.setEnabled(True) self.disable_button.setEnabled(False) self.enable_button.setEnabled(False) self.save_button.setEnabled(False) def set_item(self, check): self.refresh_button.setEnabled(False) self.save_button.setEnabled(True) self.current_file = check self.desc_label.setText(check.get_description()) self.editor.set_text_from_file(check.file_path) check.content = self.editor.toPlainText().__str__() if check.enabled: self.disable_button.setEnabled(True) self.enable_button.setEnabled(False) else: self.disable_button.setEnabled(False) self.enable_button.setEnabled(True) def set_datadog_conf(self, datadog_conf): self.save_button.setEnabled(True) self.refresh_button.setEnabled(False) self.current_file = datadog_conf self.desc_label.setText(datadog_conf.get_description()) self.editor.set_text_from_file(datadog_conf.file_path) datadog_conf.content = self.editor.toPlainText().__str__() self.disable_button.setEnabled(False) self.enable_button.setEnabled(False) datadog_conf.check_api_key(self.editor) def set_log_file(self, log_file): self.save_button.setEnabled(False) self.refresh_button.setEnabled(True) self.disable_button.setEnabled(False) self.enable_button.setEnabled(False) try: self.current_file = log_file self.desc_label.setText(log_file.get_description()) self.editor.set_text_from_file(log_file.file_path) log_file.content = self.editor.toPlainText().__str__() self.editor.go_to_line(len(log_file.content.splitlines())) except Exception: self.editor.set_text("Log file not found")
def __init__(self, parent): QWidget.__init__(self, parent) font = QFont(get_family(MONOSPACE), 10, QFont.Normal) info_icon = QLabel() icon = get_std_icon('MessageBoxInformation').pixmap(24, 24) info_icon.setPixmap(icon) info_icon.setFixedWidth(32) info_icon.setAlignment(Qt.AlignTop) self.service_status_label = QLabel() self.service_status_label.setWordWrap(True) self.service_status_label.setAlignment(Qt.AlignTop) self.service_status_label.setFont(font) self.desc_label = QLabel() self.desc_label.setWordWrap(True) self.desc_label.setAlignment(Qt.AlignTop) self.desc_label.setFont(font) group_desc = QGroupBox("Description", self) layout = QHBoxLayout() layout.addWidget(info_icon) layout.addWidget(self.desc_label) layout.addStretch() layout.addWidget(self.service_status_label ) group_desc.setLayout(layout) self.editor = CodeEditor(self) self.editor.setup_editor(linenumbers=True, font=font) self.editor.setReadOnly(False) group_code = QGroupBox("Source code", self) layout = QVBoxLayout() layout.addWidget(self.editor) group_code.setLayout(layout) self.enable_button = QPushButton(get_icon("apply.png"), "Enable", self) self.save_button = QPushButton(get_icon("filesave.png"), "Save", self) self.edit_datadog_conf_button = QPushButton(get_icon("edit.png"), "Edit agent settings", self) self.disable_button = QPushButton(get_icon("delete.png"), "Disable", self) self.view_log_button = QPushButton(get_icon("txt.png"), "View log", self) self.menu_button = QPushButton(get_icon("settings.png"), "Manager", self) hlayout = QHBoxLayout() hlayout.addWidget(self.save_button) hlayout.addStretch() hlayout.addWidget(self.enable_button) hlayout.addStretch() hlayout.addWidget(self.disable_button) hlayout.addStretch() hlayout.addWidget(self.edit_datadog_conf_button) hlayout.addStretch() hlayout.addWidget(self.view_log_button) hlayout.addStretch() hlayout.addWidget(self.menu_button) vlayout = QVBoxLayout() vlayout.addWidget(group_desc) vlayout.addWidget(group_code) vlayout.addLayout(hlayout) self.setLayout(vlayout) self.current_file = None
class PropertiesWidget(QWidget): def __init__(self, parent): QWidget.__init__(self, parent) font = QFont(get_family(MONOSPACE), 10, QFont.Normal) info_icon = QLabel() icon = get_std_icon('MessageBoxInformation').pixmap(24, 24) info_icon.setPixmap(icon) info_icon.setFixedWidth(32) info_icon.setAlignment(Qt.AlignTop) self.service_status_label = QLabel() self.service_status_label.setWordWrap(True) self.service_status_label.setAlignment(Qt.AlignTop) self.service_status_label.setFont(font) self.desc_label = QLabel() self.desc_label.setWordWrap(True) self.desc_label.setAlignment(Qt.AlignTop) self.desc_label.setFont(font) group_desc = QGroupBox("Description", self) layout = QHBoxLayout() layout.addWidget(info_icon) layout.addWidget(self.desc_label) layout.addStretch() layout.addWidget(self.service_status_label ) group_desc.setLayout(layout) self.editor = CodeEditor(self) self.editor.setup_editor(linenumbers=True, font=font) self.editor.setReadOnly(False) group_code = QGroupBox("Source code", self) layout = QVBoxLayout() layout.addWidget(self.editor) group_code.setLayout(layout) self.enable_button = QPushButton(get_icon("apply.png"), "Enable", self) self.save_button = QPushButton(get_icon("filesave.png"), "Save", self) self.edit_datadog_conf_button = QPushButton(get_icon("edit.png"), "Edit agent settings", self) self.disable_button = QPushButton(get_icon("delete.png"), "Disable", self) self.view_log_button = QPushButton(get_icon("txt.png"), "View log", self) self.menu_button = QPushButton(get_icon("settings.png"), "Manager", self) hlayout = QHBoxLayout() hlayout.addWidget(self.save_button) hlayout.addStretch() hlayout.addWidget(self.enable_button) hlayout.addStretch() hlayout.addWidget(self.disable_button) hlayout.addStretch() hlayout.addWidget(self.edit_datadog_conf_button) hlayout.addStretch() hlayout.addWidget(self.view_log_button) hlayout.addStretch() hlayout.addWidget(self.menu_button) vlayout = QVBoxLayout() vlayout.addWidget(group_desc) vlayout.addWidget(group_code) vlayout.addLayout(hlayout) self.setLayout(vlayout) self.current_file = None def set_item(self, check): self.current_file = check self.desc_label.setText(check.get_description()) self.editor.set_text_from_file(check.file_path) check.content = self.editor.toPlainText().__str__() if check.enabled: self.disable_button.setEnabled(True) self.enable_button.setEnabled(False) else: self.disable_button.setEnabled(False) self.enable_button.setEnabled(True) def set_datadog_conf(self, datadog_conf): self.current_file = datadog_conf self.desc_label.setText(datadog_conf.get_description()) self.editor.set_text_from_file(datadog_conf.file_path) datadog_conf.content = self.editor.toPlainText().__str__() self.disable_button.setEnabled(False) self.enable_button.setEnabled(False) datadog_conf.check_api_key(self.editor) def set_log_file(self, log_file): self.current_file = log_file self.desc_label.setText(log_file.get_description()) self.editor.set_text_from_file(log_file.file_path) log_file.content = self.editor.toPlainText().__str__() self.disable_button.setEnabled(False) self.enable_button.setEnabled(False) self.editor.go_to_line(len(log_file.content.splitlines()))
def add_file(self, file_name): font = QFont('Some font that does not exist') font.setStyleHint(font.TypeWriter, font.PreferDefault) editor = CodeEditor() editor.setup_editor(linenumbers=True, language='py', scrollflagarea=False, codecompletion_enter=True, tab_mode=False, edge_line=False, font=font, codecompletion_auto=True, go_to_definition=True, codecompletion_single=True) editor.setCursor(Qt.IBeamCursor) editor.horizontalScrollBar().setCursor(Qt.ArrowCursor) editor.verticalScrollBar().setCursor(Qt.ArrowCursor) editor.file_name = file_name if file_name.endswith('py'): editor.set_text_from_file(file_name) tab_name = os.path.split(file_name)[1] else: editor.set_text(self.template_code) tab_name = 'New Analysis' editor.file_was_changed = False editor.textChanged.connect(lambda: self.file_changed(editor)) self.tabs.addTab(editor, tab_name) self.tabs.setCurrentWidget(editor) self.setVisible(True) self.raise_()
def get_indent_fix(text): app = qapplication() editor = CodeEditor(parent=None) editor.setup_editor(language='Python') editor.set_text(text) cursor = editor.textCursor() cursor.movePosition(QTextCursor.End) editor.setTextCursor(cursor) editor.fix_indent() return to_text_string(editor.toPlainText())
class FilterDialog(QDialog): """ A dialog for editing filters """ def __init__(self, groups, type=None, group=None, name=None, code=None, on_exception=False, parent=None): QDialog.__init__(self, parent) self.setupUi() self.groups = groups if type: index = self.filterTypeComboBox.findText(type) if index >= 0: self.filterTypeComboBox.setCurrentIndex(index) self.populate_groups() if group: index = self.filterGroupComboBox.findText(group) if index >= 0: self.filterGroupComboBox.setCurrentIndex(index) if name: self.nameLineEdit.setText(name) if code: self.editor.set_text('\n'.join(code)) if name and code and type: self.filterTypeComboBox.setEnabled(False) self.onExceptionCheckBox.setChecked(on_exception) def populate_groups(self): self.filterGroupComboBox.clear() self.filterGroupComboBox.addItem('') for g in sorted(self.groups[self.filterTypeComboBox.currentText()]): self.filterGroupComboBox.addItem(g) def setupUi(self): self.setWindowTitle('Edit filter') #self.resize(400, 300) self.signatureLabel = QLabel(self) self.signatureLabel.setText('def filter(block):') font = QFont('Some font that does not exist') font.setStyleHint(font.TypeWriter, font.PreferDefault) self.editor = CodeEditor() self.editor.setup_editor(linenumbers=False, language='py', scrollflagarea=False, codecompletion_enter=True, font=font, highlight_current_line=False, occurence_highlighting=False) self.editor.set_text('return True') self.editor.setCursor(Qt.IBeamCursor) self.onExceptionCheckBox = QCheckBox(self) self.onExceptionCheckBox.setText('True on exception') self.onExceptionCheckBox.setToolTip('Determines if the filter will be admit items if there is an exception during its execution') self.filterTypeComboBox = QComboBox(self) self.filterTypeComboBox.addItem('Block') self.filterTypeComboBox.addItem('Segment') self.filterTypeComboBox.addItem('Recording Channel Group') self.filterTypeComboBox.addItem('Recording Channel') self.filterTypeComboBox.addItem('Unit') self.filterGroupComboBox = QComboBox(self) self.nameLineEdit = QLineEdit() self.dialogButtonBox = QDialogButtonBox(self) self.dialogButtonBox.setAutoFillBackground(False) self.dialogButtonBox.setOrientation(Qt.Horizontal) self.dialogButtonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) self.dialogButtonBox.setCenterButtons(True) gridLayout = QGridLayout(self) gridLayout.addWidget(self.signatureLabel, 0, 0, 1, 2) gridLayout.addWidget(self.editor, 1, 0, 1, 2) gridLayout.addWidget(self.onExceptionCheckBox, 2,0, 1, 2) gridLayout.addWidget(QLabel('Type:', self), 3, 0) gridLayout.addWidget(self.filterTypeComboBox, 3, 1) gridLayout.addWidget(QLabel('Group:', self), 4, 0) gridLayout.addWidget(self.filterGroupComboBox, 4, 1) gridLayout.addWidget(QLabel('Name:', self), 5, 0) gridLayout.addWidget(self.nameLineEdit, 5, 1) gridLayout.addWidget(self.dialogButtonBox, 6, 0, 1, 2) self.connect(self.dialogButtonBox, SIGNAL('accepted()'), self.accept) self.connect(self.dialogButtonBox, SIGNAL('rejected()'), self.reject) self.connect(self.filterTypeComboBox, SIGNAL('currentIndexChanged(int)'), self.on_filterTypeComboBox_currentIndexChanged) def name(self): return self.nameLineEdit.text() def code(self): return [self.editor.get_text_line(l) for l in xrange(self.editor.get_line_count())] def type(self): return self.filterTypeComboBox.currentText() def group(self): if self.filterGroupComboBox.currentText() == '': return None return self.filterGroupComboBox.currentText() def on_exception(self): return self.onExceptionCheckBox.isChecked() def code_errors(self): code = self.signatureLabel.text() + '\n\t' code += '\n\t'.join(self.code()) try: compile(code, '<filter>', 'exec') except SyntaxError as e: return e.msg + ' (Line %d)' % (e.lineno - 1) return None def on_filterTypeComboBox_currentIndexChanged(self, index): if index == 0: self.signatureLabel.setText('def filter(block):') elif index == 1: self.signatureLabel.setText('def filter(segment):') elif index == 2: self.signatureLabel.setText('def filter(rcg):') elif index == 3: self.signatureLabel.setText('def filter(rc):') elif index == 4: self.signatureLabel.setText('def filter(unit):') self.populate_groups() #noinspection PyCallByClass,PyTypeChecker,PyArgumentList def accept(self): if len(self.nameLineEdit.text()) < 1: QMessageBox.critical(self, 'Error saving filter', 'Please provide a name for the filter.') return if '"' in self.nameLineEdit.text(): QMessageBox.critical(self, 'Error saving filter', 'You cannot use " in the name of a filter.') return err = self.code_errors() if err: QMessageBox.critical(self, 'Error saving filter', 'Compile error:\n' + err) return QDialog.accept(self)
from PyQt4.QtGui import QApplication, QFont import sys from spyderlib.widgets.sourcecode.codeeditor import CodeEditor app = QApplication(sys.argv) editor = CodeEditor() editor.setup_editor(language="python", font=QFont("Courier New")) editor.set_text(open(__file__).read()) editor.show() sys.exit(app.exec_())
from PyQt4.QtGui import QApplication, QFont import sys from spyderlib.widgets.sourcecode.codeeditor import CodeEditor app = QApplication(sys.argv) editor = CodeEditor() editor.setup_editor(language = "python",font = QFont("Courier New")) editor.set_text(open(__file__).read()) editor.show() sys.exit(app.exec_())
class FilterDialog(QDialog): """ A dialog for editing filters """ solo_signatures = [ 'def filter(block):', 'def filter(segment):', 'def filter(rcg):', 'def filter(rc):', 'def filter(unit):' ] combi_signatures = [ 'def filter(blocks):', 'def filter(segments):', 'def filter(rcgs):', 'def filter(rcs):', 'def filter(units):' ] def __init__(self, groups, type=None, group=None, name=None, code=None, combined=False, on_exception=False, parent=None): QDialog.__init__(self, parent) self.setupUi() self.groups = groups if type: index = self.filterTypeComboBox.findText(type) if index >= 0: self.filterTypeComboBox.setCurrentIndex(index) self.populate_groups() if group: index = self.filterGroupComboBox.findText(group) if index >= 0: self.filterGroupComboBox.setCurrentIndex(index) if name: self.nameLineEdit.setText(name) if code: self.editor.set_text('\n'.join(code)) if name and code and type: self.filterTypeComboBox.setEnabled(False) self.combinedCheckBox.setChecked(combined) self.onExceptionCheckBox.setChecked(on_exception) def populate_groups(self): self.filterGroupComboBox.clear() self.filterGroupComboBox.addItem('') for g in sorted(self.groups[self.filterTypeComboBox.currentText()]): self.filterGroupComboBox.addItem(g) def setupUi(self): self.setWindowTitle('Edit filter') #self.resize(400, 300) self.signatureLabel = QLabel(self) self.signatureLabel.setText('def filter(block):') font = QFont('Some font that does not exist') font.setStyleHint(font.TypeWriter, font.PreferDefault) self.editor = CodeEditor(self) self.editor.setup_editor(linenumbers=False, language='py', scrollflagarea=False, codecompletion_enter=True, font=font, highlight_current_line=False, occurence_highlighting=False) self.editor.setCursor(Qt.IBeamCursor) self.editor.horizontalScrollBar().setCursor(Qt.ArrowCursor) self.editor.verticalScrollBar().setCursor(Qt.ArrowCursor) self.editor.set_text('return True') self.onExceptionCheckBox = QCheckBox(self) self.onExceptionCheckBox.setText('True on exception') self.onExceptionCheckBox.setToolTip('Determines if the filter will ' 'admit items if there is an ' 'exception during its execution') self.combinedCheckBox = QCheckBox(self) self.combinedCheckBox.setText('Combined filter') self.combinedCheckBox.setToolTip('Determines if the filter operates ' 'on single items (return True or ' 'False) or lists of items (return a ' 'list of items to be admitted)') self.filterTypeComboBox = QComboBox(self) self.filterTypeComboBox.addItem('Block') self.filterTypeComboBox.addItem('Segment') self.filterTypeComboBox.addItem('Recording Channel Group') self.filterTypeComboBox.addItem('Recording Channel') self.filterTypeComboBox.addItem('Unit') self.filterGroupComboBox = QComboBox(self) self.nameLineEdit = QLineEdit() self.dialogButtonBox = QDialogButtonBox(self) self.dialogButtonBox.setAutoFillBackground(False) self.dialogButtonBox.setOrientation(Qt.Horizontal) self.dialogButtonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.dialogButtonBox.setCenterButtons(True) gridLayout = QGridLayout(self) gridLayout.addWidget(self.signatureLabel, 0, 0, 1, 4) gridLayout.addWidget(self.editor, 1, 0, 1, 4) gridLayout.addWidget(self.onExceptionCheckBox, 2, 2, 1, 1) gridLayout.addWidget(self.combinedCheckBox, 2, 3, 1, 1) gridLayout.addWidget(QLabel('Type:', self), 2, 0) gridLayout.addWidget(self.filterTypeComboBox, 2, 1) gridLayout.addWidget(QLabel('Group:', self), 3, 0) gridLayout.addWidget(self.filterGroupComboBox, 3, 1, 1, 3) gridLayout.addWidget(QLabel('Name:', self), 4, 0) gridLayout.addWidget(self.nameLineEdit, 4, 1, 1, 3) gridLayout.addWidget(self.dialogButtonBox, 5, 0, 1, 4) self.connect(self.dialogButtonBox, SIGNAL('accepted()'), self.accept) self.connect(self.dialogButtonBox, SIGNAL('rejected()'), self.reject) self.combinedCheckBox.stateChanged.connect(self.combined_state_changed) self.connect(self.filterTypeComboBox, SIGNAL('currentIndexChanged(int)'), self.on_filterTypeComboBox_currentIndexChanged) def name(self): return self.nameLineEdit.text() def code(self): return [ self.editor.get_text_line(l) for l in xrange(self.editor.get_line_count()) ] def type(self): return self.filterTypeComboBox.currentText() def combined(self): return self.combinedCheckBox.isChecked() def group(self): if self.filterGroupComboBox.currentText() == '': return None return self.filterGroupComboBox.currentText() def on_exception(self): return self.onExceptionCheckBox.isChecked() def combined_state_changed(self): self.set_signature() def code_errors(self): code = self.signatureLabel.text() + '\n\t' code += '\n\t'.join(self.code()) try: compile(code, '<filter>', 'exec') except SyntaxError as e: return e.msg + ' (Line %d)' % (e.lineno - 1) return None def set_signature(self): if self.combinedCheckBox.isChecked(): self.signatureLabel.setText( self.combi_signatures[self.filterTypeComboBox.currentIndex()]) else: self.signatureLabel.setText( self.solo_signatures[self.filterTypeComboBox.currentIndex()]) def on_filterTypeComboBox_currentIndexChanged(self, index): self.set_signature() self.populate_groups() #noinspection PyCallByClass,PyTypeChecker,PyArgumentList def accept(self): if len(self.nameLineEdit.text()) < 1: QMessageBox.critical(self, 'Error saving filter', 'Please provide a name for the filter.') return if '"' in self.nameLineEdit.text(): QMessageBox.critical(self, 'Error saving filter', 'You cannot use " in the name of a filter.') return err = self.code_errors() if err: QMessageBox.critical(self, 'Error saving filter', 'Compile error:\n' + err) return QDialog.accept(self)
class MainWindow(QMainWindow, Ui_MainWindow): """ The main window of SpikeViewer """ def __init__(self, parent = None): QMainWindow.__init__(self, parent) QCoreApplication.setOrganizationName('SpykeUtils') QCoreApplication.setApplicationName('Spyke Viewer') self.setupUi(self) self.dir = os.getcwd() self.console = None self.progress = ProgressIndicatorDialog(self) self.provider_factory = DataProvider self.selections = [] self.provider = None self.plugin_paths = [] # Drag and Drop for selections menu self.menuSelections.setAcceptDrops(True) self.menuSelections.paintEvent =\ self.on_menuSelections_paint self.menuSelections.mousePressEvent =\ self.on_menuSelections_mousePressed self.menuSelections.mouseMoveEvent =\ self.on_menuSelections_mouseMoved self.menuSelections.dragEnterEvent =\ self.on_menuSelections_dragEnter self.menuSelections.dragMoveEvent =\ self.on_menuSelections_dragMoved self.menuSelections.dropEvent =\ self.on_menuSelections_drop self.seldrag_start_pos = None self.seldrag_selection = None self.seldrag_target = None self.seldrag_target_upper = False # Docks self.setCentralWidget(None) # A lot of docks are only needed for the internal database mode self.navigationDBDock.setVisible(False) self.filterDBDock.setVisible(False) self.spikeSortingDock.setVisible(False) self.waveformsDock.setVisible(False) self.spikeTrainDock.setVisible(False) if not hasattr(self, 'internal_database_mode'): self.removeDockWidget(self.navigationDBDock) self.removeDockWidget(self.filterDBDock) self.removeDockWidget(self.spikeSortingDock) self.removeDockWidget(self.waveformsDock) self.removeDockWidget(self.spikeTrainDock) del self.navigationDBDock del self.filterDBDock del self.spikeSortingDock del self.waveformsDock del self.spikeTrainDock self.update_view_menu() if not hasattr(self, 'internal_database_mode'): self.restore_state() self.mode_switch() def update_view_menu(self): self.menuBar.clear() self.menuBar.addMenu(self.menuFile) self.menuBar.addMenu(self.menuSelections) self.menuView = self.createPopupMenu() self.menuView.setTitle('View') self.menuBar.addMenu(self.menuView) self.menuBar.addMenu(self.menuHelp) def restore_state(self): settings = QSettings() if not settings.contains('windowGeometry') or\ not settings.contains('windowState'): self.set_initial_layout() else: self.restoreGeometry(settings.value('windowGeometry')) self.restoreState(settings.value('windowState')) if not settings.contains('pluginPaths'): if hasattr(sys, 'frozen'): module_path = os.path.dirname(sys.executable) else: file_path = os.path.abspath(os.path.dirname(__file__)) module_path = os.path.dirname(os.path.dirname(file_path)) plugin_path = os.path.join(module_path, 'plugins') if os.path.isdir(plugin_path): self.plugin_paths.append(plugin_path) else: paths = settings.value('pluginPaths') if paths is None: self.plugin_paths = [] else: self.plugin_paths = paths if not settings.contains('selectionPath'): data_path = QDesktopServices.storageLocation( QDesktopServices.DataLocation) self.selection_path = os.path.join(data_path, 'selections') else: self.selection_path = settings.value('selectionPath') if not settings.contains('dataPath'): data_path = QDesktopServices.storageLocation( QDesktopServices.DataLocation) AnalysisPlugin.data_dir = os.path.join(data_path, 'data') else: AnalysisPlugin.data_dir = settings.value('dataPath') if not settings.contains('remoteScript'): if hasattr(sys, 'frozen'): path = os.path.dirname(sys.executable) else: file_path = os.path.abspath(os.path.dirname(__file__)) path = os.path.dirname(os.path.dirname(file_path)) path = os.path.join(path, 'bin') self.remote_script = os.path.join(path, 'spykeview_analysis') else: self.remote_script = settings.value('remoteScript') def set_initial_layout(self): self.setGeometry(self.x(), self.y(), 800, 750) self.navigationNeoDock.setVisible(True) self.removeDockWidget(self.filterDock) self.removeDockWidget(self.analysisDock) self.addDockWidget(Qt.RightDockWidgetArea, self.filterDock) self.addDockWidget(Qt.RightDockWidgetArea, self.analysisDock) self.tabifyDockWidget(self.filterDock, self.analysisDock) self.filterDock.setVisible(True) self.analysisDock.setVisible(True) self.consoleDock.setVisible(False) self.variableExplorerDock.setVisible(False) self.historyDock.setVisible(False) self.tabifyDockWidget(self.consoleDock, self.variableExplorerDock) self.tabifyDockWidget(self.variableExplorerDock, self.historyDock) def mode_switch(self): if self.is_db_mode(): self.switch_to_db_mode() if self.is_neo_mode(): self.switch_to_neo_mode() if self.console: self.console.interpreter.locals['current'] = self.provider def switch_to_db_mode(self): raise NotImplementedError() def switch_to_neo_mode(self): raise NotImplementedError() def _init_python_tab(self): # Console ns = {'current': self.provider, 'selections': self.selections} cmds = """ from __future__ import division import scipy as sp import numpy as np import matplotlib.pyplot as plt import guiqwt import guiqwt.pyplot as guiplt import guidata import spykeutils import spykeviewer plt.ion() """.split('\n') self.console = InternalShell(self.consoleDock, namespace=ns, multithreaded=False, commands=cmds, max_line_count=1000) self.consoleDock.setWidget(self.console) self.console.clear_terminal() # Variable browser self.browser = NamespaceBrowser(self.variableExplorerDock) self.browser.set_shellwidget(self.console) self.browser.setup(check_all=True, exclude_private=True, exclude_uppercase=False, exclude_capitalized=False, exclude_unsupported=True, excluded_names=[], truncate=False, minmax=False, collvalue=False, remote_editing=False, inplace=False, autorefresh=False) self.variableExplorerDock.setWidget(self.browser) # History self.history = CodeEditor(self.historyDock) self.history.setup_editor(linenumbers=False, language='py', scrollflagarea=False) self.history.setReadOnly(True) self.history.set_text('\n'.join(self.console.history)) self.history.set_cursor_position('eof') self.historyDock.setWidget(self.history) self.console.connect(self.console, SIGNAL("refresh()"), self._append_python_history) def _append_python_history(self): self.browser.refresh_table() self.history.append('\n' + self.console.history[-1]) self.history.set_cursor_position('eof') def is_neo_mode(self): return True def is_db_mode(self): return False @pyqtSignature("") def on_actionExit_triggered(self): self.close() def on_menuHelp_triggered(self): QMessageBox.about(self, 'How to navigate plots', 'Zoom:\tHold right mouse button' + '\nTranslate:\tHold middle mouse button' + '\nHome:\tClick middle mouse button' + '\n\nAxis synchronization does not work with some actions. ' + 'Zoom or translate changed plot to synchronize.') def on_menuSelections_mousePressed(self, event): if event.button() == Qt.LeftButton: action = self.menuSelections.actionAt(event.pos()) if action: selection = action.data() if selection: self.seldrag_start_pos = event.pos() self.seldrag_selection = selection else: self.seldrag_start_pos = None self.seldrag_selection = None self.seldrag_target = None QMenu.mousePressEvent(self.menuSelections, event) def on_menuSelections_mouseMoved(self, event): if event.buttons() & Qt.LeftButton and self.seldrag_start_pos: if ((event.pos() - self.seldrag_start_pos).manhattanLength() >= QApplication.startDragDistance()): drag = QDrag(self.menuSelections) data = QMimeData() data.setText(self.seldrag_selection.name) drag.setMimeData(data) drag.exec_() self.seldrag_start_pos = None self.seldrag_selection = None self.seldrag_target = None QMenu.mouseMoveEvent(self.menuSelections, event) def on_menuSelections_paint(self, event): QMenu.paintEvent(self.menuSelections, event) if self.seldrag_target: # Paint line where selection will be dropped p = QPainter() color = QPalette().color(self.menuSelections.foregroundRole()) pen = QPen(color, 2, Qt.SolidLine) p.begin(self.menuSelections) p.setPen(pen) rect = self.menuSelections.actionGeometry(self.seldrag_target) if self.seldrag_target_upper: p.drawLine(rect.topLeft(), rect.topRight()) else: p.drawLine(rect.bottomLeft(), rect.bottomRight()) p.end() def _menuSelections_pos_is_drop_target(self, pos): """ Return if selection can be dropped at this position and prepare information needed for drawing and dropping """ action = self.menuSelections.actionAt(pos) if not action or not action.data(): self.seldrag_target = None return False self.seldrag_target = action rect = self.menuSelections.actionGeometry(action) if pos.y() < rect.top() + rect.height() / 2: self.seldrag_target_upper = True else: self.seldrag_target_upper = False return True def on_menuSelections_dragEnter(self, event): event.setDropAction(Qt.MoveAction) if self._menuSelections_pos_is_drop_target(event.pos()): event.accept() else: event.ignore() QMenu.dragEnterEvent(self.menuSelections, event) def on_menuSelections_dragMoved(self, event): event.setDropAction(Qt.MoveAction) if self._menuSelections_pos_is_drop_target(event.pos()): event.accept() self.menuSelections.update() else: event.ignore() QMenu.dragMoveEvent(self.menuSelections, event) def on_menuSelections_drop(self, event): source = self.seldrag_selection target = self.seldrag_target.data() if source != target: self.selections.remove(source) target_index = self.selections.index(target) if not self.seldrag_target_upper: target_index += 1 self.selections.insert(target_index, source) self.populate_selection_menu() QMenu.dropEvent(self.menuSelections, event) def populate_selection_menu(self): self.menuSelections.clear() a = self.menuSelections.addAction('New') a.triggered.connect(self.on_selection_new) a = self.menuSelections.addAction('Clear') a.triggered.connect(self.on_selection_clear) self.menuSelections.addSeparator() for i, s in enumerate(self.selections): m = self.menuSelections.addMenu(s.name) m.menuAction().setData(s) a = m.addAction('Load') self.connect(a, SIGNAL('triggered()'), lambda sel=s:self.on_selection_load(sel)) a = m.addAction('Save') self.connect(a, SIGNAL('triggered()'), lambda sel=s:self.on_selection_save(sel)) a = m.addAction('Rename') self.connect(a, SIGNAL('triggered()'), lambda sel=s:self.on_selection_rename(sel)) a = m.addAction('Remove') self.connect(a, SIGNAL('triggered()'), lambda sel=s:self.on_selection_remove(sel)) def on_selection_load(self, selection): self.set_current_selection(selection.data_dict()) def on_selection_save(self, selection): i = self.selections.index(selection) self.selections[i] = self.provider_factory( self.selections[i].name, self) self.populate_selection_menu() def on_selection_clear(self): if QMessageBox.question(self, 'Confirmation', 'Do you really want to remove all selections?', QMessageBox.Yes | QMessageBox.No) == QMessageBox.No: return del self.selections[:] self.populate_selection_menu() def on_selection_rename(self, selection): (name, ok) = QInputDialog.getText(self, 'Edit selection name', 'New name:', QLineEdit.Normal, selection.name) if ok and name: selection.name = name self.populate_selection_menu() def on_selection_remove(self, selection): if QMessageBox.question(self, 'Confirmation', 'Do you really want to remove the selection "%s"?' % selection.name, QMessageBox.Yes | QMessageBox.No) == QMessageBox.No: return self.selections.remove(selection) self.populate_selection_menu() def on_selection_new(self): self.selections.append(self.provider_factory('Selection %d' % (len(self.selections) + 1), self)) self.populate_selection_menu() def serialize_selections(self): sl = list() # Selection list, current selection as first item sl.append(self.provider_factory('current', self).data_dict()) for s in self.selections: sl.append(s.data_dict()) return json.dumps(sl, sort_keys=True, indent=2) def save_selections_to_file(self, filename): f = open(filename, 'w') f.write(self.serialize_selections()) f.close() def load_selections_from_file(self, filename): try: f = open(filename, 'r') p = json.load(f) # First selection in file is current selection self.set_current_selection(p[0]) for s in p[1:]: self.add_selection(s) f.close() self.populate_selection_menu() except Exception, e: self.progress.done() QMessageBox.critical(self, 'Error loading selection', str(e).decode('utf8'))