Ejemplo n.º 1
0
    def __init__(self):
        gtk.VBox.__init__(self)

        self._b = gtksourceview.Buffer()
        style_scheme = gtksourceview.style_scheme_manager_get_default(
        ).get_scheme('classic')
        if style_scheme:
            self._b.set_style_scheme(style_scheme)
        self._b.set_language(
            gtksourceview.language_manager_get_default().get_language("cpp"))
        self._b.set_highlight_syntax(True)

        #self._b.connect('mark-set', move_cursor_cb, view)
        #self._b.connect('changed', update_cursor_position, view)

        self._v = gtksourceview.View(self._b)
        self._v.set_show_line_numbers(True)
        #self._v.set_show_line_marks(action.get_active())
        #self._v.set_show_right_margin(action.get_active())
        #self._v.set_auto_indent(action.get_active())
        #self._v.set_insert_spaces_instead_of_tabs(action.get_active())
        #self._v.set_tab_width(action.get_current_value())
        #self._v.connect('button-press-event', button_press_cb)

        sw = gtk.ScrolledWindow()
        sw.set_shadow_type(gtk.SHADOW_IN)
        self.pack_start(sw, True, True, 0)
        sw.add(self._v)

        # setup view
        font_desc = pango.FontDescription('monospace')
        if font_desc:
            self._v.modify_font(font_desc)
Ejemplo n.º 2
0
 def set_code_mode(self, codemode):
     if not self.gtksourceview_mode:
         return
     # Non-code is the default
     if not codemode:
         return
     self.input_view.modify_font(pango.FontDescription("monospace"))
     fs = Filesystem.getInstance()
     try:
         mimetype = fs.get_file_sync(self.__filename).mimetype
     except FileStatError as e:
         mimetype = None
     target_lang = None        
     if gtksourceview2_avail:
         import gtksourceview2
         langman = gtksourceview2.language_manager_get_default() 
         for language_id in langman.get_language_ids():
             language = langman.get_language(language_id)
             for langmime in language.get_mime_types():
                 if mimetype == langmime:
                     target_lang = language
                     break
             if target_lang:
                 break
         self.input.set_highlight_syntax(True)
     else:
         import gtksourceview
         target_lang = gtksourceview.SourceLanguagesManager().get_language_from_mime_type(mimetype)
         self.input.set_highlight(True)
     if target_lang:
         self.input.set_language(target_lang)
Ejemplo n.º 3
0
 def __init__(self, win, editor=None):
     gtksourceview2.View.__init__(self)
     gtk.widget_push_composite_child()
     self.editor = editor
     self.buffer = gtksourceview2.Buffer()
     self.set_buffer(self.buffer)
     self.set_show_line_marks(True)
     width, height = gtk.icon_size_lookup(gtk.ICON_SIZE_MENU)
     pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True,
                             8, width, height)
     pixbuf.fill(0)
     self.set_mark_category_pixbuf('sql-start', pixbuf)
     self.set_mark_category_pixbuf('sql-end', pixbuf)
     lang_manager = gtksourceview2.language_manager_get_default()
     self.buffer.set_language(lang_manager.get_language('sql'))
     self.app = win.app
     self._sig_app_config_changed = self.app.config.connect(
         'changed', self.on_config_changed)
     self.update_textview_options()
     self._buffer_changed_cb = None
     self.buffer.connect('end-user-action', self.on_buffer_changed)
     self.buffer.connect('mark-set', self.on_mark_set)
     if self.editor is not None:
         self.editor.connect('connection-changed', lambda e, c:
                             self.on_buffer_changed(self.buffer))
     self.connect('expose-event', self.on_expose)
     self._sql_marks = set()
     self.connect('destroy', self.on_destroy)
Ejemplo n.º 4
0
    def __init__(self, prefs):
        BuilderAware.__init__(self, join_to_file_dir(__file__, 'editor_prefs.glade'))
        self.activator = shortcuts.ShortcutActivator(self.window)
        self.activator.bind('Escape', self.hide)

        self.prefs = prefs
        self.original_prefs = prefs.copy()

        self.langs.append(('default', ))
        lm = gtksourceview2.language_manager_get_default()
        for lang_id in sorted(lm.get_language_ids()):
            self.langs.append((lang_id, ))

        sm = gtksourceview2.style_scheme_manager_get_default()
        for style_id in sm.get_scheme_ids():
            self.styles.append((style_id, ))

        self.checks = ['use-tabs', 'show-right-margin', 'show-line-numbers', 'wrap-text',
            'highlight-current-line', 'show-whitespace', 'remove-trailing-space']

        for name in self.checks:
            getattr(self, name.replace('-', '_')).connect(
                'toggled', self.on_checkbox_toggled, name)

        self.margin_width.connect('value-changed', self.on_spin_changed, 'right-margin')
        self.tab_width.connect('value-changed', self.on_spin_changed, 'tab-width')
        self.line_spacing.connect('value-changed', self.on_spin_changed, 'line-spacing')

        self.font.connect('font-set', self.on_font_set, 'font')

        for h in on_dialog_created_hooks:
            h(self)
Ejemplo n.º 5
0
 def set_code_mode(self, codemode):
     if not self.gtksourceview_mode:
         return
     # Non-code is the default
     if not codemode:
         return
     self.input_view.modify_font(pango.FontDescription("monospace"))
     fs = Filesystem.getInstance()
     try:
         mimetype = fs.get_file_sync(self.__filename).mimetype
     except FileStatError as e:
         mimetype = None
     target_lang = None
     if gtksourceview2_avail:
         import gtksourceview2
         langman = gtksourceview2.language_manager_get_default()
         for language_id in langman.get_language_ids():
             language = langman.get_language(language_id)
             for langmime in language.get_mime_types():
                 if mimetype == langmime:
                     target_lang = language
                     break
             if target_lang:
                 break
         self.input.set_highlight_syntax(True)
     else:
         import gtksourceview
         target_lang = gtksourceview.SourceLanguagesManager(
         ).get_language_from_mime_type(mimetype)
         self.input.set_highlight(True)
     if target_lang:
         self.input.set_language(target_lang)
Ejemplo n.º 6
0
    def __init__(self, locals={}, savepath=None, content=None, parent=None):
        super(CommandShell, self).__init__(content=(content or self.DEFAULT_CONTENT), filename=savepath, parent=parent)
        self._locals = locals
        self.__ui_string = """
<ui>
  <menubar name='Menubar'>
    <menu action='ToolsMenu'>
      <menuitem action='Eval'/>    
      <separator/>
      <menuitem action='Reset'/>
    </menu>
  </menubar>
</ui>        
"""    
        actions = [
            ('ToolsMenu', None, 'Tools'),
            ('Eval', None, '_Eval', '<control>Return', 'Evaluate current input', self.__eval_cb),            
            ('Reset', None, '_Reset', None, 'Reset to default content', self.__reset_cb),
            ]
        self.__actiongroup = ag = gtk.ActionGroup('ShellActions')        
        ag.add_actions(actions)
        self._ui.insert_action_group(ag, 1)
        self._ui.add_ui_from_string(self.__ui_string)

        if self.gtksourceview_mode:
            try:
                import gtksourceview2
                pylang = gtksourceview2.language_manager_get_default().get_language('python')
            except ImportError, e:
                import gtksourceview
                pylang = gtksourceview.SourceLanguagesManager().get_language_from_mime_type("text/x-python")
                self.input.set_highlight(True)
            self.input.set_language(pylang)
Ejemplo n.º 7
0
def generateSourceWidget(language='python',linenums=True,syntaxhighlight=True,highlightline=True,editable=True,visiblecursor=True):
    """
    Generates a GTK sourceview widget or a generic TextView if GTK Sourceview is not available
    """
    # Check if we use GTK Sourceview for code widget
    if evogtk.HAS_GTKSOURCEVIEW:
        # Use GTK Sourceview
        import gtksourceview2
        buffer=gtksourceview2.Buffer()
        view=gtksourceview2.View(buffer)
        view.set_show_line_numbers(linenums)
        view.set_highlight_current_line(highlightline)
        # Set code highlighting
        lm=gtksourceview2.language_manager_get_default()
        lang=lm.get_language(language)
        if lang:
            buffer.set_language(lang)
            buffer.set_highlight_syntax(syntaxhighlight)
    else:
        # Use GTK TextView
        buffer=gtk.TextBuffer()
        view=gtk.TextView(buffer)
    # Set view basic parameters
    view.set_editable(editable)
    view.set_cursor_visible(visiblecursor)
    return view
Ejemplo n.º 8
0
    def _set_file_path(self, file_path):
        if file_path == self._file_path:
            return
        self._file_path = file_path

        if self._file_path is None:
            self._buffer.set_text('')
            return

        mime_type = mime.get_for_file(self._file_path)
        logging.debug('Detected mime type: %r' % mime_type)

        language_manager = gtksourceview2.language_manager_get_default()
        detected_language = None
        for language_id in language_manager.get_language_ids():
            language = language_manager.get_language(language_id)
            if mime_type in language.get_mime_types():
                detected_language = language
                break

        if detected_language is not None:
            logging.debug('Detected language: %r' % \
                    detected_language.get_name())

        self._buffer.set_language(detected_language)
        self._buffer.set_text(open(self._file_path, 'r').read())
Ejemplo n.º 9
0
def _complete_language(words, idx):
	manager = gsv.language_manager_get_default()
	ids = manager.get_language_ids()
	ids.append('none')
	ids.sort()

	return commands.completion.words(ids)(words, idx)
Ejemplo n.º 10
0
 def __init__(self, win, editor=None):
     gtksourceview2.View.__init__(self)
     gtk.widget_push_composite_child()
     self.editor = editor
     self.buffer = gtksourceview2.Buffer()
     self.set_buffer(self.buffer)
     self.set_show_line_marks(True)
     width, height = gtk.icon_size_lookup(gtk.ICON_SIZE_MENU)
     pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, width, height)
     pixbuf.fill(0)
     self.set_mark_category_pixbuf('sql-start', pixbuf)
     self.set_mark_category_pixbuf('sql-end', pixbuf)
     lang_manager = gtksourceview2.language_manager_get_default()
     self.buffer.set_language(lang_manager.get_language('sql'))
     self.app = win.app
     self._sig_app_config_changed = self.app.config.connect(
         'changed', self.on_config_changed)
     self.update_textview_options()
     self._buffer_changed_cb = None
     self.buffer.connect('end-user-action', self.on_buffer_changed)
     self.buffer.connect('mark-set', self.on_mark_set)
     if self.editor is not None:
         self.editor.connect(
             'connection-changed',
             lambda e, c: self.on_buffer_changed(self.buffer))
     self.connect('expose-event', self.on_expose)
     self._sql_marks = set()
     self.connect('destroy', self.on_destroy)
Ejemplo n.º 11
0
 def __init__(self):
     """
     Initialization
     """
     # Check if we have GTKSourceview support before initialising
     if not evogtk.HAS_GTKSOURCEVIEW:
         raise ImportError('(EVOGTK) There is no support for Source Editor Widget without GTKSourceview support')
     # Initialize parent class
     gtk.VBox.__init__(self)
     # Create scroll for editor
     self.__scroll=gtk.ScrolledWindow(gtk.Adjustment(),gtk.Adjustment())
     # Get default language manager
     self.__langmanager=gtksourceview.language_manager_get_default()
     # Initialize source buffer
     self.__srcbuffer=gtksourceview.Buffer()
     # Initialize source view
     self.__srcview=gtksourceview.View()
     self.__srcview.set_buffer(self.__srcbuffer)
     # Widget packing
     self.__scroll.add(self.__srcview)
     self.pack_start(self.__scroll)
     # Connect signals for status updating
     signals={
         self.__srcbuffer: ['modified-changed','changed'],
         self.__srcview: ['move-cursor','toggle-overwrite','key-press-event','key-release-event','button-press-event','button-release-event'],
     }
     for obj in signals.keys():
         for signal in signals[obj]:
             obj.connect(signal,self.__update_status)     
     # Show widget contents   
     self.show_all()
     # Update status data
     self.__status=self.SourceEditorStatus()
Ejemplo n.º 12
0
def setupBuffer (buffer, langName, styleNames):
	if GTKSV:
		sm = gtksv.style_scheme_manager_get_default()
		if styleNames != None:
			for styleName in styleNames:
				style = sm.get_scheme(styleName)
				if style != None:
					break
			else:
				style = None
		else:
			style = sm.get_scheme('classic')
		if Trace:
			if style != None:
				print 'style-scheme:', style.get_name()
			else:
				print 'no style-scheme'
		buffer.set_property("style-scheme", style)

		if langName != None:
			lm = gtksv.language_manager_get_default()
			lang = lm.get_language(langName)
		else:
			lang = None
		if Trace:
			if lang != None:
				print 'language:', lang.get_name()
			else:
				print 'no language'
		buffer.set_property("language", lang)
Ejemplo n.º 13
0
    def __init__(self):
        gtk.VBox.__init__(self)

        self._b = gtksourceview.Buffer()
        style_scheme = gtksourceview.style_scheme_manager_get_default().get_scheme('classic')
        if style_scheme:
            self._b.set_style_scheme(style_scheme)
        self._b.set_language(gtksourceview.language_manager_get_default().get_language("cpp"))
        self._b.set_highlight_syntax(True)

        #self._b.connect('mark-set', move_cursor_cb, view)
        #self._b.connect('changed', update_cursor_position, view)

        self._v = gtksourceview.View(self._b)
        self._v.set_show_line_numbers(True)
        #self._v.set_show_line_marks(action.get_active())
        #self._v.set_show_right_margin(action.get_active())
        #self._v.set_auto_indent(action.get_active())
        #self._v.set_insert_spaces_instead_of_tabs(action.get_active())
        #self._v.set_tab_width(action.get_current_value())
        #self._v.connect('button-press-event', button_press_cb)

        sw = gtk.ScrolledWindow()
        sw.set_shadow_type(gtk.SHADOW_IN)
        self.pack_start(sw, True, True, 0)
        sw.add(self._v)

        # setup view
        font_desc = pango.FontDescription('monospace')
        if font_desc:
            self._v.modify_font(font_desc)
Ejemplo n.º 14
0
def _complete_language(words, idx):
	manager = gsv.language_manager_get_default()
	ids = manager.get_language_ids()
	ids.append('none')
	ids.sort()
	
	return commands.completion.words(ids)(words, idx)
Ejemplo n.º 15
0
def createsrcview(status, f=None):
	sbuffer = gtksourceview2.Buffer()
	if f:
		content = file(f).read()
		sbuffer.set_language(get_lang_for_content(content))
		text = unicode(content, 'utf-8', 'ignore')
		sbuffer.set_text(text)
	else:
		manager = gtksourceview2.language_manager_get_default()
		sbuffer.set_language(manager.get_language("c"))
	sv = gtksourceview2.View(sbuffer)
	p = prefs.preferences()
	misc.set_widget_font(sv, config.cur_editor_font)
	manager = gtksourceview2.StyleSchemeManager()
	manager.append_search_path(misc.getArduinoUiPath())
	manager.force_rescan()
	scheme =  manager.get_scheme("arduino")
	sbuffer.set_style_scheme(scheme);
	sv.set_size_request(300, 100)
	sv.set_editable(True)
	sv.set_auto_indent(True)
	if config.show_numbers == 'true':
		sv.set_show_line_numbers(True)
	sv.set_cursor_visible(True)
	sv.set_wrap_mode(gtk.WRAP_CHAR)
	sv.set_right_margin_position(80)
	updatePos(sbuffer, status)
	sbuffer.connect("mark_set", markCb, status)
	sbuffer.connect("insert_text", instextCallback)
	sv.set_highlight_current_line(True)
	resetCursor(sbuffer)
	return sbuffer, sv
Ejemplo n.º 16
0
	def __init__(self, parent, db):
		"""
            Initializes the table panel

            @param parent: the parent dialog
		"""
		panel.Panel.__init__(self, parent, "Worksheet")
		self.db = db

		# Add query result panel
		container = self.builder.get_object("eventbox_queryresult")
		self.queryresult_panel = queryresult.QueryResultPanelView(container)
		widget, name = self.queryresult_panel.get_panel()
		container.add(widget)

		# Configure the GTK source view
		self._sourceview = self.builder.get_object("gtksourceview_worksheet")

		self._lang_manager = gtksourceview2.language_manager_get_default()
		lang = self._lang_manager.get_language('sql')

		srcbuffer = gtksourceview2.Buffer()
		srcbuffer.set_language(lang)

		self._sourceview.set_auto_indent(True)
		self._sourceview.set_buffer(srcbuffer)

		# Connect buttons
		button = self.builder.get_object("button_execute")
		button.connect("clicked", self.on_button_execute_clicked)
		button = self.builder.get_object("button_reformat")
		button.connect("clicked", self.on_button_reformat_clicked)
		button = self.builder.get_object("button_clear")
		button.connect("clicked", self.on_button_clear_clicked)
Ejemplo n.º 17
0
    def __init__(self, session):
        self.buffers = []
        self.windows = []

        self.session = session
        self.style_manager = gtksourceview2.style_scheme_manager_get_default()
        self.lang_manager = gtksourceview2.language_manager_get_default()
        self.modify_lang_search_path(self.lang_manager)

        self.activator = keymap.get_activator(config_section='editor_window')
        self.activator.add_context('manager', (), lambda: self)

        self.activator.bind_menu('_File#1')
        self.activator.bind_menu('_Edit#10')
        self.activator.bind_menu('_Prefs#15/_Global#90')
        self.activator.bind_menu('Prefs/_Session')
        self.activator.bind_menu('Prefs/_Project')
        self.activator.bind_menu('_View#20')
        self.activator.bind_menu('Too_ls#30')
        self.activator.bind_menu('_Run#40')
        self.activator.bind_menu('_Tab#90')
        self.activator.bind_menu('_Window#100')

        self.activator.bind('manager', 'quit', 'File/_Quit#100', EditorManager.quit).to('<ctrl>q')
        self.activator.bind('window', 'plugin-list', 'Prefs/Pl_ugins#10',
            snaked.core.plugins.show_plugins_prefs)

        self.activator.alias(('window', 'activator'), 'root-menu', 'Prefs/_Root menu#100')

        self.plugin_manager = PluginManager(self.activator)

        self.init_conf()

        self.default_ctx_processor = ContextProcessor(join_to_settings_dir('snaked', 'contexts.conf'))
        self.session_ctx_processor = ContextProcessor(
            join_to_settings_dir('snaked', self.session, 'contexts'))
        self.ctx_managers = {}

        self.escape_stack = []
        self.escape_map = {}
        self.on_quit = []

        # Init core plugins
        self.plugin_manager.add_plugin(prefs)
        self.plugin_manager.add_plugin(snaked.core.quick_open)
        self.plugin_manager.add_plugin(snaked.core.editor_list)
        self.plugin_manager.add_plugin(snaked.core.titler)
        self.plugin_manager.add_plugin(snaked.core.console)
        self.plugin_manager.add_plugin(snaked.core.spot)
        self.plugin_manager.add_plugin(snaked.core.monitor)
        self.plugin_manager.add_plugin(snaked.core.completer)

        self.spot_manager = snaked.core.spot.Manager()

        self.plugin_manager.ready('manager', self)

        self.plugin_manager.add_plugin(snaked.core.window)

        snaked.core.plugins.init_plugins(self.plugin_manager)
Ejemplo n.º 18
0
 def set_response(self, response):
     buf = gtksourceview.Buffer()
     self.set_buffer(buf)
     manager = gtksourceview.language_manager_get_default()
     language = manager.get_language('xml')
     buf.set_highlight_syntax(True)
     buf.set_language(language)
     buf.set_text(response.body.decode(response.encoding))
Ejemplo n.º 19
0
def _get_language_for_mime_type(mime):
    lang_manager = gtksourceview.language_manager_get_default()
    lang_ids = lang_manager.get_language_ids()
    for i in lang_ids:
        lang = lang_manager.get_language(i)
        for m in lang.get_mime_types():
            if m == mime:
                return lang
    return None
Ejemplo n.º 20
0
      def get_language_from_mime_type(mime):
	manager = gtksourceview2.language_manager_get_default()
	languagetypes = manager.get_language_ids()
	for i in languagetypes:
	  language = manager.get_language(i)
	  for mimel in language.get_mime_types():
	    if mimel == mime:
	      return language
	return None
Ejemplo n.º 21
0
def get_language_for_mime_type(mime):
    lang_manager = gtksourceview.language_manager_get_default()
    lang_ids = lang_manager.get_language_ids()
    for i in lang_ids:
        lang = lang_manager.get_language(i)
        for m in lang.get_mime_types():
            if m == mime:
                return lang
    return None
Ejemplo n.º 22
0
    def initialize_display(self):
        '''Set up GTK and friends'''
        self.fix_mimetype()

        self.cloud.shared_buffer = gtk_tools.TextBufferSharePoint(self.buffer)

        self.setup_toolbar()
        #Some graphics code borrowed from Pippy

        lang_manager = gtksourceview.language_manager_get_default()
        if hasattr(lang_manager, 'list_languages'):
            langs = lang_manager.list_languages()
        else:
            lang_ids = lang_manager.get_language_ids()
            langs = [
                lang_manager.get_language(lang_id) for lang_id in lang_ids
            ]
            for lang in langs:
                for mtype in lang.get_mime_types():
                    if mtype == self.metadata[mdnames.mimetype_md]:
                        self.buffer.set_language(lang)
                        break

        self.text_view.set_editable(True)
        self.text_view.set_cursor_visible(True)

        if self.metadata[mdnames.mimetype_md] == "text/plain":
            self.text_view.set_show_line_numbers(False)
            self.text_view.set_wrap_mode(gtk.WRAP_WORD)
            font = pango.FontDescription("Bitstream Vera Sans " +
                                         str(style.FONT_SIZE))
        else:
            if hasattr(self.buffer, 'set_highlight'):
                self.buffer.set_highlight(True)
            else:
                self.buffer.set_highlight_syntax(True)

            self.text_view.set_show_line_numbers(True)

            self.text_view.set_wrap_mode(gtk.WRAP_CHAR)
            self.text_view.set_insert_spaces_instead_of_tabs(True)
            self.text_view.set_tab_width(2)
            self.text_view.set_auto_indent(True)
            font = pango.FontDescription("Monospace " + str(style.FONT_SIZE))

        self.text_view.modify_font(font)

        if self.refresh_buffer:
            #see load_from_journal()
            self.buffer.begin_not_undoable_action()
            self.buffer.set_text(self.refresh_buffer)
            self.buffer.end_not_undoable_action()

        self.text_view.show()

        #Return the main widget. our parents take care of GTK stuff
        return self.scrollwindow
Ejemplo n.º 23
0
	def __get_language_for_mime_type(self, mime):
		from gtksourceview2 import language_manager_get_default
		lang_manager = language_manager_get_default()
		lang_ids = lang_manager.get_language_ids()
		for i in lang_ids:
			lang = lang_manager.get_language(i)
			for m in lang.get_mime_types():
				if m == mime: return lang
		return None
Ejemplo n.º 24
0
        def get_language_from_mime_type(self, mime_types):
            lang_manager = gtksourceview2.language_manager_get_default()
            lang_result = None
            for lang_id in lang_manager.get_language_ids():
                lang = lang_manager.get_language(lang_id)
                if mime_types in lang.get_mime_types():
                    lang_result = lang
                    break

            return lang_result
Ejemplo n.º 25
0
Archivo: ide.py Proyecto: aoloe/shoebot
        def get_language_from_mime_type(self, mime_types):
            lang_manager = gtksourceview2.language_manager_get_default()
            lang_result = None
            for lang_id in lang_manager.get_language_ids():
                 lang = lang_manager.get_language(lang_id)
                 if mime_types in lang.get_mime_types():
                      lang_result = lang
                      break

            return lang_result
Ejemplo n.º 26
0
 def get_language_for_mime_type(self,mime):
     """Recupere la syntaxe associee a un langage
     """
     lang_manager = gsv.language_manager_get_default()
     lang_ids = lang_manager.get_language_ids()
     for i in lang_ids:
         lang = lang_manager.get_language(i)
         for m in lang.get_mime_types():
             if m == mime:
                 return lang
     return None
Ejemplo n.º 27
0
def get_lang_for_file(f):
	manager = gtksourceview2.language_manager_get_default()
	languages = gtksourceview2.LanguageManager.get_language_ids(manager)
	for l in languages:
		lang = manager.get_language(l)
		if lang == None: return None
		globs = gtksourceview2.Language.get_globs(lang)
		if globs == None: continue
		for p in globs:
			if fnmatch.fnmatch(f, p):
				return lang
Ejemplo n.º 28
0
 def _get_languages(self):
     """Return a list of the languages known to gedit."""
     LOGGER.log()
     gtk_lang_mgr = gtksourceview2.language_manager_get_default()
     language_ids = gtk_lang_mgr.get_language_ids()
     language_names = []
     for language_id in language_ids:
         language = gtk_lang_mgr.get_language(language_id)
         language_names.append(language.get_name())
     language_names.sort(lambda a, b: cmp(a.lower(), b.lower()))
     return language_names
Ejemplo n.º 29
0
def get_lang_for_content(content):
	mime = misc.get_mime_type(content)
	manager = gtksourceview2.language_manager_get_default()
	languages = gtksourceview2.LanguageManager.get_language_ids(manager)
	for l in languages:
		lang = manager.get_language(l)
		if lang == None: return None
		globs = gtksourceview2.Language.get_mime_types(lang)
		if globs == None: continue
		for p in globs:
			if p == mime:
				return lang
Ejemplo n.º 30
0
 def _get_languages(self):
     """Return a list of the languages known to gedit."""
     LOGGER.log()
     gtk_lang_mgr = gtksourceview2.language_manager_get_default()
     language_ids = gtk_lang_mgr.get_language_ids()
     language_names = []
     for language_id in language_ids:
         language = gtk_lang_mgr.get_language(language_id)
         language_names.append(language.get_name())
     language_names.sort(lambda a, b:
                             cmp(a.lower(), b.lower()))
     return language_names
Ejemplo n.º 31
0
    def __init__(self, locals={}, savepath=None, content=None, parent=None):
        super(CommandShell, self).__init__(content=(content
                                                    or self.DEFAULT_CONTENT),
                                           filename=savepath,
                                           parent=parent)
        self._locals = locals
        self.__ui_string = """
<ui>
  <menubar name='Menubar'>
    <menu action='ToolsMenu'>
      <menuitem action='Eval'/>    
      <separator/>
      <menuitem action='Reset'/>
    </menu>
  </menubar>
</ui>        
"""
        actions = [
            ('ToolsMenu', None, 'Tools'),
            ('Eval', None, '_Eval', '<control>Return',
             'Evaluate current input', self.__eval_cb),
            ('Reset', None, '_Reset', None, 'Reset to default content',
             self.__reset_cb),
        ]
        self.__actiongroup = ag = gtk.ActionGroup('ShellActions')
        ag.add_actions(actions)
        self._ui.insert_action_group(ag, 1)
        self._ui.add_ui_from_string(self.__ui_string)

        if self.gtksourceview_mode:
            try:
                import gtksourceview2
                pylang = gtksourceview2.language_manager_get_default(
                ).get_language('python')
            except ImportError as e:
                import gtksourceview
                pylang = gtksourceview.SourceLanguagesManager(
                ).get_language_from_mime_type("text/x-python")
                self.input.set_highlight(True)
            self.input.set_language(pylang)

        # Doesn't make sense when we're not backed by a file
        self._ui.get_action_groups()[0].get_action('Revert').set_sensitive(
            False)

        self.input.move_mark_by_name("insert", self.input.get_end_iter())
        self.input.move_mark_by_name("selection_bound",
                                     self.input.get_end_iter())

        self.set_title('Hotwire Command Shell')
        self.input_view.modify_font(pango.FontDescription("monospace"))
Ejemplo n.º 32
0
def language(view, language=None):
	"""Set document language: set.language &lt;language&gt;

Set the document language to the language with the specified id"""
	if not language or language == 'none':
		view.get_buffer().set_language(None)
		return False

	manager = gsv.language_manager_get_default()
	lang = manager.get_language(language)
	
	if lang:
		view.get_buffer().set_language(lang)
		return False
	else:
		raise commander.commands.exceptions.Execute('Invalid language: ' + language)
Ejemplo n.º 33
0
def language(view, language=None):
	"""Set document language: set.language &lt;language&gt;

Set the document language to the language with the specified id"""
	if not language or language == 'none':
		view.get_buffer().set_language(None)
		return False

	manager = gsv.language_manager_get_default()
	lang = manager.get_language(language)

	if lang:
		view.get_buffer().set_language(lang)
		return False
	else:
		raise commander.commands.exceptions.Execute('Invalid language: ' + language)
Ejemplo n.º 34
0
 def __init__(self):
     gtk.ScrolledWindow.__init__(self)
     self.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)
     self.lang_manager = gtksv.language_manager_get_default()
     self.buffer = gtksv.Buffer()
     self.buffer.set_modified(False)
     self.buffer.set_highlight_syntax(True)
     self.view = gtksv.View(self.buffer)
     self.view.set_data('id', "editview")
     self.view.set_font = self.set_font
     self.view.set_max_undo_levels = self.buffer.set_max_undo_levels
     self.view.set_highlight_matching_brackets = self.buffer.set_highlight_matching_brackets
     self.view.set_stylescheme = self.set_stylescheme
     self.add(self.view)
     self.show_all()
     glib.timeout_add(250, self.view.grab_focus)
Ejemplo n.º 35
0
    def __init__(self, session):
        self.editors = []
        self.session = session
        self.style_manager = gtksourceview2.style_scheme_manager_get_default()
        self.lang_manager = gtksourceview2.language_manager_get_default()
        self.modify_lang_search_path(self.lang_manager)

        self.on_quit = []

        self.plugin_manager = PluginManager()
        prefs.register_dialog('Plugins', self.plugin_manager.show_plugins_prefs, 'plugin',
            'extension')

        prefs.register_dialog('Key configuration', self.show_key_preferences, 'key', 'bind', 'shortcut')

        prefs.register_dialog('Editor settings', self.show_editor_preferences,
            'editor', 'font', 'style', 'margin', 'line', 'tab', 'whitespace')

        prefs.register_dialog('Global preferences', self.show_global_preferences,
            'snaked', 'preferences')

        prefs.register_dialog('Session preferences', self.show_session_preferences,
            'session', 'preferences')

        prefs.register_dialog('File types', self.edit_contexts, 'file', 'type', 'association')

        self.snaked_conf = config.SnakedConf()
        self.load_conf()

        self.escape_stack = []
        self.escape_map = {}
        self.spot_history = []
        self.context_processors = {}
        self.lang_contexts = {}
        self.ctx_contexts = {}

        load_shortcuts()
        self.register_app_shortcuts()

        # Init core plugins
        self.plugin_manager.load_core_plugin(snaked.core.quick_open)
        self.plugin_manager.load_core_plugin(snaked.core.titler)
        self.plugin_manager.load_core_plugin(snaked.core.editor_list)

        add_context_setter('lang', self.set_lang_context)
        add_context_setter('ctx', self.set_ctx_context)
Ejemplo n.º 36
0
	def __init__(self, xml, nb):
		self.xml = xml
		self.nb = nb
		
		renameload = {
			"treeview": "query_view", 
			"save_result": "save_result",
			"save_result_sql": "save_result_sql",
			"add_record": "add_record_tool",
			"delete_record": "delete_record_tool",
			"apply_record": "apply_record_tool",
			"local_search": "local_search_button",
			"remove_order": "remove_order",
			"label": "query_label",
			"page": "first_query",
			"query_bottom_label": "query_bottom_label",
			"query_db_label": "query_db_label",
		}
		
		for attribute, xmlname in renameload.iteritems():
			self.__dict__[attribute] = xml.get_widget(xmlname)

		# Create a GTKSourceView for the query. One reason we do
		# this in code is because I was unable to get the widget
		# to appear in the Glade interface designer.
		lang_manager = gtksourceview.language_manager_get_default()
		buffer = gtksourceview.Buffer()
		buffer.set_language(lang_manager.get_language('sql'))
		buffer.set_highlight_syntax(True)
		container = xml.get_widget('query_text_container')
		self.textview = textview = gtksourceview.View(buffer)
		container.add(textview)
		textview.show()
			
		self.current_host = None
		self.current_db = None
		self.model = None
		self.last_source = None
		self.result_info = None
		self.append_iter = None
		self.save_result_sql.set_sensitive(False)
		self.last_path = None
		if hasattr(self, "query"):
			self.textview.get_buffer().set_text(self.query)
		self.last_auto_name = None
Ejemplo n.º 37
0
 def _get_languages_by_section(self):
     """Return a dictionary of the languages known to Gedit, grouped."""
     LOGGER.log()
     gtk_lang_mgr = gtksourceview2.language_manager_get_default()
     language_ids = gtk_lang_mgr.get_language_ids()
     languages_by_section = {}
     for language_id in language_ids:
         language = gtk_lang_mgr.get_language(language_id)
         section = language.get_section()
         name = language.get_name()
         if section in languages_by_section:
             languages_by_section[section].append(name)
         else:
             languages_by_section[section] = [name]
     for section in languages_by_section:
         languages_by_section[section].sort(lambda a, b:
                                             cmp(a.lower(), b.lower()))
     return languages_by_section
Ejemplo n.º 38
0
 def _get_languages_by_section(self):
     """Return a dictionary of the languages known to gedit, grouped."""
     LOGGER.log()
     gtk_lang_mgr = gtksourceview2.language_manager_get_default()
     language_ids = gtk_lang_mgr.get_language_ids()
     languages_by_section = {}
     for language_id in language_ids:
         language = gtk_lang_mgr.get_language(language_id)
         section = language.get_section()
         name = language.get_name()
         if section in languages_by_section:
             languages_by_section[section].append(name)
         else:
             languages_by_section[section] = [name]
     for section in languages_by_section:
         languages_by_section[section].sort(lambda a, b:
                                             cmp(a.lower(), b.lower()))
     return languages_by_section
Ejemplo n.º 39
0
    def __init__(self, locals={}, savepath=None, content=None, parent=None):
        super(CommandShell, self).__init__(content=(content or self.DEFAULT_CONTENT), filename=savepath, parent=parent)
        self._locals = locals
        self.__ui_string = """
<ui>
  <menubar name='Menubar'>
    <menu action='ToolsMenu'>
      <menuitem action='Eval'/>    
      <separator/>
      <menuitem action='Reset'/>
    </menu>
  </menubar>
</ui>        
"""    
        actions = [
            ('ToolsMenu', None, 'Tools'),
            ('Eval', None, '_Eval', '<control>Return', 'Evaluate current input', self.__eval_cb),            
            ('Reset', None, '_Reset', None, 'Reset to default content', self.__reset_cb),
            ]
        self.__actiongroup = ag = gtk.ActionGroup('ShellActions')        
        ag.add_actions(actions)
        self._ui.insert_action_group(ag, 1)
        self._ui.add_ui_from_string(self.__ui_string)

        if self.gtksourceview_mode:
            try:
                import gtksourceview2
                pylang = gtksourceview2.language_manager_get_default().get_language('python')
            except ImportError as e:
                import gtksourceview
                pylang = gtksourceview.SourceLanguagesManager().get_language_from_mime_type("text/x-python")
                self.input.set_highlight(True)
            self.input.set_language(pylang)
            
        # Doesn't make sense when we're not backed by a file
        self._ui.get_action_groups()[0].get_action('Revert').set_sensitive(False)
            
        self.input.move_mark_by_name("insert", self.input.get_end_iter())
        self.input.move_mark_by_name("selection_bound", self.input.get_end_iter())        
            
        self.set_title('Hotwire Command Shell')
        self.input_view.modify_font(pango.FontDescription("monospace"))        
Ejemplo n.º 40
0
    def __init__(self):
        #Set the Glade file
        self.builder = gtk.Builder()
        self.builder.add_from_file("openmv-ide.glade")

        sourceview = self.builder.get_object('gtksourceview')

        self.buffer = gtksourceview.Buffer()
        mgr = gtksourceview.style_scheme_manager_get_default()
        style_scheme = mgr.get_scheme('classic')
        if style_scheme:
            self.buffer.set_style_scheme(style_scheme)
        lang_manager = gtksourceview.language_manager_get_default()
        self.buffer.set_highlight_syntax(True)
        self.buffer.set_language(lang_manager.get_language("python"))
        self.buffer.set_text(ex_source)
        sourceview.set_buffer(self.buffer)

        self.terminal = self.builder.get_object('terminal')
        self.fd = os.open("/dev/ttyACM0", os.O_RDWR)
        self.terminal.set_size(80,24)
        self.terminal.set_pty(self.fd)

        self.framebuffer = self.builder.get_object("framebuffer_image")
        # status bar stuff
        self.statusbar = self.builder.get_object("statusbar")
        self.statusbar_ctx = self.statusbar.get_context_id("default")

        # init openmv
        openmv.init()

        #connect signals
        signals = {
            "on_execute_clicked" : self.execute_clicked,
            "on_stop_clicked" : self.stop_clicked,
            "on_top_window_destroy" : self.quit,
            "on_motion_notify": self.motion_notify,
            "on_button_press": self.button_pressed
        }
        self.builder.connect_signals(signals)
        self.window = self.builder.get_object("top_window")
    def setup_source_view(self):
        self._buffer = gtksourceview2.Buffer()
        lang_manager = gtksourceview2.language_manager_get_default()
        if 'python' in lang_manager.get_language_ids():
            lang = lang_manager.get_language('python')
            self._buffer.set_language(lang)

        self._source_view = gtksourceview2.View(self._buffer)
        self._source_view.set_editable(True)
        self._source_view.set_cursor_visible(True)
        self._source_view.set_show_line_numbers(True)
        self._source_view.set_wrap_mode(gtk.WRAP_CHAR)
        self._source_view.modify_font(pango.FontDescription("Monospace 10"))

        self._source_win = gtk.ScrolledWindow()
        self._source_win.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        self._source_win.add(self._source_view)

        self._find_tag = self._buffer.create_tag('find')
        self._find_tag.props.background = 'gray'
        self._find_tag.props.foreground = 'yellow'
    def setup_source_view(self):
        self._buffer = gtksourceview2.Buffer()
        lang_manager = gtksourceview2.language_manager_get_default()
        if 'python' in lang_manager.get_language_ids():
            lang = lang_manager.get_language('python')
            self._buffer.set_language(lang)

        self._source_view = gtksourceview2.View(self._buffer)
        self._source_view.set_editable(True)
        self._source_view.set_cursor_visible(True)
        self._source_view.set_show_line_numbers(True)
        self._source_view.set_wrap_mode(gtk.WRAP_CHAR)
        self._source_view.modify_font(pango.FontDescription("Monospace 10"))

        self._source_win = gtk.ScrolledWindow()
        self._source_win.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        self._source_win.add(self._source_view)

        self._find_tag = self._buffer.create_tag('find')
        self._find_tag.props.background = 'gray'
        self._find_tag.props.foreground = 'yellow'
Ejemplo n.º 43
0
    def init_syntax(self):
        text_buffer = self.get_buffer()
        lang_manager = gtksourceview2.language_manager_get_default()
        if hasattr(lang_manager, 'list_languages'):
            langs = lang_manager.list_languages()
        else:
            lang_ids = lang_manager.get_language_ids()
            langs = [lang_manager.get_language(lang_id)
                     for lang_id in lang_ids]
        for lang in langs:
            for m in lang.get_mime_types():
                if m == "text/x-python":
                    text_buffer.set_language(lang)

        if hasattr(text_buffer, 'set_highlight'):
            text_buffer.set_highlight(True)
        else:
            text_buffer.set_highlight_syntax(True)

        mgr = gtksourceview2.style_scheme_manager_get_default()
        style_scheme = mgr.get_scheme('oblivion')
        self.get_buffer().set_style_scheme(style_scheme)
Ejemplo n.º 44
0
    def load_text(self, offset=None):
        """
        Load the text, and optionally scroll to the given offset in the file.
        """
        self.text_buffer.begin_not_undoable_action()
        if not os.path.basename(self.fullPath).startswith('Unsaved_Document'):
            _file = file(self.fullPath)
            self.text_buffer.set_text(_file.read())
            _file.close()
            self.save_hash()
        if offset is not None:
            self._scroll_to_offset(offset)

        if hasattr(self.text_buffer, 'set_highlight'):
            self.text_buffer.set_highlight(False)
        else:
            self.text_buffer.set_highlight_syntax(False)
        mime_type = mimetypes.guess_type(self.fullPath)[0]
        if mime_type and not os.path.basename(
                self.fullPath).startswith('Unsaved_Document'):
            lang_manager = gtksourceview2.language_manager_get_default()
            if hasattr(lang_manager, 'list_languages'):
                langs = lang_manager.list_languages()
            else:
                lang_ids = lang_manager.get_language_ids()
                langs = [lang_manager.get_language(i) for i in lang_ids]
            for lang in langs:
                for m in lang.get_mime_types():
                    if m == mime_type:
                        self.text_buffer.set_language(lang)
                        if hasattr(self.text_buffer, 'set_highlight'):
                            self.text_buffer.set_highlight(True)
                        else:
                            self.text_buffer.set_highlight_syntax(True)
        self.restore_breakpoints()
        self.restore_embeds()
        self.text_buffer.end_not_undoable_action()
        self.text_buffer.set_modified(False)
        self.text_view.grab_focus()
Ejemplo n.º 45
0
    def _set_file_path(self, file_path):
        self._file_path = file_path

        if self._file_path is None:
            self._buffer.set_text('')
            return

        mime_type = mime.get_for_file(self._file_path)
        _logger.debug('Detected mime type: %r', mime_type)

        language_manager = gtksourceview2.language_manager_get_default()
        detected_language = None
        for language_id in language_manager.get_language_ids():
            language = language_manager.get_language(language_id)
            if mime_type in language.get_mime_types():
                detected_language = language
                break

        if detected_language is not None:
            _logger.debug('Detected language: %r',
                          detected_language.get_name())

        self._buffer.set_language(detected_language)
        self._buffer.set_text(open(self._file_path, 'r').read())
Ejemplo n.º 46
0
    'TextGenerator',
]

import re
from gettext import gettext as _
from keyword import kwlist
from pydoc import TextDoc
from xml.sax import saxutils

import gobject as GObject
import gtk as Gtk
import gtksourceview2 as GtkSource

from gdp import PluginMixin

lang_manager = GtkSource.language_manager_get_default()
doctest_language = lang_manager.get_language('doctest')

doctest_pattern = re.compile(r'^.*(doc|test|stories).*/.*\.(txt|doctest)$')


def get_word(document, word_pattern, end=None):
    """Return a 3-tuple of the word fragment before the cursor.

    The tuple contains the (word_fragment, start_iter, end_iter) to
    identify the prefix and its starting and end position in the
    document.
    """
    if end is None:
        end = document.get_iter_at_mark(document.get_insert())
    start = end.copy()
Ejemplo n.º 47
0
    def __init__(self, parent):

        ##Get the XML Config##
        glade_file_path = os.path.join('..', 'glade', 'canvasproperties.glade')
        xml = gtk.glade.XML(glade_file_path, root=None, domain="", typedict={})

        self.dialog = xml.get_widget('dialog')
        self.parent = parent

        ##Get the ASCEND lang##
        self.sourceviewLangman = gtksourceview.language_manager_get_default()
        op = self.sourceviewLangman.get_search_path()
        if os.path.join('..', '..', 'tools', 'gtksourceview-2.0') not in op:
            op.append(os.path.join('..', '..', 'tools', 'gtksourceview-2.0'))
            self.sourceviewLangman.set_search_path(op)
        self.sourceviewLang = self.sourceviewLangman.get_language('ascend')

        ##Preview Tab##
        scrolledwindow = xml.get_widget('scrolledwindow1')
        self.sourceviewView = gtksourceview.View()
        self.sourceviewView.set_editable(False)
        #self.sourceviewView.set_auto_indent(True)
        self.sourceviewBuff = gtksourceview.Buffer()
        self.sourceviewBuff.set_language(self.sourceviewLang)
        self.sourceviewBuff.set_highlight_syntax(True)
        self.sourceviewBuff.set_text(str(self.parent.view.canvas))
        self.sourceviewView.set_buffer(self.sourceviewBuff)
        scrolledwindow.add(self.sourceviewView)
        self.sourceviewView.show()

        ##Declaration Tab##
        scrolledwindow2 = xml.get_widget('scrolledwindow2')
        self.sourceviewView2 = gtksourceview.View()
        self.sourceviewView2.set_auto_indent(True)
        self.sourceviewBuffMethod = gtksourceview.Buffer()
        self.sourceviewBuffMethod.set_language(self.sourceviewLang)
        self.sourceviewBuffMethod.set_highlight_syntax(True)
        self.sourceviewBuffMethod.set_text(
            str(self.parent.view.canvas.user_code))
        self.sourceviewView2.set_buffer(self.sourceviewBuffMethod)
        scrolledwindow2.add(self.sourceviewView2)
        self.sourceviewView2.show()

        ##Instance Tab##
        try:
            self.instance_box = xml.get_widget('instancescrolledwin')
            self.instance_model = modeltree.TreeView(parent.M)
            self.instance_box.add(self.instance_model.treeview)
            self.instance_model.treeview.show()
        except Exception as e:
            self.instance_box = xml.get_widget('instancescrolledwin')
            self.instance_label = gtk.Label()
            self.instance_box.add_with_viewport(self.instance_label)
            self.instance_label.set_text(
                'Instance not Built, Solve the Canvas Model first!')
            self.instance_label.show()

        ##Stream(s) tab##
        self.treeview = xml.get_widget('treeview1')
        self.stream_store = gtk.TreeStore(gobject.TYPE_PYOBJECT,
                                          gobject.TYPE_STRING,
                                          gobject.TYPE_STRING)
        for stream in self.parent.ascwrap.streams:
            row = self.stream_store.append(None, [stream, str(stream), ''])
            for prop in stream.stream_properties:
                self.stream_store.append(
                    row, [stream, prop, stream.stream_properties[prop]])
        self.treeview.set_model(self.stream_store)
        self.draw_stream_view()

        OK_button = xml.get_widget('ok')
        OK_button.connect('clicked', self.save_changes)
        OK_button.grab_default()
Ejemplo n.º 48
0
    def init_gtk_sourceview(self):
        """
        replace textview with gtksourcevice
        """
        try:
            org_tv = self.textview
            manager = gtksourceview2.language_manager_get_default()
            language = manager.get_language("sql")

            sb = gtksourceview2.Buffer()
            sb.set_highlight_syntax(True)
            sb.set_language(language)
            sv = self.textview = gtksourceview2.View(sb)

            self.query_text_sw.remove(org_tv)
            self.query_text_sw.add(sv)
            sv.show()

            sv.set_show_line_numbers(True)
            sv.set_show_line_marks(True)
            sv.set_tab_width(4)
            sv.set_auto_indent(True)
            sv.set_insert_spaces_instead_of_tabs(False)
            sv.set_show_right_margin(True)
            sv.set_smart_home_end(True)
            sv.set_right_margin_position(80)

            # sv config
            # for pt, pn, pd in (
            #     (bool, "show_line_numbers", True),
            #     #(bool, "show_line_markers", False),
            #     #(int, "tabs_width", 4),
            #     (bool, "auto_indent", True),
            #     (bool, "insert_spaces_instead_of_tabs", False),
            #     #(bool, "show_margin", True),
            #     #(int, "margin", 80),
            #     (bool, "smart_home_end", True)
            # ):
            #
            #     cn = "sourceview.%s" % pn
            #     try:
            #         v = self.emma.config[cn]
            #         if pt == bool:
            #             v = v == "1" or v.lower() == "true" or v.lower() == "yes"
            #         else:
            #             v = pt(v)
            #     except:
            #         v = pd
            #     method = getattr(sv, "set_%s" % pn)
            #     method(v)
            # sb config
            # for pt, pn, pd in (
            #     (bool, "check_brackets", True),
            #     (bool, "highlight", True),
            #     (int, "max_undo_levels", 15)
            # ):
            #     cn = "sourceview.%s" % pn
            #     try:
            #         v = self.emma.config[cn]
            #         if pt == bool:
            #             v = v == "1" or v.lower() == "true" or v.lower() == "yes"
            #         else:
            #             v = pt(v)
            #     except:
            #         v = pd
            #     method = getattr(sb, "set_%s" % pn)
            #     method(v)
        except:
            dialogs.alert(traceback.format_exc())
Ejemplo n.º 49
0
    def __init__(self):
        #Set the Glade file
        self.builder = gtk.Builder()
        self.builder.add_from_file(ui_path)

        # get top window
        self.window = self.builder.get_object("top_window")

        # status bar stuff
        self.statusbar = self.builder.get_object("statusbar")
        self.statusbar_ctx = self.statusbar.get_context_id("default")

        #save toolbutton
        self.save_button = self.builder.get_object('save_file_toolbutton')
        self.save_button.set_sensitive(False)

        #configure gtksourceview
        sourceview = self.builder.get_object('gtksourceview')
        self.buffer = gtksourceview.Buffer()
        mgr = gtksourceview.style_scheme_manager_get_default()
        style_scheme = mgr.get_scheme('classic')
        if style_scheme:
            self.buffer.set_style_scheme(style_scheme)
        lang_manager = gtksourceview.language_manager_get_default()
        self.buffer.set_highlight_syntax(True)
        self.buffer.set_language(lang_manager.get_language("python"))
        self.buffer.connect("changed", self.text_changed)

        # open last opened file
        if os.path.isfile(config_path):
            with open(config_path, "r") as file:
                self.file_path = file.read()
            if os.path.isfile(self.file_path):
                with open(self.file_path, "r") as file:
                    self.buffer.set_text(file.read())
                    self.window.set_title(os.path.basename(self.file_path))
            else:
                self.file_path = None

        sourceview.set_buffer(self.buffer)

        # open VCP and configure the terminal
        self.terminal = self.builder.get_object('terminal')
        self.fd = os.open("/dev/ttyACM0", os.O_RDWR)
        self.terminal.set_size(80, 24)
        self.terminal.set_pty(self.fd)

        # get drawingarea
        self.pixbuf = None
        self.drawingarea = self.builder.get_object("drawingarea")
        self.da_menu = self.builder.get_object("da_menu")

        # selection coords
        self.x1 = 0
        self.y1 = 0
        self.x2 = 0
        self.y2 = 0
        self.selection_started = False
        self.sel_ended = False

        # set control scales attributes
        self.builder.get_object("contrast_adjust").attr = openmv.ATTR_CONTRAST
        self.builder.get_object(
            "brightness_adjust").attr = openmv.ATTR_BRIGHTNESS
        self.builder.get_object(
            "saturation_adjust").attr = openmv.ATTR_SATURATION
        self.builder.get_object(
            "gainceiling_adjust").attr = openmv.ATTR_GAINCEILING

        #connect signals
        signals = {
            "on_top_window_destroy": self.quit,
            "on_execute_clicked": self.execute_clicked,
            "on_stop_clicked": self.stop_clicked,
            "on_motion_notify": self.motion_notify,
            "on_button_press": self.button_pressed,
            "on_button_release": self.button_released,
            "on_open_file": self.open_file,
            "on_save_file": self.save_file,
            "on_save_file_as": self.save_file_as,
            "on_save_template_activate": self.save_template,
            "on_ctrl_scale_value_changed": self.on_ctrl_scale_value_changed,
        }
        self.builder.connect_signals(signals)

        # init openmv
        openmv.init()

        # interrupt any running code
        openmv.stop_script()
        sleep(0.1)
Ejemplo n.º 50
0
    def __init__(self):
        #Set the Glade file
        self.builder = gtk.Builder()
        self.builder.add_from_file("openmv-ide.glade")

        # get top window
        self.window = self.builder.get_object("top_window")

        # status bar stuff
        self.statusbar = self.builder.get_object("statusbar")
        self.statusbar_ctx = self.statusbar.get_context_id("default")

        #save toolbutton
        self.save_button = self.builder.get_object('save_file_toolbutton')
        self.save_button.set_sensitive(False)

        #configure gtksourceview
        sourceview = self.builder.get_object('gtksourceview')
        self.buffer = gtksourceview.Buffer()
        mgr = gtksourceview.style_scheme_manager_get_default()
        style_scheme = mgr.get_scheme('classic')
        if style_scheme:
            self.buffer.set_style_scheme(style_scheme)
        lang_manager = gtksourceview.language_manager_get_default()
        self.buffer.set_highlight_syntax(True)
        self.buffer.set_language(lang_manager.get_language("python"))
        self.buffer.connect("changed", self.text_changed)

        # open last opened file
        if os.path.isfile(config_path):
            with open(config_path, "r") as file:
                self.file_path = file.read()
            if os.path.isfile(self.file_path):
                with open(self.file_path, "r") as file:
                    self.buffer.set_text(file.read())
                    self.window.set_title(os.path.basename(self.file_path))
            else:
                self.file_path = None

        sourceview.set_buffer(self.buffer)

        # open VCP and configure the terminal
        self.terminal = self.builder.get_object('terminal')
        self.fd = os.open("/dev/ttyACM0", os.O_RDWR)
        self.terminal.set_size(80, 24)
        self.terminal.set_pty(self.fd)

        self.framebuffer = self.builder.get_object("framebuffer_image")

        #connect signals
        signals = {
            "on_top_window_destroy": self.quit,
            "on_execute_clicked": self.execute_clicked,
            "on_stop_clicked": self.stop_clicked,
            "on_motion_notify": self.motion_notify,
            "on_button_press": self.button_pressed,
            "on_open_file": self.open_file,
            "on_save_file": self.save_file,
            "on_save_file_as": self.save_file_as,
        }
        self.builder.connect_signals(signals)

        # init openmv
        openmv.init()
Ejemplo n.º 51
0
    def __init__(self, *args, **kwargs):
        # initialize main window
        gtk.Window.__init__(self, *args, **kwargs)
        self._filename = None
        self._data = None

        self._uimanager = gtk.UIManager()

        actiongroup = gtk.ActionGroup('Actions')
        actiongroup.add_actions((
            ('Open', gtk.STOCK_OPEN, None, None, None, self.open_file),
            ('Save', gtk.STOCK_SAVE, None, None, None, self.save_file),
            ('SaveAs', gtk.STOCK_SAVE_AS, None, None, None, self.save_file_as),
            ('Format', gtk.STOCK_INDENT, None, None, None, self.format_data),
        ))
        self._uimanager.insert_action_group(actiongroup, 0)

        self._uimanager.add_ui_from_string(self.ui)
        self._toolbar = self._uimanager.get_widget('/ToolBar')

        accelgroup = self._uimanager.get_accel_group()
        self.add_accel_group(accelgroup)
        self.connect('delete_event', self.quit)
        self.connect('destroy', self.quit)

        self._xdot = MyDotWindow()
        self._xdot.connect('delete_event', self.quit)

        # intialize XML code view
        self._sourcebuf = gtksourceview2.Buffer(
            language=gtksourceview2.language_manager_get_default(
            ).get_language('xml'))
        self._sourceview = gtksourceview2.View(self._sourcebuf)
        self._sourceview.connect('key-press-event', self.keypressevent)
        self._sourceview.connect('key-release-event', self.keyreleaseevent)
        self._sourceview.set_show_line_numbers(True)
        self._sourceview.set_show_line_marks(True)
        self._sourceview.set_auto_indent(True)
        self._sourceview.set_indent_on_tab(True)
        self._sourceview.set_insert_spaces_instead_of_tabs(True)
        self._sourceview.set_tab_width(2)
        self._sourceview.modify_font(pango.FontDescription('Monospace 10'))

        self._sw = gtk.ScrolledWindow()
        self._sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        self._sw.add(self._sourceview)

        # initialize information view
        self._infolabel = gtk.Label()
        self._infolabel.set_line_wrap(True)

        # layout main window
        self._vbox = gtk.VBox()
        self._vbox.pack_start(self._toolbar, False)
        self._vbox.pack_start(self._sw)
        self._vbox.pack_start(self._infolabel, False, False)
        self.add(self._vbox)
        self.set_size_request(400, 400)
        self.resize(600, 520)

        schemafile = os.path.join(basedir, 'seatml.xsd')
        xmlschema_doc = etree.parse(schemafile)
        self._xmlschema = etree.XMLSchema(xmlschema_doc)

        self.update_title()
Ejemplo n.º 52
0
import gtk
import pango
import ascpy
import os

HAVE_SOURCEVIEW = 0
try:
    from gtksourceview2 import Buffer as MyBuffer, View as MyView, language_manager_get_default
    # Ensure that the ascend.lang settings are accessible for gtksourceview

    # TODO move this to ascdev / ascend scripts, it shouldn't be here as
    # it contains assumptions about the filesystem layout.

    mgr = language_manager_get_default()
    _op = mgr.get_search_path()
    if os.path.join('..', 'tools', 'gtksourceview-2.0') not in _op:
        _op.append(os.path.join('..', 'tools', 'gtksourceview-2.0'))
        mgr.set_search_path(_op)
    lang = mgr.get_language('ascend')
    HAVE_SOURCEVIEW = 1
except ImportError, e:
    MyBuffer = gtk.TextBuffer
    MyView = gtk.TextView


class ModuleView:
    def __init__(self, browser, builder, library):
        """Set up the 'modules' tab, set up column types."""

        self.browser = browser
        self.builder = builder
Ejemplo n.º 53
0
    def __init__(self):
        #Set the Glade file
        self.builder = gtk.Builder()
        self.builder.add_from_file(GLADE_PATH)

        # get top window
        self.window = self.builder.get_object("top_window")

        # status bar stuff
        self.statusbar = self.builder.get_object("statusbar")
        self.statusbar_ctx = self.statusbar.get_context_id("default")

        # set buttons
        self.save_button = self.builder.get_object('save_file_toolbutton')
        self.connect_button = self.builder.get_object('connect_button')
        self.exec_button = self.builder.get_object('exec_button')
        self.stop_button = self.builder.get_object('stop_button')

        self.save_button.set_sensitive(False)
        self.exec_button.set_sensitive(False)
        self.stop_button.set_sensitive(False)
        self.connect_button.set_sensitive(True)

        # set control buttons
        self.controls = [
            self.builder.get_object('reset_button'),
            self.builder.get_object('exec_button'),
            self.builder.get_object('zoomin_button'),
            self.builder.get_object('zoomout_button'),
            self.builder.get_object('bestfit_button')
        ]

        self.connected = False
        map(lambda x: x.set_sensitive(False), self.controls)

        # gtksourceview widget
        sourceview = gtksourceview.View()
        lang_manager = gtksourceview.language_manager_get_default()
        style_manager = gtksourceview.style_scheme_manager_get_default()

        # append cwd to style search paths
        style_manager.set_search_path(
            style_manager.get_search_path() +
            [os.path.join(IDE_DIR, "share/gtksourceview-2.0/styles")])

        # append cwd to language search paths
        lang_manager.set_search_path(
            lang_manager.get_search_path() +
            [os.path.join(IDE_DIR, "share/gtksourceview-2.0/language-specs")])

        # configure gtksourceview widget
        sourceview.set_show_line_numbers(True)
        sourceview.set_tab_width(4)
        sourceview.set_indent_on_tab(True)
        sourceview.set_insert_spaces_instead_of_tabs(True)
        sourceview.set_auto_indent(True)
        sourceview.set_highlight_current_line(True)

        fonts = []
        for font in sourceview.get_pango_context().list_families():
            fonts.append(font.get_name().lower())

        if sys.platform.startswith("win"):
            if "consolas" in fonts:
                sourceview.modify_font(pango.FontDescription("consolas 10"))
            else:
                sourceview.modify_font(pango.FontDescription("courier new 10"))
        elif sys.platform.startswith("darwin"):
            if "monaco" in fonts:
                sourceview.modify_font(pango.FontDescription("monaco 10"))
            else:
                sourceview.modify_font(pango.FontDescription("courier new 10"))
        elif sys.platform.startswith("linux"):
            if "dejavu sans mono" in fonts:
                sourceview.modify_font(
                    pango.FontDescription("dejavu sans mono 10"))
            else:
                sourceview.modify_font(pango.FontDescription("courier new 10"))

        # configure gtksourceview buffer
        self.buffer = gtksourceview.Buffer()
        self.buffer.set_highlight_syntax(True)
        self.buffer.set_language(lang_manager.get_language("python"))
        self.buffer.connect("changed", self.text_changed)

        sourceview.set_buffer(self.buffer)
        self.builder.get_object("src_scrolledwindow").add(sourceview)

        # Configure terminal window
        self.terminal_scroll = self.builder.get_object('vte_scrolledwindow')
        self.terminal = self.builder.get_object('vte_textview')
        self.terminal.modify_base(gtk.STATE_NORMAL,
                                  gtk.gdk.color_parse('black'))
        self.terminal.modify_text(gtk.STATE_NORMAL,
                                  gtk.gdk.color_parse('green'))

        # get drawingarea
        self.fb = None
        self.pixbuf = None
        self.drawingarea = self.builder.get_object("drawingarea")
        self.da_menu = self.builder.get_object("da_menu")

        self.fb_enabled = True

        # selection coords
        self.sel_ended = False
        self.selection_started = False
        self.x1 = self.y1 = self.x2 = self.y2 = 0

        # set control scales attributes
        self.builder.get_object("contrast_adjust").attr = openmv.ATTR_CONTRAST
        self.builder.get_object(
            "brightness_adjust").attr = openmv.ATTR_BRIGHTNESS
        self.builder.get_object(
            "saturation_adjust").attr = openmv.ATTR_SATURATION
        self.builder.get_object(
            "gainceiling_adjust").attr = openmv.ATTR_GAINCEILING

        # create data directory
        if not os.path.isdir(DATA_DIR):
            os.makedirs(DATA_DIR)

        # create user scripts directory
        if not os.path.isdir(SCRIPTS_DIR):
            os.makedirs(SCRIPTS_DIR)

        # set config parser
        self.config = configparser.ConfigParser()

        config_valid = True

        # check if config file exists
        if os.path.isfile(CONFIG_PATH):
            try:
                # load config
                self.config.read(CONFIG_PATH)
            except Exception as e:
                print("Failed to open config file %s" % (e))
                sys.exit(1)

            # Check config keys, if one is missing set invalid
            for key in CONFIG_KEYS:
                if not self.config.has_option('main', key):
                    config_valid = False
                    break
        else:
            config_valid = False

        # create fresh config if needed
        if config_valid == False:
            try:
                with open(CONFIG_PATH, "w") as f:
                    f.write(DEFAULT_CONFIG)
            except Exception as e:
                print("Failed to create config file %s" % (e))
                sys.exit(1)

        # load or reload the config file
        try:
            self.config.read(CONFIG_PATH)
        except Exception as e:
            print("Failed to open config file %s" % (e))
            sys.exit(1)

        # Current file path
        self.file_path = None

        # Built-in examples menu
        submenu = gtk.Menu()
        for root, dirs, files in os.walk(EXAMPLES_DIR, topdown=True):
            for dirname in sorted(dirs):
                smenu = gtk.Menu()
                path = os.path.join(root, dirname)
                for f in os.listdir(path):
                    if f.endswith(".py"):
                        label = os.path.basename(f)
                        mitem = gtk.MenuItem(label, use_underline=False)
                        mitem.connect("activate", self.open_example, path)
                        smenu.append(mitem)

                menu = gtk.MenuItem(dirname)
                menu.set_submenu(smenu)
                submenu.append(menu)

        menu = self.builder.get_object('example_menu')
        menu.set_submenu(submenu)

        # recent files menu
        self.files = []
        files = self.config.get("main", "recent")
        if files:
            self.files = files.split(',')
            self.update_recent_files()

        self.baudrate = int(self.config.get("main", "baudrate"))

        # Set firmware version
        self.fw_version = (0, 0, 0)

        # load helloworld.py
        self._load_file(
            os.path.join(EXAMPLES_DIR, "01-Basics", "helloworld.py"))
        self.save_button.set_sensitive(False)

        #connect signals
        signals = {
            "on_top_window_destroy": self.quit,
            "on_connect_clicked": self.connect_clicked,
            "on_reset_clicked": self.reset_clicked,
            "on_execute_clicked": self.execute_clicked,
            "on_stop_clicked": self.stop_clicked,
            "on_bootloader_clicked": self.bootloader_clicked,
            "on_enable_fb_toggled": self.enable_fb_toggled,
            "on_motion_notify": self.motion_notify,
            "on_button_press": self.button_pressed,
            "on_button_release": self.button_released,
            "on_open_file": self.open_file,
            "on_new_file": self.new_file,
            "on_save_file": self.save_file,
            "on_save_file_as": self.save_file_as,
            "on_about_dialog": self.about_dialog,
            "on_pinout_dialog": self.pinout_dialog,
            "on_color_stats_activate": self.color_stats,
            "on_save_template_activate": self.save_template,
            "on_save_descriptor_activate": self.save_descriptor,
            "on_ctrl_scale_value_changed": self.on_ctrl_scale_value_changed,
            "on_zoomin_clicked": self.zoomin_clicked,
            "on_zoomout_clicked": self.zoomout_clicked,
            "on_bestfit_clicked": self.bestfit_clicked,
            "on_preferences_clicked": self.preferences_clicked,
            "on_vte_size_allocate": self.scroll_terminal,
        }
        self.builder.connect_signals(signals)

        # Create bootloader object
        self.bootloader = Bootloader(self.builder, self.config)
Ejemplo n.º 54
0
    def __init__(self, emma):
        """
        @param emma: Emma
        """
        super(QueryTab, self).__init__()
        self.xml = gtk.glade.XML(
            os.path.join(emma.glade_path, 'querytab.glade'), "first_query")
        self.xml.signal_autoconnect(self)

        self.tab_label.set_text('Query')
        self.tab_label_icon.set_from_file(
            os.path.join(icons_path, 'page_code.png'))

        self.emma = emma

        self.save_result = self.xml.get_widget('save_result')
        self.save_result_sql = self.xml.get_widget('save_result_sql')
        self.local_search = self.xml.get_widget('local_search_button')
        self.remove_order = self.xml.get_widget('remove_order')

        self.label = self.xml.get_widget('query_label')

        self.add_record = self.xml.get_widget('add_record_tool')
        self.delete_record = self.xml.get_widget('delete_record_tool')

        self.query_bottom_label = self.xml.get_widget('query_bottom_label')
        self.query_db_label = self.xml.get_widget('query_db_label')

        self.textview = self.xml.get_widget('query_text')

        self.query_text_sw = self.xml.get_widget('query_text_sw')
        self.apply_record = self.xml.get_widget('apply_record_tool')
        self.ui = self.xml.get_widget('first_query')
        self.toolbar = self.xml.get_widget('inner_query_toolbar')
        self.toolbar.set_style(gtk.TOOLBAR_ICONS)

        self.scrolledwindow6 = self.xml.get_widget('scrolledwindow6')
        self.treeview = QueryTabTreeView(emma)
        self.scrolledwindow6.add(self.treeview)
        self.treeview.show()

        self.treeview.get_selection().set_mode(gtk.SELECTION_MULTIPLE)

        self.treeview.connect('cursor_changed',
                              self.on_query_view_cursor_changed)
        # todo: move to keymap
        self.treeview.connect('key_press_event',
                              self.on_query_view_key_press_event)
        self.treeview.connect('button_press_event',
                              self.on_query_view_button_press_event)

        self.execution_timer_running = False
        self.execution_timer_interval = 0
        self.editable = False

        self.sort_timer_running = False
        self.sort_timer_execute = 0

        self.query_encoding_menu = None

        self.filled_fields = []

        # replace textview with gtksourcevice
        try:
            org_tv = self.textview
            manager = gtksourceview2.language_manager_get_default()
            language = manager.get_language("sql")

            sb = gtksourceview2.Buffer()
            sb.set_highlight_syntax(True)
            sb.set_language(language)
            sv = self.textview = gtksourceview2.View(sb)

            self.query_text_sw.remove(org_tv)
            self.query_text_sw.add(sv)
            sv.show()

            sv.set_show_line_numbers(True)
            sv.set_show_line_marks(True)
            sv.set_tab_width(4)
            sv.set_auto_indent(True)
            sv.set_insert_spaces_instead_of_tabs(False)
            sv.set_show_right_margin(True)
            sv.set_smart_home_end(True)
            sv.set_right_margin_position(80)

            # sv config
            # for pt, pn, pd in (
            #     (bool, "show_line_numbers", True),
            #     #(bool, "show_line_markers", False),
            #     #(int, "tabs_width", 4),
            #     (bool, "auto_indent", True),
            #     (bool, "insert_spaces_instead_of_tabs", False),
            #     #(bool, "show_margin", True),
            #     #(int, "margin", 80),
            #     (bool, "smart_home_end", True)
            # ):
            #
            #     cn = "sourceview.%s" % pn
            #     try:
            #         v = self.emma.config[cn]
            #         if pt == bool:
            #             v = v == "1" or v.lower() == "true" or v.lower() == "yes"
            #         else:
            #             v = pt(v)
            #     except:
            #         v = pd
            #     method = getattr(sv, "set_%s" % pn)
            #     method(v)
            # sb config
            # for pt, pn, pd in (
            #     (bool, "check_brackets", True),
            #     (bool, "highlight", True),
            #     (int, "max_undo_levels", 15)
            # ):
            #     cn = "sourceview.%s" % pn
            #     try:
            #         v = self.emma.config[cn]
            #         if pt == bool:
            #             v = v == "1" or v.lower() == "true" or v.lower() == "yes"
            #         else:
            #             v = pt(v)
            #     except:
            #         v = pd
            #     method = getattr(sb, "set_%s" % pn)
            #     method(v)
        except:
            dialogs.alert(traceback.format_exc())

        self.current_host = None
        self.current_db = None
        self.model = None
        self.last_source = None
        self.result_info = None
        self.append_iter = None
        self.last_path = None
        self.encoding = None
        if hasattr(self, "query"):
            self.textview.get_buffer().set_text(self.query)
        self.last_auto_name = None

        #
        #   INIT Query tab actions
        #

        self.remember_order_action = QueryTabRememberOrder(self, emma)
        self.remove_order_action = QueryTabRemoveOrder(self, emma)
        self.set_result_font_action = QueryTabSetResultFont(self, emma)
        self.local_search_action = QueryTabLocalSearch(self, emma)
        self.save_result_sql_action = QueryTabSaveResultSql(self, emma)
        self.save_result_csv_action = QueryTabSaveResultCsv(self, emma)
        self.manage_row_action = QueryTabManageRow(self, emma)

        #
        #
        #

        self.emma.key_map.connect('key-release', self.key_release)
        self.init_from_config()
Ejemplo n.º 55
0
    def __init__(self):
        #Set the Glade file
        self.builder = gtk.Builder()
        self.builder.add_from_file(GLADE_PATH)

        # get top window
        self.window = self.builder.get_object("top_window")

        # status bar stuff
        self.statusbar = self.builder.get_object("statusbar")
        self.statusbar_ctx = self.statusbar.get_context_id("default")

        # set buttons
        self.save_button = self.builder.get_object('save_file_toolbutton')
        self.connect_button = self.builder.get_object('connect_button')

        self.save_button.set_sensitive(False)
        self.connect_button.set_sensitive(True)

        # set control buttons
        self.controls = [
            self.builder.get_object('reset_button'),
            self.builder.get_object('bootloader_button'),
            self.builder.get_object('exec_button'),
            self.builder.get_object('stop_button'),
            self.builder.get_object('zoomin_button'),
            self.builder.get_object('zoomout_button'),
            self.builder.get_object('bestfit_button'),
            self.builder.get_object('refresh_button')]

        self.connected = False
        map(lambda x:x.set_sensitive(False), self.controls)

        #configure gtksourceview
        sourceview = self.builder.get_object('gtksourceview')
        self.buffer = gtksourceview.Buffer()
        mgr = gtksourceview.style_scheme_manager_get_default()
        style_scheme = mgr.get_scheme('classic')
        if style_scheme:
            self.buffer.set_style_scheme(style_scheme)
        lang_manager = gtksourceview.language_manager_get_default()
        self.buffer.set_highlight_syntax(True)
        self.buffer.set_language(lang_manager.get_language("python"))
        self.buffer.connect("changed", self.text_changed)
        sourceview.set_buffer(self.buffer)

        #configure the terminal
        self.fd = -1
        self.terminal = self.builder.get_object('terminal')
        self.terminal.set_size(80,24)

        # get drawingarea
        self.pixbuf = None
        self.drawingarea = self.builder.get_object("drawingarea")
        self.da_menu = self.builder.get_object("da_menu")

        # selection coords
        self.sel_ended=False
        self.selection_started=False
        self.x1 = self.y1 = self.x2 = self.y2 =0

        # set control scales attributes
        self.builder.get_object("contrast_adjust").attr=    openmv.ATTR_CONTRAST
        self.builder.get_object("brightness_adjust").attr=  openmv.ATTR_BRIGHTNESS
        self.builder.get_object("saturation_adjust").attr=  openmv.ATTR_SATURATION
        self.builder.get_object("gainceiling_adjust").attr= openmv.ATTR_GAINCEILING

        #connect signals
        signals = {
            "on_top_window_destroy"         : self.quit,
            "on_connect_clicked"            : self.connect_clicked,
            "on_reset_clicked"              : self.reset_clicked,
            "on_fwupdate_clicked"           : self.fwupdate_clicked,
            "on_fwpath_clicked"             : self.fwpath_clicked,
            "on_execute_clicked"            : self.execute_clicked,
            "on_stop_clicked"               : self.stop_clicked,
            "on_motion_notify"              : self.motion_notify,
            "on_button_press"               : self.button_pressed,
            "on_button_release"             : self.button_released,
            "on_open_file"                  : self.open_file,
            "on_new_file"                   : self.new_file,
            "on_save_file"                  : self.save_file,
            "on_save_file_as"               : self.save_file_as,
            "on_save_template_activate"     : self.save_template,
            "on_save_descriptor_activate"   : self.save_descriptor,
            "on_ctrl_scale_value_changed"   : self.on_ctrl_scale_value_changed,
            "on_zoomin_clicked"             : self.zoomin_clicked,
            "on_zoomout_clicked"            : self.zoomout_clicked,
            "on_bestfit_clicked"            : self.bestfit_clicked,
            "on_updatefb_clicked"           : self.updatefb_clicked,
        }
        self.builder.connect_signals(signals)

        # create fresh config if needed
        if not os.path.isfile(CONFIG_PATH):
            try:
                with open(CONFIG_PATH, "w") as f:
                    f.write(DEFAULT_CONFIG)
            except Exception as e:
                print ("Failed to create config file %s"%(e))
                sys.exit(1)

        # load config
        self.config = configparser.ConfigParser()
        try:
            self.config.read(CONFIG_PATH)
        except Exception as e:
            print ("Failed to open config file %s"%(e))
            sys.exit(1)

        # current file path
        self.file_path= None
        self.fw_file_path=""
#        path = self.config.get("main", "last_opened_file")
#        if os.path.isfile(path):
#            self._load_file(path)

        # built-in examples menu
        if os.path.isdir(EXAMPLE_PATH):
            submenu = gtk.Menu()
            menu = self.builder.get_object('example_menu')
            files = sorted(os.listdir(EXAMPLE_PATH))
            for f in files:
                if f.endswith(".py"):
                    label = os.path.basename(f)
                    mitem = gtk.MenuItem(label)
                    mitem.connect("activate", self.open_example, EXAMPLE_PATH)
                    submenu.append(mitem)

            menu.set_submenu(submenu)

        # recent files menu
        self.files = []
        files =self.config.get("main", "recent")
        if files:
            self.files = files.split(',')
            self.update_recent_files()
Ejemplo n.º 56
0
class HotEditorWindow(gtk.Window):
    def __init__(self,
                 filename=None,
                 content=None,
                 title=None,
                 parent=None,
                 autosave=False):
        gtk.Window.__init__(self, type=gtk.WINDOW_TOPLEVEL)
        vbox = gtk.VBox()
        self.add(vbox)
        self.__ui_string = """
<ui>
  <menubar name='Menubar'>
    <menu action='FileMenu'>
      <menuitem action='Save'/>
      <menuitem action='SaveAs'/>
      <separator/>
      <menuitem action='ReadOnly'/>
      <separator/>
      <menuitem action='Revert'/>
      <separator/>
      <menuitem action='Close'/>
    </menu>
    <menu action='EditMenu'>
      <menuitem action='Undo'/>
      <menuitem action='Redo'/>
      <separator/>
      <menuitem action='Find'/>
      <menuitem action='GotoLine'/>
    </menu>
    <menu action='ToolsMenu'>
      <menuitem action='About'/>
    </menu>
  </menubar>
</ui>
"""
        self.__create_ui()
        vbox.pack_start(self._ui.get_widget('/Menubar'), expand=False)

        self.__filename = os.path.abspath(filename)
        self.__autosave = autosave
        self.__modified = False
        self.__last_len = 0

        self.__save_text_id = 0

        self.gtksourceview_mode = gtksourceview_avail

        if gtksourceview_avail:
            self.input = SourceBuffer()
            self.input_view = SourceView(self.input)
            if gtksourceview2_avail:
                self.input.connect('notify::can-undo',
                                   lambda *args: self.__sync_undoredo())
                self.input.connect('notify::can-redo',
                                   lambda *args: self.__sync_undoredo())
            else:
                self.input.connect('can-undo',
                                   lambda *args: self.__sync_undoredo())
                self.input.connect('can-redo',
                                   lambda *args: self.__sync_undoredo())
        else:
            self.input = gtk.TextBuffer()
            self.input_view = gtk.TextView(self.input)
        self.input_view.set_wrap_mode(gtk.WRAP_WORD)
        self.input_view.connect("key-press-event",
                                self.__handle_key_press_event)

        scroll = gtk.ScrolledWindow()
        scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)
        scroll.add(self.input_view)

        vbox.pack_start(scroll, True, True)

        if filename and os.path.isfile(self.__filename):
            _logger.debug("reading %s", self.__filename)
            f = open_text_file(self.__filename, 'r')
            self.__original_text = f.read()
        else:
            self.__original_text = content

        if self.__original_text:
            if gtksourceview_avail:
                self.input.begin_not_undoable_action()
            self.input.set_property('text', self.__original_text)
            self.__last_len = self.input.get_char_count()
            if gtksourceview_avail:
                self.input.end_not_undoable_action()

        self.input.move_mark_by_name('insert', self.input.get_start_iter())
        self.input.move_mark_by_name('selection_bound',
                                     self.input.get_start_iter())

        self.input.connect('mark-set', self.__on_mark_set)

        self.__searcharea = InlineSearchArea(self.input_view)
        self.__searcharea.connect('close', self.__on_search_close)
        self.__searcharea.show_all()
        self.__searcharea.hide()
        self.__searcharea.set_no_show_all(True)
        vbox.pack_start(self.__searcharea, expand=False)

        self.__status_hbox = gtk.HBox()
        self.__statusbar = gtk.Statusbar()
        self.__status_hbox.pack_start(self.__statusbar, expand=True)
        self.__statusbar_ctx = self.__statusbar.get_context_id("HotEditor")
        self.__pos_status = gtk.Statusbar()
        self.__pos_status.set_size_request(160, 10)  # Taken from GEdit
        self.__pos_context = self.__pos_status.get_context_id("HotEditor")
        self.__status_hbox.pack_start(self.__pos_status, expand=False)
        vbox.pack_start(self.__status_hbox, expand=False)
        self.__sync_undoredo()
        self.__sync_modified_sensitivity()

        self.input.connect("changed", self.__handle_text_changed)

        self.connect("delete-event", self.__handle_delete_event)
        self.__sync_title()
        if parent:
            self.set_transient_for(parent)
        self.set_size_request(800, 600)

    def __on_search_close(self, sa):
        self.__searcharea.hide()

    def set_read_only(self, readonly):
        readonly_toggle = self.__actiongroup.get_action('ReadOnly')
        readonly_toggle.set_active(readonly)

    def set_code_mode(self, codemode):
        if not self.gtksourceview_mode:
            return
        # Non-code is the default
        if not codemode:
            return
        self.input_view.modify_font(pango.FontDescription("monospace"))
        fs = Filesystem.getInstance()
        try:
            mimetype = fs.get_file_sync(self.__filename).mimetype
        except FileStatError, e:
            mimetype = None
        target_lang = None
        if gtksourceview2_avail:
            import gtksourceview2
            langman = gtksourceview2.language_manager_get_default()
            for language_id in langman.get_language_ids():
                language = langman.get_language(language_id)
                for langmime in language.get_mime_types():
                    if mimetype == langmime:
                        target_lang = language
                        break
                if target_lang:
                    break
            self.input.set_highlight_syntax(True)
        else:
            import gtksourceview
            target_lang = gtksourceview.SourceLanguagesManager(
            ).get_language_from_mime_type(mimetype)
            self.input.set_highlight(True)
        if target_lang:
            self.input.set_language(target_lang)