コード例 #1
0
ファイル: views.py プロジェクト: Evansbee/synacor
    def __init__(self, parent, ID, vm):
        self.breakpoint_lines = []
        StyledTextCtrl.__init__(self, parent, ID)
        self.SetKeyWords(
            0, "nop set halt add eq mod push pop jnz gt jz jmp call in out")

        faces = {
            'times': 'Times New Roman',
            'mono': 'Consolas',
            'helv': 'Arial',
            'other': 'Comic Sans MS',
            'size': 12,
            'size2': 10,
        }
        self.StyleSetSpec(stc.STC_STYLE_DEFAULT,
                          "face:%(mono)s,size:%(size)d" % faces)
        self.StyleClearAll()  # Reset all to be like the default

        self.SetMarginType(0, stc.STC_MARGIN_NUMBER)
        self.SetMarginWidth(0, 50)
        self.StyleSetSpec(stc.STC_STYLE_LINENUMBER,
                          "size:%d,face:%s" % (10, 'mono'))

        self.SetMarginType(1, stc.STC_MARGIN_SYMBOL)
        self.SetMarginWidth(1, 70)
        self.MarkerDefine(0, stc.STC_MARK_ROUNDRECT, "#CCFF00", "RED")

        self.SetMarginSensitive(1, True)

        self.Bind(stc.EVT_STC_MARGINCLICK, self.onSetRemoveBreakpoint)
コード例 #2
0
ファイル: Notebook.py プロジェクト: neffmallon/pistol
 def __init__(self,*args,**kwargs):
     StyledTextCtrl.__init__(self,*args,**kwargs)
     self.shell = Shell()
     try:
         self.ps1 = sys.ps1
         self.ps2 = sys.ps2
     except:
         self.ps1 = '>>> '
         self.ps2 = '... '
     wx.EVT_KEY_DOWN(self, self.OnKeyDown)
     self.Write(self.ps1)
     self.prompt_pos_end = self.GetCurrentPos()
     return
コード例 #3
0
    def __init__(self, *args, **kwds):
        kwds["style"] = wx.TAB_TRAVERSAL
        wx.Panel.__init__(self, *args, **kwds)

        self._config = EditorConfig (Application.config)

        self._enableSpellChecking = True
        self._spellChecker = None

        self.SPELL_ERROR_INDICATOR = 0

        self._spellErrorText = None
        self._spellSuggestList = []

        self._spellMaxSuggest = len (TextEditorMenu.ID_SUGGESTS)
        self._spellStartByteError = -1
        self._spellEndByteError = -1

        # Уже были установлены стили текста (раскраска)
        self._styleSet = False

        self.__stylebytes = None
        self.__indicatorsbytes = None

        # Начинаем раскраску кода не менее чем через это время с момента его изменения
        self._DELAY = timedelta (milliseconds=300)

        # Время последней модификации текста страницы.
        # Используется для замера времени после модификации, чтобы не парсить текст
        # после каждой введенной буквы
        self._lastEdit = datetime.now() - self._DELAY * 2

        self.textCtrl = StyledTextCtrl(self, -1)

        self._popupMenu = TextEditorMenu(self)

        # Создание панели поиска и ее контроллера
        self._searchPanel = SearchReplacePanel (self)
        self._searchPanelController = SearchReplaceController (self._searchPanel, self)
        self._searchPanel.setController (self._searchPanelController)

        self.__do_layout()
        self.__createCoders()
        self._helper = TextEditorHelper()

        self.__showlinenumbers = self._config.lineNumbers.value

        self.setDefaultSettings()
        self.__bindEvents()
コード例 #4
0
    def __init__(self, parent):
        super(TextEditorBase, self).__init__(parent, style=0)
        self.textCtrl = StyledTextCtrl(self, -1)

        # Создание панели поиска и ее контроллера
        self._searchPanel = SearchReplacePanel(self)
        self._searchPanelController = SearchReplaceController(
            self._searchPanel, self)
        self._searchPanel.setController(self._searchPanelController)

        self._do_layout()

        self.__createCoders()
        self._helper = TextEditorHelper()
        self._bind()
        self._setDefaultSettings()
コード例 #5
0
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyDialog.__init__
        kwds[
            "style"] = wx.DEFAULT_DIALOG_STYLE | wx.MAXIMIZE_BOX | wx.MINIMIZE_BOX | wx.RESIZE_BORDER
        wx.Dialog.__init__(self, *args, **kwds)
        self.combo_box_type = wx.ComboBox(self,
                                          wx.ID_ANY,
                                          choices=[],
                                          style=wx.CB_DROPDOWN)
        self.text_ctrl_number = wx.TextCtrl(self, wx.ID_ANY, _("100"))
        self.text_ctrl_rules = StyledTextCtrl(self, wx.ID_ANY)
        self.window_info = InfoBar(self, wx.ID_ANY)
        self.button_generate = wx.Button(self, wx.ID_ANY, _(u"\u51fa\u9898"))
        self.button_copy_result = wx.Button(self, wx.ID_ANY,
                                            _(u"\u590d\u5236\u7ed3\u679c"))
        self.button_about = wx.Button(self, wx.ID_ANY, _(u"\u5173\u4e8e"))
        self.grid_result = wx.grid.Grid(self, wx.ID_ANY, size=(1, 1))

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_COMBOBOX, self.OnSelectType, self.combo_box_type)
        self.Bind(wx.EVT_BUTTON, self.OnGenerate, self.button_generate)
        self.Bind(wx.EVT_BUTTON, self.OnCopyResult, self.button_copy_result)
        self.Bind(wx.EVT_BUTTON, self.OnAbout, self.button_about)
コード例 #6
0
    def __init__(self, parent):
        super(TextEditorBase, self).__init__(parent, style=0)
        self.textCtrl = StyledTextCtrl(self, -1)

        # Used to fix text encoding after clipboard pasting
        self._needFixTextEncoding = False

        # Создание панели поиска и ее контроллера
        self._searchPanel = SearchReplacePanel(self)
        self._searchPanelController = SearchReplaceController(
            self._searchPanel, self)
        self._searchPanel.setController(self._searchPanelController)

        self._do_layout()

        self._helper = TextEditorHelper()
        self._bind()
        self._setDefaultSettings()
コード例 #7
0
 def open_files(self,
                path,
                exdirs,
                subdirs,
                include,
                exclude,
                ignore_dotted=0):
     for win in self.root.control:
         full = self.getfn(win)
         if namematches(win.filename, include, exclude) and not [
                 i for i in exdirs if i and full.startswith(i)
         ]:
             yield full, fixnewlines(StyledTextCtrl.GetText(win))
コード例 #8
0
    def __init__(self, parent=None, dpi=(1, 1)):
        StyledTextCtrl.__init__(self, parent)
        # 设置样式
        self.InitStyle()
        # 设置显示行号
        self.SetMarginType(0, STC_MARGIN_NUMBER)
        # 设置行号显示区域宽度
        self.SetMarginWidth(0, self.TextWidth(STC_STYLE_LINENUMBER, u"_9999"))
        # 不显示换行符
        self.SetViewEOL(False)
        # 不显示空白字符
        self.SetViewWhiteSpace(False)
        # 行号和内容之间留一定的间距
        self.SetMarginWidth(1, self.TextWidth(STC_STYLE_LINENUMBER, u"_"))
        self.SetEdgeColumn(80)
        self.SetScrollWidth(600 * dpi[0])
        # 可编辑
        self.SetReadOnly(False)

        self.Bind(EVT_STC_CHANGE, self.OnChange)
        self.Bind(EVT_KEY_UP, self.OnCodeEditorKeyUp)
        self.Bind(EVT_KEY_DOWN, self.OnKeyDown)
コード例 #9
0
    def __init__(self, *args, **kwds):
        # begin wxGlade: KarelFrame.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)

        # Menu Bar
        self.kframe_menubar = wx.MenuBar()
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(11, _(u"Configuración..."), "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.AppendSeparator()
        wxglade_tmp_menu.Append(1, _("Salir"), _("Sair del programa por completo"), wx.ITEM_NORMAL)
        self.kframe_menubar.Append(wxglade_tmp_menu, _("Karel"))
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(21, _("Nuevo"), _("Crea un nuevo programa"), wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(22, _("Abrir..."), _(u"Abre un código de Karel"), wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(23, _("Guardar"), _(u"Guarda el código actual"), wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(24, _("Guardar como..."), _(u"Guarda el código actual con otro nombre"), wx.ITEM_NORMAL)
        self.kframe_menubar.Append(wxglade_tmp_menu, _("Programa"))
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(31, _("Nuevo"), _("Crea un nuevo mundo"), wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(32, _("Abrir..."), _("Abre un archivo de mundo"), wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(33, _("Guardar"), _("Guarda el mundo actual"), wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(34, _("Guardar como..."), _("Guarda el mundo actual con otro nombre"), wx.ITEM_NORMAL)
        self.kframe_menubar.Append(wxglade_tmp_menu, _("Mundo"))
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(41, _(u"Documentación"), _(u"Lee la documentación de Karel"), wx.ITEM_NORMAL)
        wxglade_tmp_menu.AppendSeparator()
        wxglade_tmp_menu.Append(42, _("Acerca de..."), _("Cosas importantes que saber de Karel"), wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(43, _(u"Créditos"), _("Personas que ayudaron a este proyecto"), wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(44, _("Licencia"), _("Conoce tus derechos respecto a este software"), wx.ITEM_NORMAL)
        self.kframe_menubar.Append(wxglade_tmp_menu, _("Ayuda"))
        self.SetMenuBar(self.kframe_menubar)
        # Menu Bar end
        self.kframe_statusbar = self.CreateStatusBar(3, 0)

        # Tool Bar
        self.kframe_toolbar = wx.ToolBar(self, -1, style=wx.TB_HORIZONTAL | wx.TB_DOCKABLE | wx.TB_3DBUTTONS)
        self.SetToolBar(self.kframe_toolbar)
        self.kframe_toolbar.AddLabelTool(wx.NewId(), _("Nuevo"), wx.Bitmap("wx/images/document-new.png", wx.BITMAP_TYPE_ANY), wx.Bitmap("wx/images/document-new.png", wx.BITMAP_TYPE_ANY), wx.ITEM_NORMAL, _("Nuevo programa"), _("Crea un nuevo programa"))
        self.kframe_toolbar.AddLabelTool(wx.NewId(), _("Abrir"), wx.Bitmap("wx/images/document-open.png", wx.BITMAP_TYPE_ANY), wx.Bitmap("wx/images/document-open.png", wx.BITMAP_TYPE_ANY), wx.ITEM_NORMAL, _("Abrir programa"), _("Abre un archivo de programa"))
        self.kframe_toolbar.AddLabelTool(wx.NewId(), _("Guardar"), wx.Bitmap("wx/images/document-save.png", wx.BITMAP_TYPE_ANY), wx.Bitmap("wx/images/document-save.png", wx.BITMAP_TYPE_ANY), wx.ITEM_NORMAL, _("Guardar programa"), _("Guarda el programa a un archivo"))
        self.kframe_toolbar.AddSeparator()
        self.kframe_toolbar.AddLabelTool(wx.NewId(), _("Nuevo"), wx.Bitmap("wx/images/world-new.png", wx.BITMAP_TYPE_ANY), wx.Bitmap("wx/images/world-new.png", wx.BITMAP_TYPE_ANY), wx.ITEM_NORMAL, _("Nuevo mundo"), _("Crea un nuevo mundo donde todo es felicidad"))
        self.kframe_toolbar.AddLabelTool(wx.NewId(), _("Abrir"), wx.Bitmap("wx/images/world-open.png", wx.BITMAP_TYPE_ANY), wx.Bitmap("wx/images/world-open.png", wx.BITMAP_TYPE_ANY), wx.ITEM_NORMAL, _("Abre un mundo"), _("Entra a un mundo desconocido"))
        self.kframe_toolbar.AddLabelTool(wx.NewId(), _("Guardar"), wx.Bitmap("wx/images/world-save.png", wx.BITMAP_TYPE_ANY), wx.Bitmap("wx/images/world-save.png", wx.BITMAP_TYPE_ANY), wx.ITEM_NORMAL, _("Salva el mundo"), _(u"Salva el mundo de la destrucción"))
        self.kframe_toolbar.AddSeparator()
        self.kframe_toolbar.AddLabelTool(wx.NewId(), _("Regresar"), wx.Bitmap("wx/images/view-refresh.png", wx.BITMAP_TYPE_ANY), wx.Bitmap("wx/images/view-refresh.png", wx.BITMAP_TYPE_ANY), wx.ITEM_NORMAL, _("Regresar al estado original"), _("Regresa el mundo y el programa a su estado original"))
        self.kframe_toolbar.AddSeparator()
        self.kframe_toolbar.AddLabelTool(wx.NewId(), _("Compilar"), wx.Bitmap("wx/images/applications-system.png", wx.BITMAP_TYPE_ANY), wx.Bitmap("wx/images/applications-system.png", wx.BITMAP_TYPE_ANY), wx.ITEM_NORMAL, _("Compilar programa"), _("Compila el programa"))
        self.kframe_toolbar.AddLabelTool(wx.NewId(), _("Correr"), wx.Bitmap("wx/images/media-playback-start.png", wx.BITMAP_TYPE_ANY), wx.Bitmap("wx/images/media-playback-start.png", wx.BITMAP_TYPE_ANY), wx.ITEM_NORMAL, _("Ejecutar programa"), _("Ejecuta el programa en el mundo"))
        self.kframe_toolbar.AddLabelTool(wx.NewId(), _("Atras"), wx.Bitmap("wx/images/media-seek-backward.png", wx.BITMAP_TYPE_ANY), wx.Bitmap("wx/images/media-seek-backward.png", wx.BITMAP_TYPE_ANY), wx.ITEM_NORMAL, _("Retrocede"), _(u"Retroceder en le ejecución"))
        self.kframe_toolbar.AddLabelTool(wx.NewId(), _("Adelante"), wx.Bitmap("wx/images/media-seek-forward.png", wx.BITMAP_TYPE_ANY), wx.Bitmap("wx/images/media-seek-forward.png", wx.BITMAP_TYPE_ANY), wx.ITEM_NORMAL, _("Avanza"), _(u"Avanza en la ejecución"))
        # Tool Bar end
        self.kseparator = wx.SplitterWindow(self, -1, style=wx.SP_3D | wx.SP_BORDER)
        self.keditorzone = wx.SplitterWindow(self.kseparator, -1, style=wx.SP_3D | wx.SP_BORDER)
        self.kprogram = StyledTextCtrl(self.keditorzone, -1)
        self.notebook_1 = wx.Notebook(self.keditorzone, -1, style=0)
        self.notebook_1_pane_1 = wx.Panel(self.notebook_1, -1)
        self.notebook_1_pane_2 = wx.Panel(self.notebook_1, -1)
        self.notebook_1_pane_3 = wx.Panel(self.notebook_1, -1)
        self.panel_1 = wx.Panel(self.kseparator, -1)
        self.label_1 = wx.StaticText(self.panel_1, -1, _("Mochila: "))
        self.text_ctrl_1 = wx.TextCtrl(self.panel_1, -1, _("0"))
        self.label_2 = wx.StaticText(self.panel_1, -1, _(u"Retraso en la ejecución (ms): "))
        self.text_ctrl_2 = wx.TextCtrl(self.panel_1, -1, _("500"))
        self.karelscrolledwindow = wx.ScrolledWindow(self.panel_1, -1, style=wx.TAB_TRAVERSAL)
        self.mundo_karel = kworldpanel(self.karelscrolledwindow)

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_MENU, self.on_exit, id=1)
        self.Bind(wx.EVT_MENU, self.license_menu_selected, id=44)
コード例 #10
0
def EditSource(self):
    'Brings up a simple editor with the HTML source of this window, available for editing.'

    import wx
    from util import soupify
    from wx.stc import StyledTextCtrl, STC_LEX_HTML

    font = wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL,
                   wx.FONTWEIGHT_NORMAL, False, "Consolas")

    f = wx.Frame(wx.GetTopLevelParent(self), -1, 'View Source', name = 'View Source', size = (640, 480))
    s = wx.BoxSizer(wx.VERTICAL)
    t = StyledTextCtrl(f, -1, wx.DefaultPosition, wx.DefaultSize, wx.NO_BORDER)
    #t.SetLexer(STC_LEX_HTML)

    orightml = self.HTML

    # TODO: BeautifulSoup is more destructive than is useful here.
    html = soupify(orightml).prettify()
    t.SetText(html)
    #t.SetFont(font)
    wx.CallAfter(t.SetSelection, 0, 0)

    buttons = wx.Panel(f)
    save = wx.Button(buttons, -1, '&Save')
    save.Bind(wx.EVT_BUTTON, lambda e: self.SetHTML(t.GetText()))

    save_as_file = wx.Button(buttons, -1, 'Save &As File...')

    def onsaveasfile(e):
        diag = wx.FileDialog(self, "Save HTML", "contents.html", style=wx.SAVE)

        if diag.ShowModal() == wx.ID_OK:
            with open(diag.GetPath(), 'wb') as f:
                f.write(orightml.encode('utf-8'))

    save_as_file.Bind(wx.EVT_BUTTON, onsaveasfile)

    copybutton = wx.Button(buttons, -1, _('&Copy'))

    def openinbrowser(e):
        from subprocess import Popen
        import os.path, tempfile

        fdesc, fname  = tempfile.mkstemp()
        with os.fdopen(fdesc, 'w') as f:
            f.write(t.GetText().encode('utf-8'))

        if "wxMSW" in wx.PlatformInfo:
            from common import pref
            from path import path

            browser_exe = pref('debug.message_area.debug_browser',
                               r'c:\Program Files\Safari\Safari.exe', type=basestring)
            browser_exe = path(browser_exe).expand()

            if browser_exe.isfile():
                Popen([browser_exe, fname])
            else:
                wx.MessageBox('Error launching browser:\n\n'
                              '"%s"\n\n'
                              'Please set the "debug.message_area.debug_browser" pref to\n'
                              'the path to your web browser.' % browser_exe,
                              'Open in Browser')
        else:
            import webbrowser
            webbrowser.open_new("file://" + fname)


    openbutton = wx.Button(buttons, -1, _('&Open in Browser'))
    openbutton.Bind(wx.EVT_BUTTON, openinbrowser)
    openbutton.SetToolTipString(_('Launches browser in pref "debug.message_area.debug_browser"'))

    def docopy(e):
        clip = wx.TheClipboard
        if clip.Open():
            clip.SetData( wx.TextDataObject(t.Value) )
            clip.Close()

    copybutton.Bind(wx.EVT_BUTTON, docopy)

    buttons.Sizer = wx.BoxSizer(wx.HORIZONTAL)
    buttons.Sizer.AddMany([save, copybutton, openbutton, save_as_file])

    s.Add(t, 1, wx.EXPAND)
    s.Add(buttons, 0, wx.EXPAND)
    f.SetSizer(s)

    # remember position and cascade when necessary
    from gui.toolbox import persist_window_pos
    persist_window_pos(f)
    f.EnsureNotStacked()

    f.Show()
コード例 #11
0
class TextEditor(wx.Panel):
    _fontConfigSection = "Font"

    def __init__(self, *args, **kwds):
        kwds["style"] = wx.TAB_TRAVERSAL
        wx.Panel.__init__(self, *args, **kwds)

        self._config = EditorConfig (Application.config)

        self._enableSpellChecking = True
        self._spellChecker = None

        self.SPELL_ERROR_INDICATOR = 0

        self._spellErrorText = None
        self._spellSuggestList = []

        self._spellMaxSuggest = len (TextEditorMenu.ID_SUGGESTS)
        self._spellStartByteError = -1
        self._spellEndByteError = -1

        # Уже были установлены стили текста (раскраска)
        self._styleSet = False

        self.__stylebytes = None
        self.__indicatorsbytes = None

        # Начинаем раскраску кода не менее чем через это время с момента его изменения
        self._DELAY = timedelta (milliseconds=300)

        # Время последней модификации текста страницы.
        # Используется для замера времени после модификации, чтобы не парсить текст
        # после каждой введенной буквы
        self._lastEdit = datetime.now() - self._DELAY * 2

        self.textCtrl = StyledTextCtrl(self, -1)

        self._popupMenu = TextEditorMenu(self)

        # Создание панели поиска и ее контроллера
        self._searchPanel = SearchReplacePanel (self)
        self._searchPanelController = SearchReplaceController (self._searchPanel, self)
        self._searchPanel.setController (self._searchPanelController)

        self.__do_layout()
        self.__createCoders()
        self._helper = TextEditorHelper()

        self.__showlinenumbers = self._config.lineNumbers.value

        self.setDefaultSettings()
        self.__bindEvents()


    def __bindEvents (self):
        self.textCtrl.Bind(wx.EVT_MENU, self.__onCopyFromEditor, id = wx.ID_COPY)
        self.textCtrl.Bind(wx.EVT_MENU, self.__onCutFromEditor, id = wx.ID_CUT)
        self.textCtrl.Bind(wx.EVT_MENU, self.__onPasteToEditor, id = wx.ID_PASTE)
        self.textCtrl.Bind(wx.EVT_MENU, self.__onUndo, id = wx.ID_UNDO)
        self.textCtrl.Bind(wx.EVT_MENU, self.__onRedo, id = wx.ID_REDO)
        self.textCtrl.Bind(wx.EVT_MENU, self.__onSelectAll, id = wx.ID_SELECTALL)

        self.textCtrl.Bind(wx.EVT_MENU, self.__onAddWordToDict, id = TextEditorMenu.ID_ADD_WORD)
        self.textCtrl.Bind(wx.EVT_MENU, self.__onAddWordLowerToDict, id = TextEditorMenu.ID_ADD_WORD_LOWER)

        for suggestId in TextEditorMenu.ID_SUGGESTS:
            self.textCtrl.Bind(wx.EVT_MENU, self.__onSpellSuggest, id = suggestId)

        self.textCtrl.Bind (wx.EVT_CHAR, self.__OnChar_ImeWorkaround)
        self.textCtrl.Bind (wx.EVT_KEY_DOWN, self.__onKeyDown)
        self.textCtrl.Bind (wx.EVT_CONTEXT_MENU, self.__onContextMenu)

        # self.textCtrl.Bind (wx.stc.EVT_STC_STYLENEEDED, self._onStyleNeeded)
        self.textCtrl.Bind (wx.EVT_IDLE, self._onStyleNeeded)
        self.Bind (EVT_APPLY_STYLE, self._onApplyStyle)

        # При перехвате этого сообщения в других классах, нужно вызывать event.Skip(),
        # чтобы это сообщение дошло досюда
        self.textCtrl.Bind (wx.stc.EVT_STC_CHANGE, self.__onChange)


    @property
    def config (self):
        return self._config


    @property
    def enableSpellChecking (self):
        return self._enableSpellChecking


    @enableSpellChecking.setter
    def enableSpellChecking (self, value):
        self._enableSpellChecking = value
        self._styleSet = False


    def __onChange (self, event):
        self._styleSet = False
        self._lastEdit = datetime.now()
        self.__setMarginWidth (self.textCtrl)


    @property
    def searchPanel (self):
        """
        Возвращает контроллер панели поиска
        """
        return self._searchPanelController


    def Print (self):
        selectedtext = self.textCtrl.GetSelectedText()
        text = self.textCtrl.GetText()

        printer = TextPrinter (self)
        printer.printout (text if len (selectedtext) == 0 else selectedtext)


    def __onCopyFromEditor (self, event):
        self.textCtrl.Copy()


    def __onCutFromEditor (self, event):
        self.textCtrl.Cut()


    def __onPasteToEditor (self, event):
        self.textCtrl.Paste()


    def __onUndo (self, event):
        self.textCtrl.Undo()


    def __onRedo (self, event):
        self.textCtrl.Redo()


    def __onSelectAll (self, event):
        self.textCtrl.SelectAll()


    def __do_layout(self):
        mainSizer = wx.FlexGridSizer(rows=2)
        mainSizer.AddGrowableRow(0)
        mainSizer.AddGrowableCol(0)

        mainSizer.Add(self.textCtrl, 0, wx.EXPAND, 0)
        mainSizer.Add(self._searchPanel, 0, wx.EXPAND, 0)
        self.SetSizer(mainSizer)

        self._searchPanel.Hide()
        self.Layout()


    def setDefaultSettings (self):
        """
        Установить стили и настройки по умолчанию в контрол StyledTextCtrl
        """
        self._spellChecker = self.getSpellChecker()

        size = self._config.fontSize.value
        faceName = self._config.fontName.value
        isBold = self._config.fontIsBold.value
        isItalic = self._config.fontIsItalic.value
        fontColor = self._config.fontColor.value
        backColor = self._config.backColor.value

        self.__showlinenumbers = self._config.lineNumbers.value
        self.textCtrl.SetEndAtLastLine (False)

        self.textCtrl.StyleSetSize (wx.stc.STC_STYLE_DEFAULT, size)
        self.textCtrl.StyleSetFaceName (wx.stc.STC_STYLE_DEFAULT, faceName)
        self.textCtrl.StyleSetBold (wx.stc.STC_STYLE_DEFAULT, isBold)
        self.textCtrl.StyleSetItalic (wx.stc.STC_STYLE_DEFAULT, isItalic)
        self.textCtrl.StyleSetForeground (wx.stc.STC_STYLE_DEFAULT, fontColor)
        self.textCtrl.StyleSetBackground (wx.stc.STC_STYLE_DEFAULT, backColor)

        self.textCtrl.StyleClearAll()

        self.textCtrl.SetCaretForeground (fontColor)
        self.textCtrl.SetCaretLineBack (backColor)

        # Заблокируем горячую клавишу Ctrl+D, чтобы использовать ее как добавление закладки
        self.textCtrl.CmdKeyClear (ord ("D"), wx.stc.STC_SCMOD_CTRL)
        self.textCtrl.CmdKeyClear (ord ("R"), wx.stc.STC_SCMOD_CTRL | wx.stc.STC_SCMOD_SHIFT)
        self.textCtrl.SetWrapMode (wx.stc.STC_WRAP_WORD)
        self.textCtrl.SetWrapVisualFlags (wx.stc.STC_WRAPVISUALFLAG_END)

        self.__setMarginWidth (self.textCtrl)
        self.textCtrl.SetTabWidth (self._config.tabWidth.value)

        self.enableSpellChecking = self._config.spellEnabled.value
        self._spellChecker.skipWordsWithNumbers = self.config.spellSkipDigits.value

        if self._config.homeEndKeys.value == EditorConfig.HOME_END_OF_LINE:
            # Клавиши Home / End переносят курсор на начало / конец строки
            self.textCtrl.CmdKeyAssign (wx.stc.STC_KEY_HOME,
                                        0,
                                        wx.stc.STC_CMD_HOMEDISPLAY)

            self.textCtrl.CmdKeyAssign (wx.stc.STC_KEY_HOME,
                                        wx.stc.STC_SCMOD_ALT,
                                        wx.stc.STC_CMD_HOME)

            self.textCtrl.CmdKeyAssign (wx.stc.STC_KEY_END,
                                        0,
                                        wx.stc.STC_CMD_LINEENDDISPLAY)

            self.textCtrl.CmdKeyAssign (wx.stc.STC_KEY_END,
                                        wx.stc.STC_SCMOD_ALT,
                                        wx.stc.STC_CMD_LINEEND)
        else:
            # Клавиши Home / End переносят курсор на начало / конец абзаца
            self.textCtrl.CmdKeyAssign (wx.stc.STC_KEY_HOME,
                                        0,
                                        wx.stc.STC_CMD_HOME)

            self.textCtrl.CmdKeyAssign (wx.stc.STC_KEY_HOME,
                                        wx.stc.STC_SCMOD_ALT,
                                        wx.stc.STC_CMD_HOMEDISPLAY)

            self.textCtrl.CmdKeyAssign (wx.stc.STC_KEY_END,
                                        0,
                                        wx.stc.STC_CMD_LINEEND)

            self.textCtrl.CmdKeyAssign (wx.stc.STC_KEY_END,
                                        wx.stc.STC_SCMOD_ALT,
                                        wx.stc.STC_CMD_LINEENDDISPLAY)

        self.textCtrl.IndicatorSetStyle(self.SPELL_ERROR_INDICATOR, wx.stc.STC_INDIC_SQUIGGLE)
        self.textCtrl.IndicatorSetForeground(self.SPELL_ERROR_INDICATOR, "red")
        self._styleSet = False


    def __setMarginWidth (self, editor):
        """
        Установить размер левой области, где пишутся номера строк в зависимости от шрифта
        """
        if self.__showlinenumbers:
            editor.SetMarginWidth (0, self.__getMarginWidth())
            editor.SetMarginWidth (1, 5)
        else:
            editor.SetMarginWidth (0, 0)
            editor.SetMarginWidth (1, 8)


    def __getMarginWidth (self):
        """
        Расчет размера серой области с номером строк
        """
        fontSize = self._config.fontSize.value
        linescount = len (self.GetText().split("\n"))

        if linescount == 0:
            width = 10
        else:
            # Количество десятичных цифр в числе строк
            digits = int (math.log10 (linescount) + 1)
            width = int (1.2 * fontSize * digits)

        return width


    def getPosChar (self, posBytes):
        return len (self.textCtrl.GetTextRange (0, posBytes))


    def __createCoders (self):
        encoding = outwiker.core.system.getOS().inputEncoding
        self.mbcsEnc = codecs.getencoder(encoding)


    def __onKeyDown (self, event):
        key = event.GetKeyCode()

        if key == wx.WXK_ESCAPE:
            self._searchPanel.Close()

        event.Skip()


    def __OnChar_ImeWorkaround(self, evt):
        """
        Обработка клавиш вручную, чтобы не было проблем с вводом русских букв в Linux.
        Основа кода взята из Wikidpad (WikiTxtCtrl.py -> OnChar_ImeWorkaround)
        """
        key = evt.GetKeyCode()

        # Return if this doesn't seem to be a real character input
        if evt.ControlDown() or (0 < key < 32):
            evt.Skip()
            return

        if key >= wx.WXK_START and evt.GetUnicodeKey() != key:
            evt.Skip()
            return

        unichar = unichr(evt.GetUnicodeKey())

        self.textCtrl.ReplaceSelection(self.mbcsEnc (unichar, "replace")[0])


    def AddText (self, text):
        self.textCtrl.AddText (text)


    def replaceText (self, text):
        self.textCtrl.ReplaceSelection (text)


    def turnText (self, lefttext, righttext):
        selText = self.textCtrl.GetSelectedText()
        newtext = lefttext + selText + righttext
        self.textCtrl.ReplaceSelection (newtext)

        currPos = self.GetSelectionEnd()
        if len (selText) == 0:
            """
            Если не оборачиваем текст, а делаем пустой тег, то поместим каретку до закрывающегося тега
            """
            newpos = currPos - len (righttext)
            self.SetSelection (newpos, newpos)
        else:
            self.SetSelection (currPos - len (selText) - len (righttext),
                               currPos - len (righttext))


    def escapeHtml (self):
        selText = self.textCtrl.GetSelectedText()
        text = cgi.escape (selText, quote=False)
        self.textCtrl.ReplaceSelection (text)


    def SetReadOnly (self, readonly):
        self.textCtrl.SetReadOnly (readonly)


    def GetReadOnly (self):
        return self.textCtrl.GetReadOnly()


    def GetText(self):
        return self.textCtrl.GetText()


    def SetText (self, text):
        self.textCtrl.SetText (text)


    def EmptyUndoBuffer (self):
        self.textCtrl.EmptyUndoBuffer()


    def GetSelectedText (self):
        return self.textCtrl.GetSelectedText()


    def SetSelection (self, start, end):
        """
        start и end в символах, а не в байтах, в отличие от исходного StyledTextCtrl
        """
        startText = self.GetText()[:start]
        endText = self.GetText()[:end]

        firstByte = self._helper.calcByteLen (startText)
        endByte = self._helper.calcByteLen (endText)

        self.textCtrl.SetSelection (firstByte, endByte)


    def GetCurrentPosition (self):
        """
        Возвращает номер символа (а не байта), перед которых находится курсор
        """
        return self.__calcCharPos (self.textCtrl.GetCurrentPos())


    def GetSelectionStart (self):
        """
        Возвращает позицию начала выбранной области в символах, а не в байтах
        """
        return self.__calcCharPos (self.textCtrl.GetSelectionStart())


    def GetSelectionEnd (self):
        """
        Возвращает позицию конца выбранной области в символах, а не в байтах
        """
        return self.__calcCharPos (self.textCtrl.GetSelectionEnd())


    def SetFocus (self):
        self.textCtrl.SetFocus()
        self.textCtrl.SetSTCFocus(True)


    def __calcCharPos (self, pos_bytes):
        """
        Пересчет позиции в байтах в позицию в символах
        """
        text_left = self.textCtrl.GetTextRange (0, pos_bytes)
        currpos = len (text_left)
        return currpos


    def _getTextForParse (self):
        # Табуляция в редакторе считается за несколько символов
        return self.textCtrl.GetText().replace ("\t", " ")


    def runSpellChecking (self, stylelist, fullText, start, end):
        errors = self._spellChecker.findErrors (fullText[start: end])

        for word, err_start, err_end in errors:
            self._helper.setSpellError (stylelist,
                                        fullText,
                                        err_start + start,
                                        err_end + start)


    def _onStyleNeeded (self, event):
        if (not self._styleSet and
                datetime.now() - self._lastEdit >= self._DELAY):
            page = Application.selectedPage
            text = self._getTextForParse()
            params = EditorStyleNeededParams (self,
                                              text,
                                              self._enableSpellChecking)
            Application.onEditorStyleNeeded (page, params)
            self._styleSet = True


    def _onApplyStyle (self, event):
        if event.text == self._getTextForParse():
            startByte = self._helper.calcBytePos (event.text, event.start)
            endByte = self._helper.calcBytePos (event.text, event.end)
            lenBytes = endByte - startByte

            textlength = self._helper.calcByteLen (event.text)
            self.__stylebytes = [0] * textlength

            if event.stylebytes is not None:
                self.__stylebytes = event.stylebytes

            if event.indicatorsbytes is not None:
                self.__stylebytes = [item1 | item2
                                     for item1, item2
                                     in zip (self.__stylebytes, event.indicatorsbytes)]

            stylebytesstr = "".join ([chr(byte) for byte in self.__stylebytes])


            if event.stylebytes is not None:
                self.textCtrl.StartStyling (startByte, 0xff ^ wx.stc.STC_INDICS_MASK)
                self.textCtrl.SetStyleBytes (lenBytes, stylebytesstr[startByte:endByte])

            if event.indicatorsbytes is not None:
                self.textCtrl.StartStyling (startByte, wx.stc.STC_INDICS_MASK)
                self.textCtrl.SetStyleBytes (lenBytes, stylebytesstr[startByte:endByte])

            self._styleSet = True


    def getSpellChecker (self):
        langlist = self._getDictsFromConfig()
        spellDirList = outwiker.core.system.getSpellDirList()

        spellChecker = SpellChecker (Application, langlist, spellDirList)
        spellChecker.addCustomDict (os.path.join (spellDirList[-1], CUSTOM_DICT_FILE_NAME))

        return spellChecker


    def _getDictsFromConfig (self):
        dictsStr = self._config.spellCheckerDicts.value
        return [item.strip()
                for item
                in dictsStr.split(',')
                if item.strip()]


    def _getMenu (self):
        """
        pos_byte - nearest text position (in bytes) where was produce a click
        """
        self._popupMenu.RefreshItems ()
        return self._popupMenu


    def __onContextMenu (self, event):
        point = self.textCtrl.ScreenToClient (event.GetPosition())
        pos_byte = self.textCtrl.PositionFromPoint(point)

        popupMenu = self._getMenu ()
        self._appendSpellItems (popupMenu, pos_byte)

        Application.onEditorPopupMenu (
            Application.selectedPage,
            EditorPopupMenuParams (self, popupMenu, point, pos_byte)
        )

        self.textCtrl.PopupMenu(popupMenu)


    def getCachedStyleBytes (self):
        return self.__stylebytes


    def __onAddWordToDict (self, event):
        if self._spellErrorText is not None:
            self.__addWordToDict (self._spellErrorText)


    def __onAddWordLowerToDict (self, event):
        if self._spellErrorText is not None:
            self.__addWordToDict (self._spellErrorText.lower())


    def __addWordToDict (self, word):
        self._spellChecker.addToCustomDict (0, word)
        self._spellErrorText = None
        self._styleSet = False


    def _appendSpellItems (self, menu, pos_byte):
        stylebytes = self.getCachedStyleBytes()
        if stylebytes is None:
            return

        stylebytes_len = len (stylebytes)

        if (stylebytes is None or
                pos_byte >= stylebytes_len or
                stylebytes[pos_byte] & self._helper.SPELL_ERROR_INDICATOR_MASK == 0):
            return

        endSpellError = startSpellError = pos_byte

        while (startSpellError >= 0 and
               stylebytes[startSpellError] & self._helper.SPELL_ERROR_INDICATOR_MASK != 0):
            startSpellError -= 1


        while (endSpellError < stylebytes_len and
               stylebytes[endSpellError] & self._helper.SPELL_ERROR_INDICATOR_MASK != 0):
            endSpellError += 1

        self._spellStartByteError = startSpellError + 1
        self._spellEndByteError = endSpellError
        self._spellErrorText = self.textCtrl.GetTextRange (self._spellStartByteError, self._spellEndByteError)
        self._spellSuggestList = self._spellChecker.getSuggest (self._spellErrorText)[:self._spellMaxSuggest]

        menu.AppendSeparator()
        menu.AppendSpellSubmenu (self._spellErrorText, self._spellSuggestList)


    def __onSpellSuggest (self, event):
        assert event.GetId() in TextEditorMenu.ID_SUGGESTS

        index = TextEditorMenu.ID_SUGGESTS.index (event.GetId())
        word = self._spellSuggestList[index]

        self.textCtrl.SetSelection (self._spellStartByteError, self._spellEndByteError)
        self.textCtrl.ReplaceSelection (word)
コード例 #12
0
class KarelFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: KarelFrame.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)

        # Menu Bar
        self.kframe_menubar = wx.MenuBar()
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(11, _(u"Configuración..."), "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.AppendSeparator()
        wxglade_tmp_menu.Append(1, _("Salir"), _("Sair del programa por completo"), wx.ITEM_NORMAL)
        self.kframe_menubar.Append(wxglade_tmp_menu, _("Karel"))
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(21, _("Nuevo"), _("Crea un nuevo programa"), wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(22, _("Abrir..."), _(u"Abre un código de Karel"), wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(23, _("Guardar"), _(u"Guarda el código actual"), wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(24, _("Guardar como..."), _(u"Guarda el código actual con otro nombre"), wx.ITEM_NORMAL)
        self.kframe_menubar.Append(wxglade_tmp_menu, _("Programa"))
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(31, _("Nuevo"), _("Crea un nuevo mundo"), wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(32, _("Abrir..."), _("Abre un archivo de mundo"), wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(33, _("Guardar"), _("Guarda el mundo actual"), wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(34, _("Guardar como..."), _("Guarda el mundo actual con otro nombre"), wx.ITEM_NORMAL)
        self.kframe_menubar.Append(wxglade_tmp_menu, _("Mundo"))
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(41, _(u"Documentación"), _(u"Lee la documentación de Karel"), wx.ITEM_NORMAL)
        wxglade_tmp_menu.AppendSeparator()
        wxglade_tmp_menu.Append(42, _("Acerca de..."), _("Cosas importantes que saber de Karel"), wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(43, _(u"Créditos"), _("Personas que ayudaron a este proyecto"), wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(44, _("Licencia"), _("Conoce tus derechos respecto a este software"), wx.ITEM_NORMAL)
        self.kframe_menubar.Append(wxglade_tmp_menu, _("Ayuda"))
        self.SetMenuBar(self.kframe_menubar)
        # Menu Bar end
        self.kframe_statusbar = self.CreateStatusBar(3, 0)

        # Tool Bar
        self.kframe_toolbar = wx.ToolBar(self, -1, style=wx.TB_HORIZONTAL | wx.TB_DOCKABLE | wx.TB_3DBUTTONS)
        self.SetToolBar(self.kframe_toolbar)
        self.kframe_toolbar.AddLabelTool(wx.NewId(), _("Nuevo"), wx.Bitmap("wx/images/document-new.png", wx.BITMAP_TYPE_ANY), wx.Bitmap("wx/images/document-new.png", wx.BITMAP_TYPE_ANY), wx.ITEM_NORMAL, _("Nuevo programa"), _("Crea un nuevo programa"))
        self.kframe_toolbar.AddLabelTool(wx.NewId(), _("Abrir"), wx.Bitmap("wx/images/document-open.png", wx.BITMAP_TYPE_ANY), wx.Bitmap("wx/images/document-open.png", wx.BITMAP_TYPE_ANY), wx.ITEM_NORMAL, _("Abrir programa"), _("Abre un archivo de programa"))
        self.kframe_toolbar.AddLabelTool(wx.NewId(), _("Guardar"), wx.Bitmap("wx/images/document-save.png", wx.BITMAP_TYPE_ANY), wx.Bitmap("wx/images/document-save.png", wx.BITMAP_TYPE_ANY), wx.ITEM_NORMAL, _("Guardar programa"), _("Guarda el programa a un archivo"))
        self.kframe_toolbar.AddSeparator()
        self.kframe_toolbar.AddLabelTool(wx.NewId(), _("Nuevo"), wx.Bitmap("wx/images/world-new.png", wx.BITMAP_TYPE_ANY), wx.Bitmap("wx/images/world-new.png", wx.BITMAP_TYPE_ANY), wx.ITEM_NORMAL, _("Nuevo mundo"), _("Crea un nuevo mundo donde todo es felicidad"))
        self.kframe_toolbar.AddLabelTool(wx.NewId(), _("Abrir"), wx.Bitmap("wx/images/world-open.png", wx.BITMAP_TYPE_ANY), wx.Bitmap("wx/images/world-open.png", wx.BITMAP_TYPE_ANY), wx.ITEM_NORMAL, _("Abre un mundo"), _("Entra a un mundo desconocido"))
        self.kframe_toolbar.AddLabelTool(wx.NewId(), _("Guardar"), wx.Bitmap("wx/images/world-save.png", wx.BITMAP_TYPE_ANY), wx.Bitmap("wx/images/world-save.png", wx.BITMAP_TYPE_ANY), wx.ITEM_NORMAL, _("Salva el mundo"), _(u"Salva el mundo de la destrucción"))
        self.kframe_toolbar.AddSeparator()
        self.kframe_toolbar.AddLabelTool(wx.NewId(), _("Regresar"), wx.Bitmap("wx/images/view-refresh.png", wx.BITMAP_TYPE_ANY), wx.Bitmap("wx/images/view-refresh.png", wx.BITMAP_TYPE_ANY), wx.ITEM_NORMAL, _("Regresar al estado original"), _("Regresa el mundo y el programa a su estado original"))
        self.kframe_toolbar.AddSeparator()
        self.kframe_toolbar.AddLabelTool(wx.NewId(), _("Compilar"), wx.Bitmap("wx/images/applications-system.png", wx.BITMAP_TYPE_ANY), wx.Bitmap("wx/images/applications-system.png", wx.BITMAP_TYPE_ANY), wx.ITEM_NORMAL, _("Compilar programa"), _("Compila el programa"))
        self.kframe_toolbar.AddLabelTool(wx.NewId(), _("Correr"), wx.Bitmap("wx/images/media-playback-start.png", wx.BITMAP_TYPE_ANY), wx.Bitmap("wx/images/media-playback-start.png", wx.BITMAP_TYPE_ANY), wx.ITEM_NORMAL, _("Ejecutar programa"), _("Ejecuta el programa en el mundo"))
        self.kframe_toolbar.AddLabelTool(wx.NewId(), _("Atras"), wx.Bitmap("wx/images/media-seek-backward.png", wx.BITMAP_TYPE_ANY), wx.Bitmap("wx/images/media-seek-backward.png", wx.BITMAP_TYPE_ANY), wx.ITEM_NORMAL, _("Retrocede"), _(u"Retroceder en le ejecución"))
        self.kframe_toolbar.AddLabelTool(wx.NewId(), _("Adelante"), wx.Bitmap("wx/images/media-seek-forward.png", wx.BITMAP_TYPE_ANY), wx.Bitmap("wx/images/media-seek-forward.png", wx.BITMAP_TYPE_ANY), wx.ITEM_NORMAL, _("Avanza"), _(u"Avanza en la ejecución"))
        # Tool Bar end
        self.kseparator = wx.SplitterWindow(self, -1, style=wx.SP_3D | wx.SP_BORDER)
        self.keditorzone = wx.SplitterWindow(self.kseparator, -1, style=wx.SP_3D | wx.SP_BORDER)
        self.kprogram = StyledTextCtrl(self.keditorzone, -1)
        self.notebook_1 = wx.Notebook(self.keditorzone, -1, style=0)
        self.notebook_1_pane_1 = wx.Panel(self.notebook_1, -1)
        self.notebook_1_pane_2 = wx.Panel(self.notebook_1, -1)
        self.notebook_1_pane_3 = wx.Panel(self.notebook_1, -1)
        self.panel_1 = wx.Panel(self.kseparator, -1)
        self.label_1 = wx.StaticText(self.panel_1, -1, _("Mochila: "))
        self.text_ctrl_1 = wx.TextCtrl(self.panel_1, -1, _("0"))
        self.label_2 = wx.StaticText(self.panel_1, -1, _(u"Retraso en la ejecución (ms): "))
        self.text_ctrl_2 = wx.TextCtrl(self.panel_1, -1, _("500"))
        self.karelscrolledwindow = wx.ScrolledWindow(self.panel_1, -1, style=wx.TAB_TRAVERSAL)
        self.mundo_karel = kworldpanel(self.karelscrolledwindow)

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_MENU, self.on_exit, id=1)
        self.Bind(wx.EVT_MENU, self.license_menu_selected, id=44)
        # end wxGlade

    def __set_properties(self):
        # begin wxGlade: KarelFrame.__set_properties
        self.SetTitle(_("Karel el Robot"))
        _icon = wx.EmptyIcon()
        _icon.CopyFromBitmap(wx.Bitmap("wx/images/logo/karel.png", wx.BITMAP_TYPE_ANY))
        self.SetIcon(_icon)
        self.SetSize((1038, 638))
        self.kframe_statusbar.SetStatusWidths([-1, 100, 120])
        # statusbar fields
        kframe_statusbar_fields = [_("Me llamo Karel"), _("Mochila: 0"), _("Estado: OK")]
        for i in range(len(kframe_statusbar_fields)):
            self.kframe_statusbar.SetStatusText(kframe_statusbar_fields[i], i)
        self.kframe_toolbar.SetToolBitmapSize((16, 16))
        self.kframe_toolbar.Realize()
        self.kprogram.SetForegroundColour(wx.Colour(3, 12, 87))
        self.kprogram.SetFont(wx.Font(11, wx.SCRIPT, wx.NORMAL, wx.NORMAL, 0, ""))
        self.label_1.SetToolTipString(_("Zumbadores en la mochila de Karel"))
        self.mundo_karel.SetMinSize((2040, 2040))
        self.karelscrolledwindow.SetScrollRate(10, 10)
        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: KarelFrame.__do_layout
        sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_1 = wx.FlexGridSizer(2, 1, 0, 0)
        sizer_5 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_3 = wx.FlexGridSizer(1, 4, 0, 0)
        self.notebook_1.AddPage(self.notebook_1_pane_1, _("Pila"))
        self.notebook_1.AddPage(self.notebook_1_pane_2, _("Consola de Errores"))
        self.notebook_1.AddPage(self.notebook_1_pane_3, _("Línea de comandos"))
        self.keditorzone.SplitHorizontally(self.kprogram, self.notebook_1, -200)
        sizer_3.Add(self.label_1, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_3.Add(self.text_ctrl_1, 0, 0, 0)
        sizer_3.Add(self.label_2, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_3.Add(self.text_ctrl_2, 0, 0, 0)
        sizer_1.Add(sizer_3, 1, wx.EXPAND, 0)
        sizer_5.Add(self.mundo_karel, 1, wx.EXPAND, 0)
        self.karelscrolledwindow.SetSizer(sizer_5)
        sizer_1.Add(self.karelscrolledwindow, 1, wx.EXPAND, 0)
        self.panel_1.SetSizer(sizer_1)
        sizer_1.AddGrowableRow(1)
        sizer_1.AddGrowableCol(0)
        self.kseparator.SplitVertically(self.keditorzone, self.panel_1, 439)
        sizer_2.Add(self.kseparator, 1, wx.EXPAND, 0)
        self.SetSizer(sizer_2)
        self.Layout()
        # end wxGlade
        #self.mundo_karel.inicializar()
        self.karelscrolledwindow.Scroll(0, 1900)

    def on_exit(self, event):  # wxGlade: KarelFrame.<event_handler>
        print "metodo 'on_exit' no implementado"
        event.Skip()

    def license_menu_selected(self, event):  # wxGlade: KarelFrame.<event_handler>
        #print "Event handler `license_menu_selected' not implemented"
        self.licencia_frame.Show(True)
        event.Skip()
コード例 #13
0
ファイル: TextCtrl.py プロジェクト: nigamv/datasciencetool
    def __init__(self, parent, style):

        StyledTextCtrl.__init__(self, parent, style)
        self.SetWrapMode(STC_WRAP_WORD)
コード例 #14
0
class TextEditorBase(wx.Panel):
    def __init__(self, parent):
        super(TextEditorBase, self).__init__(parent, style=0)
        self.textCtrl = StyledTextCtrl(self, -1)

        # Создание панели поиска и ее контроллера
        self._searchPanel = SearchReplacePanel(self)
        self._searchPanelController = SearchReplaceController(
            self._searchPanel, self)
        self._searchPanel.setController(self._searchPanelController)

        self._do_layout()

        self.__createCoders()
        self._helper = TextEditorHelper()
        self._bind()
        self._setDefaultSettings()

    def _bind(self):
        self.textCtrl.Bind(wx.EVT_KEY_DOWN, self.__onKeyDown)

    def _do_layout(self):
        mainSizer = wx.FlexGridSizer(rows=2, cols=0, vgap=0, hgap=0)
        mainSizer.AddGrowableRow(0)
        mainSizer.AddGrowableCol(0)

        mainSizer.Add(self.textCtrl, 0, wx.EXPAND, 0)
        mainSizer.Add(self._searchPanel, 0, wx.EXPAND, 0)
        self.SetSizer(mainSizer)

        self._searchPanel.Hide()
        self.Layout()

    def __createCoders(self):
        encoding = outwiker.core.system.getOS().inputEncoding
        self.mbcsEnc = codecs.getencoder(encoding)

    def __onKeyDown(self, event):
        key = event.GetKeyCode()

        if key == wx.WXK_ESCAPE:
            self._searchPanel.Close()

        event.Skip()

    def _setDefaultSettings(self):
        self.textCtrl.SetEndAtLastLine(False)
        self.textCtrl.StyleClearAll()
        self.textCtrl.SetWrapMode(wx.stc.STC_WRAP_WORD)
        self.textCtrl.SetWrapVisualFlags(wx.stc.STC_WRAPVISUALFLAG_END)
        self.textCtrl.SetTabWidth(4)
        self._setDefaultHotKeys()

    def _setDefaultHotKeys(self):
        self.textCtrl.CmdKeyClearAll()

        # Clear Cmd keys for Ubuntu
        for key in list(range(ord('A'),
                              ord('Z') + 1)) + list(
                                  range(ord('0'),
                                        ord('9') + 1)):
            self.textCtrl.CmdKeyClear(
                key, wx.stc.STC_SCMOD_ALT | wx.stc.STC_SCMOD_CTRL)
            self.textCtrl.CmdKeyClear(
                key, wx.stc.STC_SCMOD_SHIFT | wx.stc.STC_SCMOD_ALT
                | wx.stc.STC_SCMOD_CTRL)

        self.textCtrl.CmdKeyClear(wx.stc.STC_KEY_UP, wx.stc.STC_SCMOD_CTRL)
        self.textCtrl.CmdKeyClear(wx.stc.STC_KEY_DOWN, wx.stc.STC_SCMOD_CTRL)

        # Code from Wikidpad sources
        # Default mapping based on Scintilla's "KeyMap.cxx" file
        defaultHotKeys = (
            (wx.stc.STC_KEY_DOWN, wx.stc.STC_SCMOD_NORM,
             wx.stc.STC_CMD_LINEDOWN),
            (wx.stc.STC_KEY_UP, wx.stc.STC_SCMOD_NORM, wx.stc.STC_CMD_LINEUP),
            # (wx.stc.STC_KEY_DOWN,        wx.stc.STC_SCMOD_CTRL,     wx.stc.STC_CMD_LINESCROLLDOWN),
            # (wx.stc.STC_KEY_UP,          wx.stc.STC_SCMOD_CTRL,     wx.stc.STC_CMD_LINESCROLLUP),
            (wx.stc.STC_KEY_UP, wx.stc.STC_SCMOD_SHIFT,
             wx.stc.STC_CMD_LINEUPEXTEND),
            (wx.stc.STC_KEY_DOWN, wx.stc.STC_SCMOD_SHIFT,
             wx.stc.STC_CMD_LINEDOWNEXTEND),
            (ord('['), wx.stc.STC_SCMOD_CTRL, wx.stc.STC_CMD_PARAUP),
            (ord('['), wx.stc.STC_SCMOD_SHIFT | wx.stc.STC_SCMOD_CTRL,
             wx.stc.STC_CMD_PARAUPEXTEND),
            (ord(']'), wx.stc.STC_SCMOD_CTRL, wx.stc.STC_CMD_PARADOWN),
            (ord(']'), wx.stc.STC_SCMOD_SHIFT | wx.stc.STC_SCMOD_CTRL,
             wx.stc.STC_CMD_PARADOWNEXTEND),
            (wx.stc.STC_KEY_LEFT, wx.stc.STC_SCMOD_NORM,
             wx.stc.STC_CMD_CHARLEFT),
            (wx.stc.STC_KEY_LEFT, wx.stc.STC_SCMOD_SHIFT,
             wx.stc.STC_CMD_CHARLEFTEXTEND),
            # (wx.stc.STC_KEY_LEFT,        wx.stc.STC_SCMOD_CTRL,    wx.stc.STC_CMD_WORDLEFT),
            # (wx.stc.STC_KEY_LEFT,        wx.stc.STC_SCMOD_SHIFT | wx.stc.STC_SCMOD_CTRL,    wx.stc.STC_CMD_WORDLEFTEXTEND),
            (wx.stc.STC_KEY_RIGHT, wx.stc.STC_SCMOD_NORM,
             wx.stc.STC_CMD_CHARRIGHT),
            (wx.stc.STC_KEY_RIGHT, wx.stc.STC_SCMOD_SHIFT,
             wx.stc.STC_CMD_CHARRIGHTEXTEND),
            # (wx.stc.STC_KEY_RIGHT,        wx.stc.STC_SCMOD_CTRL,    wx.stc.STC_CMD_WORDRIGHT),
            # (wx.stc.STC_KEY_RIGHT,        wx.stc.STC_SCMOD_SHIFT | wx.stc.STC_SCMOD_CTRL,    wx.stc.STC_CMD_WORDRIGHTEXTEND),
            (ord('/'), wx.stc.STC_SCMOD_CTRL, wx.stc.STC_CMD_WORDPARTLEFT),
            (ord('/'), wx.stc.STC_SCMOD_SHIFT | wx.stc.STC_SCMOD_CTRL,
             wx.stc.STC_CMD_WORDPARTLEFTEXTEND),
            (ord('\\'), wx.stc.STC_SCMOD_CTRL, wx.stc.STC_CMD_WORDPARTRIGHT),
            (ord('\\'), wx.stc.STC_SCMOD_SHIFT | wx.stc.STC_SCMOD_CTRL,
             wx.stc.STC_CMD_WORDPARTRIGHTEXTEND),
            (wx.stc.STC_KEY_HOME, wx.stc.STC_SCMOD_NORM,
             wx.stc.STC_CMD_VCHOME),
            (wx.stc.STC_KEY_HOME, wx.stc.STC_SCMOD_SHIFT,
             wx.stc.STC_CMD_VCHOMEEXTEND),
            (wx.stc.STC_KEY_HOME, wx.stc.STC_SCMOD_CTRL,
             wx.stc.STC_CMD_DOCUMENTSTART),
            (wx.stc.STC_KEY_HOME,
             wx.stc.STC_SCMOD_SHIFT | wx.stc.STC_SCMOD_CTRL,
             wx.stc.STC_CMD_DOCUMENTSTARTEXTEND),
            (wx.stc.STC_KEY_HOME, wx.stc.STC_SCMOD_ALT,
             wx.stc.STC_CMD_HOMEDISPLAY),
            (wx.stc.STC_KEY_END, wx.stc.STC_SCMOD_NORM,
             wx.stc.STC_CMD_LINEEND),
            (wx.stc.STC_KEY_END, wx.stc.STC_SCMOD_SHIFT,
             wx.stc.STC_CMD_LINEENDEXTEND),
            (wx.stc.STC_KEY_END, wx.stc.STC_SCMOD_CTRL,
             wx.stc.STC_CMD_DOCUMENTEND),
            (wx.stc.STC_KEY_END,
             wx.stc.STC_SCMOD_SHIFT | wx.stc.STC_SCMOD_CTRL,
             wx.stc.STC_CMD_DOCUMENTENDEXTEND),
            (wx.stc.STC_KEY_END, wx.stc.STC_SCMOD_ALT,
             wx.stc.STC_CMD_LINEENDDISPLAY),
            (wx.stc.STC_KEY_PRIOR, wx.stc.STC_SCMOD_NORM,
             wx.stc.STC_CMD_PAGEUP),
            (wx.stc.STC_KEY_PRIOR, wx.stc.STC_SCMOD_SHIFT,
             wx.stc.STC_CMD_PAGEUPEXTEND),
            (wx.stc.STC_KEY_NEXT, wx.stc.STC_SCMOD_NORM,
             wx.stc.STC_CMD_PAGEDOWN),
            (wx.stc.STC_KEY_NEXT, wx.stc.STC_SCMOD_SHIFT,
             wx.stc.STC_CMD_PAGEDOWNEXTEND),
            (wx.stc.STC_KEY_DELETE, wx.stc.STC_SCMOD_NORM,
             wx.stc.STC_CMD_CLEAR),
            (wx.stc.STC_KEY_INSERT, wx.stc.STC_SCMOD_NORM,
             wx.stc.STC_CMD_EDITTOGGLEOVERTYPE),
            (wx.stc.STC_KEY_ESCAPE, wx.stc.STC_SCMOD_NORM,
             wx.stc.STC_CMD_CANCEL),
            (wx.stc.STC_KEY_BACK, wx.stc.STC_SCMOD_NORM,
             wx.stc.STC_CMD_DELETEBACK),
            (wx.stc.STC_KEY_BACK, wx.stc.STC_SCMOD_SHIFT,
             wx.stc.STC_CMD_DELETEBACK),
            (wx.stc.STC_KEY_BACK, wx.stc.STC_SCMOD_ALT, wx.stc.STC_CMD_UNDO),
            (ord('Z'), wx.stc.STC_SCMOD_CTRL, wx.stc.STC_CMD_UNDO),
            (ord('Y'), wx.stc.STC_SCMOD_CTRL, wx.stc.STC_CMD_REDO),
            (ord('A'), wx.stc.STC_SCMOD_CTRL, wx.stc.STC_CMD_SELECTALL),
            (wx.stc.STC_KEY_INSERT,
             wx.stc.STC_SCMOD_CTRL | wx.stc.STC_SCMOD_SHIFT,
             wx.stc.STC_CMD_COPY),
            (wx.stc.STC_KEY_INSERT, wx.stc.STC_SCMOD_SHIFT,
             wx.stc.STC_CMD_PASTE),
            (ord('C'), wx.stc.STC_SCMOD_CTRL, wx.stc.STC_CMD_COPY),
            (ord('X'), wx.stc.STC_SCMOD_CTRL, wx.stc.STC_CMD_CUT),
            (ord('V'), wx.stc.STC_SCMOD_CTRL, wx.stc.STC_CMD_PASTE),
            (wx.stc.STC_KEY_TAB, wx.stc.STC_SCMOD_NORM, wx.stc.STC_CMD_TAB),
            (wx.stc.STC_KEY_TAB, wx.stc.STC_SCMOD_SHIFT,
             wx.stc.STC_CMD_BACKTAB),
            (wx.stc.STC_KEY_RETURN, wx.stc.STC_SCMOD_NORM,
             wx.stc.STC_CMD_NEWLINE),
            (wx.stc.STC_KEY_RETURN, wx.stc.STC_SCMOD_SHIFT,
             wx.stc.STC_CMD_NEWLINE),
            (wx.stc.STC_KEY_ADD, wx.stc.STC_SCMOD_CTRL, wx.stc.STC_CMD_ZOOMIN),
            (wx.stc.STC_KEY_SUBTRACT, wx.stc.STC_SCMOD_CTRL,
             wx.stc.STC_CMD_ZOOMOUT),
            (wx.stc.STC_KEY_DOWN,
             wx.stc.STC_SCMOD_SHIFT | wx.stc.STC_SCMOD_ALT,
             wx.stc.STC_CMD_LINEDOWNRECTEXTEND),
            (wx.stc.STC_KEY_UP, wx.stc.STC_SCMOD_SHIFT | wx.stc.STC_SCMOD_ALT,
             wx.stc.STC_CMD_LINEUPRECTEXTEND),
            (wx.stc.STC_KEY_LEFT,
             wx.stc.STC_SCMOD_SHIFT | wx.stc.STC_SCMOD_ALT,
             wx.stc.STC_CMD_CHARLEFTRECTEXTEND),
            (wx.stc.STC_KEY_RIGHT,
             wx.stc.STC_SCMOD_SHIFT | wx.stc.STC_SCMOD_ALT,
             wx.stc.STC_CMD_CHARRIGHTRECTEXTEND),
            (wx.stc.STC_KEY_HOME,
             wx.stc.STC_SCMOD_SHIFT | wx.stc.STC_SCMOD_ALT,
             wx.stc.STC_CMD_VCHOMERECTEXTEND),
            (wx.stc.STC_KEY_END, wx.stc.STC_SCMOD_SHIFT | wx.stc.STC_SCMOD_ALT,
             wx.stc.STC_CMD_LINEENDRECTEXTEND),
            (wx.stc.STC_KEY_PRIOR,
             wx.stc.STC_SCMOD_SHIFT | wx.stc.STC_SCMOD_ALT,
             wx.stc.STC_CMD_PAGEUPRECTEXTEND),
            (wx.stc.STC_KEY_NEXT,
             wx.stc.STC_SCMOD_SHIFT | wx.stc.STC_SCMOD_ALT,
             wx.stc.STC_CMD_PAGEDOWNRECTEXTEND),

            # (wx.stc.STC_KEY_DELETE,    wx.stc.STC_SCMOD_SHIFT | wx.stc.STC_SCMOD_CTRL,    wx.stc.STC_CMD_DELLINERIGHT),
            # (wx.stc.STC_KEY_BACK,        wx.stc.STC_SCMOD_SHIFT | wx.stc.STC_SCMOD_CTRL,    wx.stc.STC_CMD_DELLINELEFT),
            # (wx.stc.STC_KEY_BACK,        wx.stc.STC_SCMOD_CTRL,     wx.stc.STC_CMD_DELWORDLEFT),
            # (wx.stc.STC_KEY_DELETE,     wx.stc.STC_SCMOD_CTRL,    wx.stc.STC_CMD_DELWORDRIGHT),
            # (wx.stc.STC_KEY_DIVIDE,    wx.stc.STC_SCMOD_CTRL,    wx.stc.STC_CMD_SETZOOM),
            #        (ord('L'),             wx.stc.STC_SCMOD_CTRL,    wx.stc.STC_CMD_LINECUT),
            #        (ord('L'),             wx.stc.STC_SCMOD_SHIFT | wx.stc.STC_SCMOD_CTRL,    wx.stc.STC_CMD_LINEDELETE),
            #        (ord('T'),             wx.stc.STC_SCMOD_SHIFT | wx.stc.STC_SCMOD_CTRL,    wx.stc.STC_CMD_LINECOPY),
            #        (ord('T'),             wx.stc.STC_SCMOD_CTRL,    wx.stc.STC_CMD_LINETRANSPOSE),
            #        (ord('D'),             wx.stc.STC_SCMOD_CTRL,    wx.stc.STC_CMD_SELECTIONDUPLICATE),
            #        (ord('U'),             wx.stc.STC_SCMOD_CTRL,    wx.stc.STC_CMD_LOWERCASE),
            #        (ord('U'),             wx.stc.STC_SCMOD_SHIFT | wx.stc.STC_SCMOD_CTRL,    wx.stc.STC_CMD_UPPERCASE),
        )

        [self.textCtrl.CmdKeyAssign(*key) for key in defaultHotKeys]

    @property
    def searchPanel(self):
        """
        Возвращает контроллер панели поиска
        """
        return self._searchPanelController

    def Print(self):
        selectedtext = self.textCtrl.GetSelectedText()
        text = self.textCtrl.GetText()

        printer = TextPrinter(self)
        printer.printout(text if len(selectedtext) == 0 else selectedtext)

    def getPosChar(self, posBytes):
        return len(self.textCtrl.GetTextRange(0, posBytes))

    def AddText(self, text):
        self.textCtrl.AddText(text)

    def replaceText(self, text):
        self.textCtrl.ReplaceSelection(text)

    def toddleLinePrefix(self, line, prefix):
        """
        If line with number "line" starts with prefix, prefix will be removed
        else prefix will be added.
        """
        assert line < self.GetLineCount()
        line_text = self.GetLine(line)
        if line_text.startswith(prefix):
            line_text = line_text[len(prefix):]
        else:
            line_text = prefix + line_text
        self.SetLine(line, line_text)

    def toddleSelectedLinesPrefix(self, prefix):
        """
        Apply toddleLinePrefix method to selected lines
        """
        self.BeginUndoAction()
        old_sel_start = self.GetSelectionStart()
        old_sel_end = self.GetSelectionEnd()

        first_line, last_line = self.GetSelectionLines()
        [
            self.toddleLinePrefix(n, prefix)
            for n in range(first_line, last_line + 1)
        ]

        if old_sel_start != old_sel_end:
            new_sel_start = self.GetLineStartPosition(first_line)
            new_sel_end = self.GetLineEndPosition(last_line)
        else:
            new_sel_start = new_sel_end = self.GetLineEndPosition(last_line)

        self.SetSelection(new_sel_start, new_sel_end)
        self.EndUndoAction()

    def turnText(self, lefttext, righttext):
        selText = self.textCtrl.GetSelectedText()
        newtext = lefttext + selText + righttext
        self.textCtrl.ReplaceSelection(newtext)

        currPos = self.GetSelectionEnd()
        if len(selText) == 0:
            """
            Если не оборачиваем текст, а делаем пустой тег, то поместим каретку до закрывающегося тега
            """
            newpos = currPos - len(righttext)
            self.SetSelection(newpos, newpos)
        else:
            self.SetSelection(currPos - len(selText) - len(righttext),
                              currPos - len(righttext))

    def escapeHtml(self):
        selText = self.textCtrl.GetSelectedText()
        text = html.escape(selText, quote=False)
        self.textCtrl.ReplaceSelection(text)

    def SetReadOnly(self, readonly):
        self.textCtrl.SetReadOnly(readonly)

    def GetReadOnly(self):
        return self.textCtrl.GetReadOnly()

    def GetText(self):
        return self.textCtrl.GetText()

    def SetText(self, text):
        self.textCtrl.SetText(text)

    def EmptyUndoBuffer(self):
        self.textCtrl.EmptyUndoBuffer()

    def GetSelectedText(self):
        return self.textCtrl.GetSelectedText()

    def GetCurrentLine(self):
        return self.textCtrl.GetCurrentLine()

    def ScrollToLine(self, line):
        self.textCtrl.ScrollToLine(line)

    def SetSelection(self, start, end):
        """
        start и end в символах, а не в байтах, в отличие от исходного
        StyledTextCtrl
        """
        startText = self.GetText()[:start]
        endText = self.GetText()[:end]

        firstByte = self._helper.calcByteLen(startText)
        endByte = self._helper.calcByteLen(endText)

        self.textCtrl.SetSelection(firstByte, endByte)

    def GotoPos(self, pos):
        pos_bytes = self._helper.calcBytePos(self.GetText(), pos)
        self.textCtrl.GotoPos(pos_bytes)

    def GetCurrentPosition(self):
        """
        Возвращает номер символа(а не байта), перед которых находится курсор
        """
        return self._calcCharPos(self.textCtrl.GetCurrentPos())

    def GetSelectionStart(self):
        """
        Возвращает позицию начала выбранной области в символах, а не в байтах
        """
        return self._calcCharPos(self.textCtrl.GetSelectionStart())

    def GetSelectionLines(self):
        """
        Return tuple (first selected line, last selected line)
        """
        start_bytes = self.textCtrl.GetSelectionStart()
        end_bytes = self.textCtrl.GetSelectionEnd()
        return (self.textCtrl.LineFromPosition(start_bytes),
                self.textCtrl.LineFromPosition(end_bytes))

    def GetSelectionEnd(self):
        """
        Возвращает позицию конца выбранной области в символах, а не в байтах
        """
        return self._calcCharPos(self.textCtrl.GetSelectionEnd())

    def SetFocus(self):
        self.textCtrl.SetFocus()
        self.textCtrl.SetSTCFocus(True)

    def GetLine(self, line):
        """
        Return line with the "line" number. \n included.
        """
        return self.textCtrl.GetLine(line)

    def SetLine(self, line, newline):
        """
        Replace line with the number "line" newline.
        Newline will be ended with "\n" else line will be joined with next line
        """
        linecount = self.GetLineCount()
        assert line < linecount

        line_start_bytes = self.textCtrl.PositionFromLine(line)
        line_end_bytes = self.textCtrl.PositionFromLine(line + 1)
        self.textCtrl.Replace(line_start_bytes, line_end_bytes, newline)

    def GetLineCount(self):
        return self.textCtrl.GetLineCount()

    def GetLineStartPosition(self, line):
        """
        Retrieve the position at the start of a line in symbols (not bytes)
        """
        return self._calcCharPos(self.textCtrl.PositionFromLine(line))

    def GetLineEndPosition(self, line):
        """
        Get the position after the last visible characters on a line
            in symbols (not bytes)
        """
        return self._calcCharPos(self.textCtrl.GetLineEndPosition(line))

    def MoveSelectedLinesUp(self):
        """
        Move the selected lines up one line,
        shifting the line above after the selection.
        """
        self.textCtrl.MoveSelectedLinesUp()

    def MoveSelectedLinesDown(self):
        """
        Move the selected lines down one line,
        shifting the line below before the selection.
        """
        self.textCtrl.MoveSelectedLinesDown()

    def LineDuplicate(self):
        """
        Duplicate the current line.
        """
        self.textCtrl.LineDuplicate()

    def LineDelete(self):
        """
        Delete the current line.
        """
        self.textCtrl.LineDelete()

    def BeginUndoAction(self):
        self.textCtrl.BeginUndoAction()

    def EndUndoAction(self):
        self.textCtrl.EndUndoAction()

    def JoinLines(self):
        """
        Join selected lines
        """
        first_line, last_line = self.GetSelectionLines()
        if first_line != last_line:
            last_line -= 1

        self.BeginUndoAction()

        for _ in range(first_line, last_line + 1):
            line = self.GetLine(first_line).replace(u'\r\n', u'\n')
            if line.endswith(u'\n'):
                newline = line[:-1]
                self.SetLine(first_line, newline)

        new_sel_pos = self.GetLineEndPosition(first_line)
        self.SetSelection(new_sel_pos, new_sel_pos)

        self.EndUndoAction()

    def DelWordLeft(self):
        self.textCtrl.DelWordLeft()

    def DelWordRight(self):
        self.textCtrl.DelWordRight()

    def DelLineLeft(self):
        """
        Delete back from the current position to the start of the line
        """
        self.textCtrl.DelLineLeft()

    def DelLineRight(self):
        """
        Delete forwards from the current position to the end of the line
        """
        self.textCtrl.DelLineRight()

    def WordLeft(self):
        self.textCtrl.WordLeft()

    def WordRight(self):
        self.textCtrl.WordRight()

    def WordLeftEnd(self):
        self.textCtrl.WordLeftEnd()

    def WordRightEnd(self):
        self.textCtrl.WordRightEnd()

    def WordLeftExtend(self):
        self.textCtrl.WordLeftExtend()

    def WordRightExtend(self):
        self.textCtrl.WordRightExtend()

    def GotoWordStart(self):
        self.WordRight()
        self.WordLeft()

    def GotoWordEnd(self):
        self.WordLeftEnd()
        self.WordRightEnd()

    def ScrollLineToCursor(self):
        maxlines = self.textCtrl.LinesOnScreen()
        line = self.GetCurrentLine()
        if line >= maxlines:
            delta = min(10, maxlines / 3)
            line -= delta
            if line < 0:
                line = 0
            self.ScrollToLine(line)

    def WordStartPosition(self, pos):
        pos_bytes = self._helper.calcBytePos(self.GetText(), pos)
        result_bytes = self.textCtrl.WordStartPosition(pos_bytes, True)
        return self.getPosChar(result_bytes)

    def WordEndPosition(self, pos):
        pos_bytes = self._helper.calcBytePos(self.GetText(), pos)
        result_bytes = self.textCtrl.WordEndPosition(pos_bytes, True)
        return self.getPosChar(result_bytes)

    def GetWord(self, pos):
        pos_bytes = self._helper.calcBytePos(self.GetText(), pos)
        word_start_bytes = self.textCtrl.WordStartPosition(pos_bytes, True)
        word_end_bytes = self.textCtrl.WordEndPosition(pos_bytes, True)
        word = self.textCtrl.GetTextRange(word_start_bytes, word_end_bytes)
        return word

    def _calcCharPos(self, pos_bytes):
        """
        Пересчет позиции в байтах в позицию в символах
        """
        text_left = self.textCtrl.GetTextRange(0, pos_bytes)
        currpos = len(text_left)
        return currpos

    def _getTextForParse(self):
        # Табуляция в редакторе считается за несколько символов
        return self.textCtrl.GetText().replace("\t", " ")
コード例 #15
0
 def current_file(self, *args):
     try:
         _, win = self.root.getNumWin()
         yield self.getfn(win), fixnewlines(StyledTextCtrl.GetText(win))
     except cancelled:
         pass
コード例 #16
0
ファイル: idn_customstc.py プロジェクト: IDNoise/NoiseIDE
    def __init__(self, parent, markerPanel, filePath = None):
        StyledTextCtrl.__init__(self, parent, style = wx.NO_BORDER)
        EditorFoldMixin.__init__(self)
        EditorLineMarginMixin.__init__(self)

        self.SetCodePage(wx.stc.STC_CP_UTF8)

        self.snippetCompleter = SnippetCompleter(self)
        self.snippetVarRegExp = re.compile(r"""\$[a-zA-Z0-9]*?\$""", re.VERBOSE | re.MULTILINE)
        self.snippetEditing = False

        self.findPanel = None
        self.markerPanel = markerPanel
        if self.markerPanel:
            self.markerPanel.Editor = self
            self.markerPanel.SetMarkerColor("selected_word",
                ColorSchema.codeEditor["selected_word_marker_color"])

        self.SetupLexer()
        self.filePath = None
        self.lastHighlightedWord = ""
        self.changed = False
        self.saved = True
        self.closed = False

        self.SetCaretWidth(ColorSchema.codeEditor["caret_size"])
        self.SetCaretForeground(ColorSchema.codeEditor["caret_color"])
        self.SetCaretLineBackground(ColorSchema.codeEditor["current_line_background"])
        self.SetCaretLineVisible(True)

        self.SetEndAtLastLine(False)
        self.SetScrollWidthTracking(True)
        self.SetScrollWidth(140)

        self.SetTabWidth(4)
        self.SetUseTabs(False)
        self.SetTabIndents(True)
        self.SetBackSpaceUnIndents(True)
        self.SetIndent(4)
        self.SetEOLMode(stc.STC_EOL_LF)

        self.SetEdgeColumn(140)
        self.SetEdgeMode(stc.STC_EDGE_LINE)

        self.SetMargins(5, 5)

        self.SetMarginType(2, stc.STC_MARGIN_SYMBOL)
        self.SetMarginSensitive(2, True)
        self.SetMarginWidth(2, 10)

        self.IndicatorSetStyle(0, stc.STC_INDIC_ROUNDBOX)
        self.IndicatorSetForeground(0, ColorSchema.codeEditor["highlighted_word"])

        self.SetVisiblePolicy(stc.STC_CARET_STRICT | stc.STC_CARET_EVEN, 0)
        self.SetYCaretPolicy(stc.STC_CARET_JUMPS | stc.STC_CARET_EVEN, 0)

        self.font = wx.Font(ColorSchema.codeEditor["font_size"],
            wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False,
            ColorSchema.codeEditor["font_name"])

        self.StyleSetBackground(stc.STC_STYLE_DEFAULT, ColorSchema.codeEditor["background"])
        self.StyleSetForeground(stc.STC_STYLE_DEFAULT, ColorSchema.codeEditor["foreground"])
        self.StyleSetFont(stc.STC_STYLE_DEFAULT, self.font)
        self.StyleClearAll()
        self.StyleSetBackground(stc.STC_STYLE_LINENUMBER, ColorSchema.codeEditor["line_number_area_background"])
        self.SetupLanguageStyles()
        self.StyleSetBackground(stc.STC_STYLE_BRACELIGHT, ColorSchema.codeEditor["brace_background"])
        self.StyleSetForeground(stc.STC_STYLE_BRACELIGHT, ColorSchema.codeEditor["brace_foreground"])
        self.StyleSetBackground(stc.STC_STYLE_BRACEBAD, ColorSchema.codeEditor["brace_bad_background"])
        self.StyleSetForeground(stc.STC_STYLE_BRACEBAD, ColorSchema.codeEditor["brace_bad_foreground"])
        self.SetSelBackground(True, ColorSchema.codeEditor["selection_background"])

        if hasattr(self, "lexer"):
            self.Bind(stc.EVT_STC_STYLENEEDED, self.OnStyleNeeded)
        self.Bind(stc.EVT_STC_UPDATEUI, self.HighlightBrackets)
        self.Bind(stc.EVT_STC_CHARADDED, self.OnCharAdded)
        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        self.Bind(stc.EVT_STC_UPDATEUI, self.OnUpdateSnippetCompleter)

        self.EnableLineNumbers()

        self.Bind(stc.EVT_STC_CHANGE , self.OnDocumentChanged)
        self.SetModEventMask(stc.STC_MOD_INSERTTEXT | stc.STC_MOD_DELETETEXT |
                             stc.STC_PERFORMED_USER | stc.STC_PERFORMED_UNDO |
                             stc.STC_PERFORMED_REDO)

        self.UpdateOptions()
        self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
        
        self.modifyCheckTimer = None
        if filePath:
            self.LoadFile(filePath)
            self.Bind(stc.EVT_STC_SAVEPOINTLEFT, self.OnSavePointLeft)
            self.Bind(stc.EVT_STC_SAVEPOINTREACHED, self.OnSavePointReached)
            self.StartModifyCheck()

        self.highlightTimer = wx.Timer(self, wx.ID_ANY)
        self.Bind(wx.EVT_TIMER, self.OnHighlightTimer, self.highlightTimer)
        self.highlightTimer.Start(400)
        
        self.editorMenu = core.MainFrame.editorMenu
        self.SetupEditorMenu()

        self.Bind(wx.EVT_RIGHT_UP, self.ShowPopupMenu)

        self.customTooltip = STCContextToolTip(self, self.OnRequestTooltipText)

        wx.CallAfter(self.OnInit)
コード例 #17
0
 def SetValue(self, value: str):
     StyledTextCtrl.SetValue(self, value.replace(os.linesep, "\n"))
     self.EmptyUndoBuffer()
コード例 #18
0
ファイル: McushDebugDlg.py プロジェクト: zephyract/mcush
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyFrame.__init__
        kwds["style"] = kwds.get(
            "style", 0
        ) | wx.CAPTION | wx.CLOSE_BOX | wx.MAXIMIZE_BOX | wx.MINIMIZE_BOX | wx.RESIZE_BORDER | wx.SYSTEM_MENU | wx.TAB_TRAVERSAL
        wx.Frame.__init__(self, *args, **kwds)
        self.SetSize((990, 681))
        self.bitmap_tip = wx.StaticBitmap(
            self, wx.ID_ANY,
            wx.Bitmap("img/connect_controller.png", wx.BITMAP_TYPE_ANY))
        self.button_exit = wx.Button(self, wx.ID_ANY, _("Exit"))
        self.label_port = wx.StaticText(self, wx.ID_ANY, _("Port"))
        self.combo_box_port = wx.ComboBox(self,
                                          wx.ID_ANY,
                                          choices=[],
                                          style=wx.CB_DROPDOWN | wx.CB_SORT)
        self.button_test_port = wx.Button(self, wx.ID_ANY, _("Test"))
        self.button_stop = wx.Button(self, wx.ID_ANY, _("Stop"))
        self.notebook_1 = wx.Notebook(self, wx.ID_ANY, style=0)
        self.notebook_1_pane_scripts = wx.Panel(self.notebook_1, wx.ID_ANY)
        self.text_ctrl_script = StyledTextCtrl(self.notebook_1_pane_scripts,
                                               wx.ID_ANY)
        self.button_run = wx.Button(self.notebook_1_pane_scripts, wx.ID_ANY,
                                    _("Run"))
        self.button_reset = wx.Button(self.notebook_1_pane_scripts, wx.ID_ANY,
                                      _("Reset"))
        self.button_reboot = wx.Button(self.notebook_1_pane_scripts, wx.ID_ANY,
                                       _("Reboot"))
        self.button_load_example = wx.Button(self.notebook_1_pane_scripts,
                                             wx.ID_ANY, _("Load example..."))
        self.button_load_file = wx.Button(self.notebook_1_pane_scripts,
                                          wx.ID_ANY, _("Load file..."))
        self.button_save_as = wx.Button(self.notebook_1_pane_scripts,
                                        wx.ID_ANY, _("Save as..."))
        self.notebook_1_pane_spiffs = wx.Panel(self.notebook_1, wx.ID_ANY)
        self.tree_ctrl_fs = wx.TreeCtrl(self.notebook_1_pane_spiffs,
                                        wx.ID_ANY,
                                        style=wx.BORDER_SUNKEN
                                        | wx.TR_HAS_BUTTONS | wx.TR_HIDE_ROOT
                                        | wx.TR_NO_BUTTONS | wx.TR_SINGLE)
        self.button_query = wx.Button(self.notebook_1_pane_spiffs, wx.ID_ANY,
                                      _("Query"))
        self.button_remove = wx.Button(self.notebook_1_pane_spiffs, wx.ID_ANY,
                                       _("Remove"))
        self.button_put_file = wx.Button(self.notebook_1_pane_spiffs,
                                         wx.ID_ANY, _("Put file"))
        self.button_get_file = wx.Button(self.notebook_1_pane_spiffs,
                                         wx.ID_ANY, _("Get file"))
        self.button_rename = wx.Button(self.notebook_1_pane_spiffs, wx.ID_ANY,
                                       _("Rename"))
        self.button_view = wx.Button(self.notebook_1_pane_spiffs, wx.ID_ANY,
                                     _("View"))
        self.notebook_1_pane_i2c = wx.Panel(self.notebook_1, wx.ID_ANY)
        self.text_ctrl_i2c_data = wx.TextCtrl(
            self.notebook_1_pane_i2c,
            wx.ID_ANY,
            "",
            style=wx.HSCROLL | wx.TE_MULTILINE | wx.TE_PROCESS_ENTER)
        self.text_ctrl_i2c_address = wx.TextCtrl(self.notebook_1_pane_i2c,
                                                 wx.ID_ANY,
                                                 _("0x50"),
                                                 style=wx.TE_CENTRE)
        self.button_i2c_scan = wx.Button(self.notebook_1_pane_i2c, wx.ID_ANY,
                                         _("Scan"))
        self.text_ctrl_i2c_pin_sda = wx.TextCtrl(self.notebook_1_pane_i2c,
                                                 wx.ID_ANY,
                                                 _("0.0"),
                                                 style=wx.TE_CENTRE)
        self.text_ctrl_i2c_pin_scl = wx.TextCtrl(self.notebook_1_pane_i2c,
                                                 wx.ID_ANY,
                                                 _("0.1"),
                                                 style=wx.TE_CENTRE)
        self.text_ctrl_i2c_delay_us = wx.TextCtrl(self.notebook_1_pane_i2c,
                                                  wx.ID_ANY,
                                                  _("10"),
                                                  style=wx.TE_CENTRE)
        self.text_ctrl_i2c_reg_from = wx.TextCtrl(self.notebook_1_pane_i2c,
                                                  wx.ID_ANY,
                                                  _("0x00"),
                                                  style=wx.TE_CENTRE)
        self.text_ctrl_i2c_reg_to = wx.TextCtrl(self.notebook_1_pane_i2c,
                                                wx.ID_ANY,
                                                _("0xFF"),
                                                style=wx.TE_CENTRE)
        self.button_i2c_read = wx.Button(self.notebook_1_pane_i2c, wx.ID_ANY,
                                         _("Read data"))
        self.button_i2c_write = wx.Button(self.notebook_1_pane_i2c, wx.ID_ANY,
                                          _("Write data"))
        self.button_i2c_load_data = wx.Button(self.notebook_1_pane_i2c,
                                              wx.ID_ANY, _("Load..."))
        self.button_i2c_save_data = wx.Button(self.notebook_1_pane_i2c,
                                              wx.ID_ANY, _("Save..."))
        self.bitmap_info = wx.StaticBitmap(
            self, wx.ID_ANY, wx.Bitmap("img/message.png", wx.BITMAP_TYPE_ANY))
        self.label_info = wx.StaticText(self, wx.ID_ANY, "")

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_BUTTON, self.OnExit, self.button_exit)
        self.Bind(wx.EVT_BUTTON, self.OnTestPort, self.button_test_port)
        self.Bind(wx.EVT_BUTTON, self.OnStop, self.button_stop)
        self.Bind(wx.EVT_BUTTON, self.OnRun, self.button_run)
        self.Bind(wx.EVT_BUTTON, self.OnReset, self.button_reset)
        self.Bind(wx.EVT_BUTTON, self.OnReboot, self.button_reboot)
        self.Bind(wx.EVT_BUTTON, self.OnLoadExample, self.button_load_example)
        self.Bind(wx.EVT_BUTTON, self.OnLoadFile, self.button_load_file)
        self.Bind(wx.EVT_BUTTON, self.OnSaveAs, self.button_save_as)
        self.Bind(wx.EVT_TREE_BEGIN_DRAG, self.OnFileBeginDrag,
                  self.tree_ctrl_fs)
        self.Bind(wx.EVT_TREE_END_DRAG, self.OnFileEndDrag, self.tree_ctrl_fs)
        self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelectFileItem,
                  self.tree_ctrl_fs)
        self.Bind(wx.EVT_BUTTON, self.OnQuery, self.button_query)
        self.Bind(wx.EVT_BUTTON, self.OnRemove, self.button_remove)
        self.Bind(wx.EVT_BUTTON, self.OnPutFile, self.button_put_file)
        self.Bind(wx.EVT_BUTTON, self.OnGetFile, self.button_get_file)
        self.Bind(wx.EVT_BUTTON, self.OnRename, self.button_rename)
        self.Bind(wx.EVT_BUTTON, self.OnView, self.button_view)
        self.Bind(wx.EVT_BUTTON, self.OnI2cScan, self.button_i2c_scan)
        self.Bind(wx.EVT_BUTTON, self.OnI2cRead, self.button_i2c_read)
        self.Bind(wx.EVT_BUTTON, self.OnI2cWrite, self.button_i2c_write)
        self.Bind(wx.EVT_BUTTON, self.OnI2cLoad, self.button_i2c_load_data)
        self.Bind(wx.EVT_BUTTON, self.OnI2cSave, self.button_i2c_save_data)
        self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnSwitchPage,
                  self.notebook_1)
コード例 #19
0
    def current_file_with_includes(self,
                                   path,
                                   subdirs,
                                   include,
                                   exclude,
                                   ignore_dotted=0):
        try:
            _, win = self.root.getNumWin()
            t = fixnewlines(StyledTextCtrl.GetText(win))
            yield self.getfn(win), t

            typ, lst = find_imports(t)
            if typ == C:
                for pth in lst:
                    a = os.path.join(win.dirname, pth)
                    if os.path.isfile(a):
                        if namematches(a.split('/')[-1], include, exclude):
                            try:
                                x = self.root.GetPositionAbsolute(a)
                                if x != -1:
                                    t = StyledTextCtrl.GetText(
                                        self.root.GetPage(x).GetWindow1())
                                else:
                                    t = open(a, 'rb').read()
                                t = fixnewlines(t)
                            except:
                                continue
                    yield a, t
            elif typ == PY:
                tried = {}
                extns = [
                    '.py', '.pyw', os.path.sep + '__init__.py',
                    os.path.sep + '__init__.pyw'
                ]
                for pth in lst:
                    found = 0
                    pth = pth.split('.')
                    while not found and pth:
                        for extn in extns:
                            a = win.dirname + os.path.sep + os.path.sep.join(
                                pth) + extn
                            if a in tried:
                                found = 1
                                break
                            tried[a] = None
                            if os.path.isfile(a):
                                if namematches(
                                        a.split('/')[-1], include, exclude):
                                    try:
                                        x = self.root.GetPositionAbsolute(a)
                                        if x != -1:
                                            t = StyledTextCtrl.GetText(
                                                self.root.GetPage(
                                                    x).GetWindow1())
                                        else:
                                            t = open(a, 'rb').read()
                                        t = fixnewlines(t)
                                        found = 1
                                        tried[a] = 1
                                        break
                                    except Exception, why:
                                        continue
                        if not found and pth:
                            _ = pth.pop()
                    if found and pth and tried[a]:
                        yield a, t
                        tried[a] = None
        except cancelled:
            pass