示例#1
0
	def initialize_app(self):
		'''
		Load the gui elements from the builder
		'''
		
		self.window = self.builder.get_object("main_window")
		self.window.set_title(__application__)
		self.window.show_all()
		
		if not os.path.exists(os.path.expanduser('~/.gthemer/')):
			os.makedirs(os.path.expanduser('~/.gthemer/'))
		self.sourceview_styles = GThemerDB(__db_path__)
		# Generate language_combo
		self.language_combo = self.builder.get_object("language_combo")
		self.language_combo.set_model(None)
		self.build_language_combo()
		self.styles_combo = self.builder.get_object("styles_combo")
		scrolled_window = self.builder.get_object("scrolledwindow")
		self.name_entry = self.builder.get_object("name_entry")
		self.id_entry = self.builder.get_object("id_entry")
		self.author_entry = self.builder.get_object("author_entry")
		self.version_entry = self.builder.get_object("version_entry")
		self.description_entry = self.builder.get_object("description_entry")
		# Create TreeView
		self.styles_treeview = StylesTreeView()
		self.styles_treeview._setup_columns()
		self.styles_treeview.show_all()
		scrolled_window.add(self.styles_treeview)
		# Initialize treemodel
		styles_model = Gtk.TreeStore(str, str, str, str, str, bool, bool, bool, bool, bool)
		self.styles_treeview.set_model(styles_model)
		self.styles_interface = StylesTreeStoreInterface(styles_model, self.sourceview_styles)
		self.styles_treeview.styles = self.styles_interface.styles_rows
		# Setup globals
		self.styles_interface.init_globals()
示例#2
0
class MainWindow():
	'''
	The main window of GThemer
	'''	
	def __init__(self, ui_file):	
		builder = self.builder = Gtk.Builder()
		builder.add_from_file(ui_file)
		builder.add_from_file(__about_dialog__)
		builder.connect_signals(self)
		self.filename = None

	def initialize_app(self):
		'''
		Load the gui elements from the builder
		'''
		
		self.window = self.builder.get_object("main_window")
		self.window.set_title(__application__)
		self.window.show_all()
		
		if not os.path.exists(os.path.expanduser('~/.gthemer/')):
			os.makedirs(os.path.expanduser('~/.gthemer/'))
		self.sourceview_styles = GThemerDB(__db_path__)
		# Generate language_combo
		self.language_combo = self.builder.get_object("language_combo")
		self.language_combo.set_model(None)
		self.build_language_combo()
		self.styles_combo = self.builder.get_object("styles_combo")
		scrolled_window = self.builder.get_object("scrolledwindow")
		self.name_entry = self.builder.get_object("name_entry")
		self.id_entry = self.builder.get_object("id_entry")
		self.author_entry = self.builder.get_object("author_entry")
		self.version_entry = self.builder.get_object("version_entry")
		self.description_entry = self.builder.get_object("description_entry")
		# Create TreeView
		self.styles_treeview = StylesTreeView()
		self.styles_treeview._setup_columns()
		self.styles_treeview.show_all()
		scrolled_window.add(self.styles_treeview)
		# Initialize treemodel
		styles_model = Gtk.TreeStore(str, str, str, str, str, bool, bool, bool, bool, bool)
		self.styles_treeview.set_model(styles_model)
		self.styles_interface = StylesTreeStoreInterface(styles_model, self.sourceview_styles)
		self.styles_treeview.styles = self.styles_interface.styles_rows
		# Setup globals
		self.styles_interface.init_globals()
		
	def open_about_dialog(self, widget):
		'''
		Open the About Dialog.
		'''
		dialog = self.builder.get_object("aboutdialog")
		text_view = self.builder.get_object("about_textview")
		text_buffer = Gtk.TextBuffer()
		text_buffer.set_text(open(__about_file__, 'rb').read())
		text_view.set_buffer(text_buffer)
		dialog.run()
		dialog.destroy()
		
	def open_file_dialog(self):
		'''
		When the filename icon is clicked on, open the file chooser dialog that
		will determine the file.
		'''
		dialog = Gtk.FileChooserDialog(title="Choose a File",
							 	 	   parent=self.window,
							 	 	   action=Gtk.FileChooserAction.SAVE,
							 	 	   buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
							 	 	   			Gtk.STOCK_OPEN, Gtk.ResponseType.ACCEPT))
		xml_file_filter = Gtk.FileFilter()
		xml_file_filter.add_pattern("*.xml")
		xml_file_filter.set_name("XML Files")
		dialog.add_filter(xml_file_filter)
		if self.filename is None:
			dialog.set_current_name("Untitled.xml")
			dialog.set_do_overwrite_confirmation(True)
		else:
			dialog.set_current_name(self.filename)
		response = dialog.run()
		if response == Gtk.ResponseType.ACCEPT:
			# Get the file name that is currently in the 
			filename = dialog.get_filename()
			self.window.set_title(__application__ + " - " + filename)
			dialog.destroy()
			return filename
		elif response == Gtk.ResponseType.CANCEL:
			dialog.destroy()
			return None
		else:
			dialog.destroy()
			return None

	def build_language_combo(self, languages=None):
		'''
		Retrieve languages from the SourceviewStyles or from an existing file
		and update the language combo
		'''
		self.language_combo.set_model(None)
		model = Gtk.ListStore(str, str)
		if languages is None:
			# Get languages from SourceviewStyles
			for language in sorted(self.sourceview_styles.iter_languages()):
				model.append([language[1], language[0]])
			self.language_combo.set_model(model)
		else:
			# Get languages extracted from file.
			pass

	def on_language_combo_changed(self, widget):
		'''
		This callback is fired whenever a language is selected from the language
		combo. When a language is selected, the styles associated with that
		language is updated in the styles_combo
		'''
		current_language = self.language_combo.get_model()[self.language_combo.get_active_iter()][1]
		if current_language not in [x[0] for x in self.sourceview_styles.iter_languages()]:
			print("Error! {} is NOT defined in SourceviewStyles".format(repr(current_language)))
		else:
			self.styles_combo.remove_all()
			styles = self.sourceview_styles.iter_styles(language=current_language)
			for style in sorted(styles):
				self.styles_combo.append_text(str(style['style']))

	def add_group(self, widget):
		'''
		When the Add Lang button is clicked, add all the definitions for 
		the chosen language to the StylesTreeView if they don't exist
		'''
		model = self.language_combo.get_model()
		current_iter = self.language_combo.get_active_iter()
		lang_title = model[current_iter][0]
		lang_name = model[current_iter][1]
		self.styles_interface.add_group(lang_name,
										lang_title,
										sorted(name['style'] for name in self.sourceview_styles.iter_styles(lang_name)))

	def add_style(self, widget):
		'''
		When the Add Style button is clicked, add the selected definition to
		the StylesTreeView if the definition isn't already in the TreeView.
		'''
		model = self.language_combo.get_model()
		lang = model[self.language_combo.get_active_iter()][0]
		style = self.styles_combo.get_active_text()
		self.styles_interface.add_style(lang, style)

	def on_delete_event(self, widget, event):
		Gtk.main_quit()

	def on_quit(self, widget):
		'''
		Exit the application when Quit button is pressed
		'''
		self.window.destroy()
		Gtk.main_quit()

	def load_file(self, widget, data=None):
		'''
		This callback is fired when the "Open" Gtk.MenuItem is activated. This
		method opens a filechooser dialog to choose an xml file and then load
		its contents into the treeview.
		'''
		dialog = Gtk.FileChooserDialog(title=None,
							 	 	   parent=None,
							 	 	   action=Gtk.FileChooserAction.OPEN,
							 	 	   buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
							 	 	   			Gtk.STOCK_OPEN, Gtk.ResponseType.ACCEPT))
		xml_file_filter = Gtk.FileFilter()
		xml_file_filter.add_pattern("*.xml")
		xml_file_filter.set_name("XML Files")
		dialog.add_filter(xml_file_filter)
		response = dialog.run()
		if response == Gtk.ResponseType.ACCEPT:
			filename = dialog.get_filename()
			print("Opening file: {}".format(filename))
			dialog.destroy()
			generator = StyleGenerator()
			try:
				info, styles = generator.parse_file(filename, self.sourceview_styles)
			except ParseError:
				traceback.print_exc()
				# Open a dialog that says it failed to parse.
				return
			except Exception as e:
				traceback.print_exc()
				# Open a dialog that says it failed to parse.
				return
			# Set the info pane
			#self.filename_entry.set_text(filename)
			self.window.set_title(__application__ + " - " + filename)
			self.name_entry.set_text(info['name'])
			self.id_entry.set_text(info['id'])
			self.author_entry.set_text(info['author'])
			self.version_entry.set_text(info['version'])
			self.description_entry.set_text(info['description'])
			self.styles_interface.treestore.clear()
			self.styles_interface.styles_rows = {}
			# Set styles
			for lang, config in sorted(styles.iteritems()):
				if lang == '__globals':
					# Add globals to the StylesTreeView
					for scheme, conf in config.iteritems():
						row = self.format_row(conf, scheme)
						config[scheme] = row
					self.styles_interface.init_globals(globals_defaults=config)
				else:
					language = config['name']
					styles = config['styles']
					for scheme, style in styles.iteritems():
						row = self.format_row(style, scheme)
						self.styles_interface.add_style(language, scheme, row)
		else:
			dialog.destroy()

	def format_row(self, config, scheme):
		'''
		Format values for use in the StylesTreeView.
		
		*config* (``dict``) of attributes to set.
		'''
		color_cols = {
			'background': 'background_display',
			'foreground': 'foreground_display',
		}
		bool_cols = ('italic', 'bold', 'underline', 'strikethrough')
		markup_cols = ('background', 'foreground') + bool_cols
		new_config = {}
		for col_name, col_value in config.iteritems():
			if col_name in bool_cols:
				new_config[col_name] = True if col_value.lower() == 'true' else False
		
			elif col_name in color_cols:
				text = config[col_name]
				display_text = '<span background="{text}">{text}</span>'.format(text=text) if text else ""
				new_config[color_cols[col_name]] = display_text
				new_config[col_name + "_data"] = text
		new_keys = {}
		for key, value in new_config.iteritems():
			new_keys[key] = value
		markup = "<span"
		if new_keys['foreground_data'] not in (None, ""):
			markup += ' foreground="{}" '.format(new_keys['foreground_data'])
		if new_keys['background_data'] not in (None, ""):
			markup += ' background="{}" '.format(new_keys['background_data'])
		if new_keys['bold'] == True:
			markup += ' weight="bold" '
		if new_keys['italic'] == True:
			markup += ' style="italic" '
		if new_keys['underline'] == True:
			markup += ' underline="single" '
		if new_keys['strikethrough'] == True:
			markup += ' strikethrough="true" '
		markup += ">{}</span>".format(scheme)
		new_keys['definition'] = markup	
		return new_keys

	def on_new(self, widget):
		'''
		When the "New" button is pressed, clear the current contents of the
		application.
		'''
		self.styles_interface.styles_rows = {}
		self.styles_interface.treestore.clear()
		self.filename = None
		self.styles_interface.init_globals()
		self.window.set_title(__application__)
		self.name_entry.set_text("")
		self.id_entry.set_text("")
		self.author_entry.set_text("")
		self.description_entry.set_text("")

	def on_save(self, widget):
		'''
		When the save button is pressed, a filechooser dialog is created, asking
		the user to choose a file. That file is overwritten with the new information.
		'''
		if self.filename:
			self._save_file()
		else:
			self.on_save_as(widget)

	def on_save_as(self, widget):
		'''
		When that save as button is pressed, a filechooser dialog is created, asking
		the user to choose a filename to save the theme to. That file is overwritten
		with the new information.
		'''
		filename = self.open_file_dialog()
		if filename:
			self.filename = filename
			self._save_file()

	def _save_file(self):
		'''
		Save the theme to the current filepath in `self.filename`
		'''
		# Build the styles dict based on the styles that are laid out in the
		# StylesTreeView.
		styles_object = self.styles_interface.treestore
		generator = StyleGenerator()
		info = self. get_info()
		generator.add_info(info['id'], info['name'], 
						   author=info['author'],
						   description=info['description'],
						   version=info['version'])	
		generator.add_styles(styles_object)
		print etree.tostring(generator.tree.getroot(), pretty_print=True)
		generator.save_file(info['filename'])

	def get_info(self):
		'''
		Get text from the textboxes. Returns a dict of all the values
		info_dict = {
			'filename': '',
			'name': '',
			'id': '',
			'author': '',
			'version': '',
			'description': '',			
		}
		'''
		info_dict = {}
		info_dict['filename'] = self.filename
		info_dict['name'] = self.name_entry.get_text()
		info_dict['id'] = self.id_entry.get_text()
		info_dict['author'] = self.author_entry.get_text()
		info_dict['version'] = self.version_entry.get_text()
		info_dict['description'] = self.description_entry.get_text()
		return info_dict