示例#1
0
    def build(self):
        self.theme_cls.theme_style = "Dark"

        boxlayout = BoxLayout()
        code = ''
        with open(self.path_to_kv_file, "r") as kv_file:
            code = kv_file.read()
        codeinput = CodeInput(
            text=code,
            lexer=KivyLexer(),
            style_name="native",
            size_hint_x=.6,
        )
        codeinput.bind(text=self.update_kv_file)
        hot_reload_viewer = HotReloadViewer(
            size_hint_x=.4,
            path=self.path_to_kv_file,
            errors=True,
            errors_text_color=(1, 1, 0, 1),
            errors_background_color=self.theme_cls.bg_dark,
        )
        boxlayout.add_widget(codeinput)
        boxlayout.add_widget(hot_reload_viewer)

        return boxlayout
    def build(self):
        b = BoxLayout(orientation='vertical')
        languages = Spinner(text='language',
                            values=sorted([
                                'KvLexer',
                            ] + lexers.LEXERS.keys()))

        languages.bind(text=self.change_lang)

        menu = BoxLayout(size_hint_y=None, height='30pt')
        fnt_size = Spinner(text='12', values=map(str, range(5, 40)))
        fnt_size.bind(text=self._update_size)
        fnt_name = Spinner(text='DroidSansMono',
                           option_cls=Fnt_SpinnerOption,
                           values=sorted(map(str, fonts.get_fonts())))
        fnt_name.bind(text=self._update_font)
        mnu_file = Spinner(text='File',
                           values=('Open', 'SaveAs', 'Save', 'Close'))
        mnu_file.bind(text=self._file_menu_selected)

        menu.add_widget(mnu_file)
        menu.add_widget(fnt_size)
        menu.add_widget(fnt_name)
        menu.add_widget(languages)
        b.add_widget(menu)

        self.codeinput = CodeInput(lexer=KivyLexer(),
                                   font_name='data/fonts/DroidSansMono.ttf',
                                   font_size=12,
                                   text=example_text)

        b.add_widget(self.codeinput)

        return b
示例#3
0
    def get_response(self, prompt, btn):
        response = openai.Completion.create(
            engine="curie-instruct-beta",
            prompt=prompt,
            temperature=0.8,
            max_tokens=250,
            top_p=1,
            best_of=5,
            frequency_penalty=0,
            presence_penalty=0,
            stop=["###"] 
            )

        new_kv = fix_indent(response.choices[0].text)
        print(new_kv)
        result_layout = self.app_root.ids.result_layout
        code_input = self.app_root.ids.code_input
        code_input.lexer = KivyLexer()
        
        result_layout.clear_widgets()
        try:
            code_input.text = new_kv+"\n"
            new_widget = Builder.load_string(new_kv)
            result_layout.add_widget(new_widget)
        except Exception as e:
            print(e) 
            info_label = InfoLabel()
            info_label.text = str(e)
            info_label._color = "Red"
            info_label.font_style = "H5"
            result_layout.add_widget(info_label)
        btn.disabled = False
示例#4
0
    def add_widget(self, widget, name, tab_type='code'):
        if tab_type == 'code':
            if os.path.splitext(widget.filename)[1] == '.kv':
                widget.code_input.lexer = KivyLexer()
            Clock.schedule_once(lambda dt: self.open_file(widget),
                                1)  # open the file

        screen = CodeScreen(name=name)
        screen.add_widget(widget, tab_type=tab_type)
        super(CodeScreenManager, self).add_widget(screen)
示例#5
0
def get_lexer_for_file(filename):
    ext = os.path.splitext(filename)[1]
    try:
        lexer = lexers.get_lexer_for_filename(filename)
    except lexers.ClassNotFound:
        if ext == '.kv':
            lexer = KivyLexer()
        else:
            lexer = lexers.TextLexer()
    # print('found {} for {}'.format(lexer, filename))
    return lexer
示例#6
0
        def build(self):
            return CodeInput(lexer=KivyLexer(),
                             font_size=12,
                             text='''
#:kivy 1.0

<YourWidget>:
    canvas:
        Color:
            rgb: .5, .5, .5
        Rectangle:
            pos: self.pos
            size: self.size''')
示例#7
0
        def build(self):
            return CodeInput(lexer=KivyLexer(),
                font_name='data/fonts/DroidSansMono.ttf', font_size=12,
                text='''
#:kivy 1.0

<YourWidget>:
    canvas:
        Color:
            rgb: .5, .5, .5
        Rectangle:
            pos: self.pos
            size: self.size''')
示例#8
0
    def build(self):
        b = BoxLayout(orientation='vertical')
        languages = Spinner(
            text='language',
            values=sorted(['KvLexer', ] + list(lexers.LEXERS.keys())))

        languages.bind(text=self.change_lang)

        menu = BoxLayout(
            size_hint_y=None,
            height='30pt')
        fnt_size = Spinner(
            text='12',
            values=list(map(str, list(range(5, 40)))))
        fnt_size.bind(text=self._update_size)

        fonts = [
            file for file in LabelBase._font_dirs_files
            if file.endswith('.ttf')]

        fnt_name = Spinner(
            text='RobotoMono',
            option_cls=Fnt_SpinnerOption,
            values=fonts)
        fnt_name.bind(text=self._update_font)
        mnu_file = Spinner(
            text='File',
            values=('Open', 'SaveAs', 'Save', 'Close'))
        mnu_file.bind(text=self._file_menu_selected)
        key_bindings = Spinner(
            text='Key bindings',
            values=('Default key bindings', 'Emacs key bindings'))
        key_bindings.bind(text=self._bindings_selected)

        menu.add_widget(mnu_file)
        menu.add_widget(fnt_size)
        menu.add_widget(fnt_name)
        menu.add_widget(languages)
        menu.add_widget(key_bindings)
        b.add_widget(menu)

        self.codeinput = CodeInputWithBindings(
            lexer=KivyLexer(),
            font_size=12,
            text=example_text,
            key_bindings='default',
        )

        b.add_widget(self.codeinput)

        return b
示例#9
0
    def change_lexer(self, mimetype=None):
        """Change the lexer of this :py:class:`.Editor`.
        
        The lexer is what takes care of recognizing the keywords, variable names, etc.
        
        :param mimetype: The mimetype for which a lexer should be found. The lexer is \
        changed to that found with this mimetype.
        """
        if mimetype is not None:

            try:
                # If the mimetype is 'text/plain' and the extension
                # of the file is '.kv', then a kivylexer should be used.
                if mimetype == 'text/plain' and os.path.splitext(
                        self._name)[1] == '.kv':
                    self.lexer = KivyLexer()
                else:
                    self.lexer = get_lexer_for_mimetype(mimetype)

            except ClassNotFound as err:
                print(err, 'Unsopported type {}'.format(mimetype), sep='\n')
                self.lexer = lexers.TextLexer()
            finally:
                return self.lexer.name

        elif self._name is not None:
            # If the mimetype is 'text/plain' and the extension
            # of the file is '.kv', then a kivylexer should be used.

            if os.path.splitext(self._name)[1] == '.kv':
                self.lexer = KivyLexer()
            else:
                self.lexer = lexers.TextLexer()
        else:

            self.lexer = lexers.TextLexer()

        return self.lexer.name
示例#10
0
文件: codeViewer.py 项目: pl77/cypher
    def build_code(self, path):
        filename = path.split('/')[-1]
        monokai = [.152, .156, .133, 1]  # monokai background color

        if filename.split('.')[-1] == 'kv':
            l = KivyLexer()
        else:
            l = get_lexer_for_filename(filename)

        code = open(path, 'r').read()

        return CodeInput(lexer=l,
                         text=code,
                         style_name='monokai',
                         background_color=monokai,
                         disabled=False)
示例#11
0
def get_code_lexer_for_filename(file_name):
    """
    Get a lexer that can highlight the contents of a file type.

    Select a pygments lexer with the utility function get_lexer_for_filename.
    If no such lexer exists, check if we opened a KivyLang file (.kv), Otherwise
    return a dummy lexer without highlighting.

    :param file_name: The name of the file to highlight.
    :return: An adequate lexer for the file, or a plain lexer if there are none
    available.
    """
    try:
        lexer = get_lexer_for_filename(file_name)
    except ClassNotFound:
        if file_name.split('.')[-1] == "kv":
            lexer = KivyLexer()
        else:
            lexer = TextLexer()
    return lexer
示例#12
0
class CodeEditor(CodeInput):
    lexer = KivyLexer()

    def keyboard_on_key_down(self, window, keycode, text, modifiers):
        self.readonly = False
        if len(modifiers) and text:

            if modifiers[0] == "ctrl" and ord(text) in [270, 269, 43, 45, 61]:
                self.readonly = True
                if ord(text) in [270, 61, 43]:
                    self.font_size += 1
                    self.cursor = (self.cursor[0] - 1, 0)
                    return
                elif ord(text) in [269, 45]:
                    self.font_size -= 1
                    self.cursor = (self.cursor[0] - 1, 0)
                    return

        return super(CodeEditor,
                     self).keyboard_on_key_down(window, keycode, text,
                                                modifiers)
示例#13
0
 def change_lexer(self, widget):
     """Manage the on_realese event of a button added to :py:attr:`.HighlightMenu.layout`.
     Change the lexer of the current_tab's editor of :py:attr:`.editor_container`.
     
     It also changes the :py:attr:`footer.footer.FooterSpinner.display_state`
     of the parent (to "hidden").
     
     :param widget: Widget is a button that was added to :py:attr:`.HighlightMenu.layout`.       
     """
     
     if widget.text == 'Kivy':
         lexer = KivyLexer()
     else:
         lexer = get_lexer_by_name(self.lexers[widget.text])
     
     self.parent.text = widget.text
             
     self.parent.display_state = self.parent.states[self.parent.state_index]
     
     if self.editor_container:
         self.editor_container.current_tab.content.editor.lexer = lexer
示例#14
0
def setup(app):
    app.add_lexer("kv", KivyLexer())
示例#15
0
 def change_lang(self, instance, z):
     if z == 'KvLexer':
         lx = KivyLexer()
     else:
         lx = lexers.get_lexer_by_name(lexers.LEXERS[z][2][0])
     self.codeinput.lexer = lx
示例#16
0
content = BoxLayout(orientation="vertical")  # in vertical stack
topbar = GridLayout(
    cols=2, size_hint=(1, 0.2)
)  # create a grid layout (with 2 columns) topbar/menu bar for dismissing popup etc.
btn2 = Button(
    text='Close Me!', size_hint_x=0.2
)  # dismiss button with custom text and spacing (size_hint is the fraction of the x axis the widget occupies)
topbar.add_widget(Label(
    text="How does a button and slider work?"))  # adds label (text) for title
topbar.add_widget(
    btn2
)  # adds dismiss button (order matters in boxlayout and gridlayout -- typically left to right, top down)
content.add_widget(topbar)  # adds topbar to popup
# code input widget to explain the code of slider and button
content.add_widget(
    CodeInput(lexer=KivyLexer(),
              text="""# kivy 1.10.1
# Using kv language, it's easy to read what's going on
# in the code. The layout is clear and legible.
# The behavior (root.command()) associated with
# actions calls on functions in the Python code.

# Full arrangement
<Layout>
	orientation: 'horizontal' # is horizontally stacked
	padding: 20 # padded 20% per widget for aesthetic reasons

	# the "Hello World" button and its properties and behavior
	Button:
		id: hw
		text: 'Hello World! (click me!)'
示例#17
0
class EditorScreen(Screen):
    row_num = ObjectProperty(None)
    col_num = ObjectProperty(None)
    text_input_area = ObjectProperty(None)
    file_name_input = ObjectProperty(None)
    language_mode_chooser = ObjectProperty(None)
    dashboard = ObjectProperty(None)
    toggle_btn_file_chooser = ObjectProperty(None)
    lexer_dict = DictProperty({
        "Plain text": lexers.get_lexer_by_name("text"),
        "C": lexers.CLexer(),
        "C++": lexers.CppLexer(),
        "CSS": lexers.CssLexer(),
        "HTML": lexers.HtmlLexer(),
        "JavaScript": lexers.JavascriptLexer(),
        "Kivy": KivyLexer(),
        "Rust": lexers.RustLexer(),
        "Python": lexers.PythonLexer(),
        "Python3": lexers.Python3Lexer(),
        "SASS": lexers.SassLexer(),
        "SCSS": lexers.ScssLexer(),
    })

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.set_syntax_highlight(tuple(self.lexer_dict.keys())[0])
        self.text_input_area.bind(cursor=self.on_cursor)
        self.language_mode_chooser.bind(text=self.on_lang_mode_chooser)
        self.file_path = ""
        self.progress_popup = None
        self.gen_to_progress = None

    def on_cursor(self, instance, cursor):
        # cursor[0]: current cursor postition(col)
        # cursor[1]: current cursor postition(row)
        self.col_num.text = str(cursor[0])
        self.row_num.text = str(cursor[1] + 1)

    def on_lang_mode_chooser(self, instance, text):
        self.set_syntax_highlight(text)

    def set_syntax_highlight(self, language):
        self.text_input_area.lexer = self.lexer_dict[language]

    def toggle_file_chooser_show(self):
        if self.toggle_btn_file_chooser.state == "normal":
            # self.dashboard_file_chooser = None
            self.dashboard.clear_widgets()
            self.dashboard.size_hint_x = None
            self.dashboard.width = 0
        elif self.toggle_btn_file_chooser.state == "down":
            self.dashboard.add_widget(
                DashBoardFileChooserView(file_chooser_user=self))
            self.dashboard.size_hint_x = 0.4

    def clear_text(self):
        self.text_input_area.text = ""

    def save_file(self, file_path):
        with open(file_path, "w") as f:
            f.write(self.text_input_area.text)
        self.file_path = file_path
        return True

    def show_save(self):
        def close():
            if self.toggle_btn_file_chooser.state == "down":
                self.toggle_btn_file_chooser.state = "normal"
                self.toggle_file_chooser_show()
                # self.toggle_btn_file_chooser.state = "down"
                # self.toggle_file_chooser_show()

        popup = SaveFilePopup(self.save_file, close)
        popup.open()

    def open_file_yield_progress(self, file_path, *args):
        progress_max = 0
        progress_count = 0
        try:
            with open(file_path, "r") as f:
                progress_max = sum(1 for line in open(file_path, "r")) + 1
                yield progress_count, progress_max
                text = ""
                for line in f:
                    text += line
                    progress_count += 1
                    yield progress_count, progress_max
                self.text_input_area.text = text
                self.file_name_input.text = Path(file_path).parts[-1]
                self.file_path = file_path
                progress_count += 1
                yield progress_count, progress_max
        except PermissionError:
            self.text_input_area.text = (":( Permisson denined: {}".format(
                Path(file_path).parts[-1]))
            yield progress_max, progress_max
        except UnicodeDecodeError:
            self.text_input_area.text = (":( Unicode decode error: {}".format(
                Path(file_path).parts[-1]))
            yield progress_max, progress_max

    def open_file(self, file_path):
        try:
            with open(file_path, "r") as f:
                text = ""
                for line in f:
                    text += line
                self.text_input_area.text = text
                self.file_name_input.text = Path(file_path).parts[-1]
                self.file_path = file_path
        except PermissionError:
            self.text_input_area.text = (":( Permisson denined: {}".format(
                Path(file_path).parts[-1]))
        except UnicodeDecodeError:
            self.text_input_area.text = (":( Unicode decode error: {}".format(
                Path(file_path).parts[-1]))
        else:
            return True

    def update_progress_popup(self, dt):
        try:
            value, max_value = next(self.gen_to_progress)
            self.progress_popup.set_progress_max(max_value)
            self.progress_popup.set_progress_value(value)
            # --- This code For speeding up to opening file.
            if dt == 0:
                dt = -1
            else:
                dt = 0
            # ---
            Clock.schedule_once(self.update_progress_popup, dt)
        except StopIteration:
            Clock.unschedule(self.show_progress_schedule)
            self.progress_popup.dismiss()

    def open_file_with_progress(self, file_path):
        self.progress_popup = ProgressPopup()
        self.gen_to_progress = self.open_file_yield_progress(file_path)
        self.show_progress_schedule = Clock.schedule_interval(
            self.update_progress_popup, 0)

    def show_open(self):
        open_file_popup = OpenFilePopup(self.open_file_with_progress)
        open_file_popup.open()

    def show_license(self):
        save_file_popup = LicensePopup()
        save_file_popup.open()