def create_base_schema(): log.info('Creating base schema') create_log.info("SCHEMA") # Functions functions = environ.find_resource('sql', 'functions.sql') if db_settings.execute_sql(functions) != 0: error(u'Failed to create functions') # A Base schema shared between all RDBMS implementations schema = _get_latest_schema() if db_settings.execute_sql(schema) != 0: error(u'Failed to create base schema') try: schema = environ.find_resource('sql', '%s-schema.sql' % db_settings.rdbms) if db_settings.execute_sql(schema) != 0: error(u'Failed to create %s specific schema' % (db_settings.rdbms, )) except EnvironmentError: pass migration = StoqlibSchemaMigration() migration.apply_all_patches()
def __init__(self, image): self._image = image path = environ.find_resource('images', 'Throbber-small.png') self._image.set_from_file(path) self._static_image = self._image.get_pixbuf() path = environ.find_resource('images', 'Throbber-small.gif') self._animation = gtk.gdk.PixbufAnimation(path)
def get_uri(self): if locale.getlocale()[0] == 'pt_BR' or platform.system() == 'Windows': content = environ.find_resource('html', 'welcome-pt_BR.html') else: content = environ.find_resource('html', 'welcome.html') if api.sysparam(api.get_default_store()).DEMO_MODE: content += '?demo-mode' return 'file:///' + content
def _open_glade(view, gladefile, domain): if not gladefile: raise ValueError("A gladefile wasn't provided.") elif not isinstance(gladefile, basestring): raise TypeError( "gladefile should be a string, found %s" % type(gladefile)) if gladefile.endswith('.ui'): directory = os.path.dirname(namedAny(view.__module__).__file__) gladefile = os.path.join(directory, gladefile) else: filename = os.path.splitext(os.path.basename(gladefile))[0] try: gladefile = environ.find_resource("glade", filename + '.glade') except EnvironmentError: gladefile = environ.find_resource("glade", filename + '.ui') fp = open(gladefile) sniff = fp.read(200) fp.close() if '<interface' in sniff: WidgetTree = _get_builder() loader_name = 'builder' # glade-2: <!DOCTYPE glade-interface SYSTEM "http://glade.gnome.org/glade-2.0.dtd"> # glade-3: <!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd"> elif 'glade-2.0.dtd' in sniff: WidgetTree = _get_libglade() loader_name = 'libglade' elif 'gaxml-0.1.dtd' in sniff: WidgetTree = _get_gaxml() loader_name = 'gaxml' # gazpacho: <!DOCTYPE glade-interface SYSTEM "http://gazpacho.sicem.biz/gazpacho-0.1.dtd"> elif 'gazpacho-0.1.dtd' in sniff: WidgetTree = _get_gazpacho() loader_name = 'gazpacho.loader' else: log.warning("Could not determine type/dtd of gladefile %s" % gladefile) # Defaulting to builder WidgetTree = _get_builder() loader_name = 'builder' # None means, failed to import if WidgetTree is None: raise RuntimeError( "Could not find %s, it needs to be installed to " "load the gladefile %r" % (loader_name, gladefile)) return WidgetTree(view, gladefile, domain)
def setup_sourceview(self): """ Setup the source editor. """ self.buffer = gtksourceview.Buffer() tagtable = self.buffer.get_tag_table() setup_tags(tagtable) lang_manager = gtksourceview.LanguageManager() lang = lang_manager.get_language('python') self.buffer.set_language(lang) self.editor = gtksourceview.View(self.buffer) accel_group = gtk.AccelGroup() self.get_toplevel().add_accel_group(accel_group) self.editor.add_accelerator("paste-clipboard", accel_group, ord('v'), gtk.gdk.CONTROL_MASK, 0) self.editor.add_accelerator("copy-clipboard", accel_group, ord('c'), gtk.gdk.CONTROL_MASK, 0) self.editor.add_accelerator("cut-clipboard", accel_group, ord('x'), gtk.gdk.CONTROL_MASK, 0) self.editor.set_left_margin(5) self.editor.set_right_margin(5) self.editor.set_show_line_marks(True) self.editor.set_show_line_numbers(True) self.editor.set_auto_indent(True) self.editor.set_insert_spaces_instead_of_tabs(True) self.editor.set_highlight_current_line(True) self.editor.set_indent_width(4) self.editor.set_indent_on_tab(True) path = environ.find_resource('images', 'red-warning.png') high = gtk.gdk.pixbuf_new_from_file(path) path = environ.find_resource('images', 'violet-warning.png') medium = gtk.gdk.pixbuf_new_from_file(path) path = environ.find_resource('images', 'yellow-warning.png') low = gtk.gdk.pixbuf_new_from_file(path) self.icons["low"] = low self.icons["warning"] = medium self.icons["error"] = high self.editor.set_mark_category_pixbuf('error', high) self.editor.set_mark_category_pixbuf('warning', medium) self.editor.set_mark_category_pixbuf('low', low) self.view.scrolledwindow1.add(self.editor)
def _about_cb(self, action): about = gtk.AboutDialog() about.set_name('Gazpacho') about.set_version(__version__) authorsfile = file(environ.find_resource('doc', 'AUTHORS')) authors = [a.strip() for a in authorsfile.readlines()] authors.append('') # separate authors from contributors contributorsfile = file(environ.find_resource('doc', 'CONTRIBUTORS')) authors.extend([c.strip() for c in contributorsfile.readlines()[:-2]]) about.set_authors(authors) license = file('/usr/share/common-licenses/LGPL-2').read() about.set_license(license) about.set_website('http://gazpacho.sicem.biz') about.run() about.destroy()
def __init__(self, **kwargs): # Informações gerais self.especie_documento = "" self.instrucoes = [] # Cedente (empresa - dados do banco) self.agencia = "" self.carteira = "" self.cedente = "" self.conta = "" # Sacado (cliente) self.sacado_nome = "" self.sacado_cidade = "" self.sacado_uf = "" self.sacado_endereco = "" self.sacado_bairro = "" self.sacado_cep = "" # Pagamento self.data_documento = "" self.data_processamento = datetime.date.today() self.data_vencimento = "" self.demonstrativo = [] if (not 'numero_documento' in kwargs and 'nosso_numero' in kwargs): kwargs['numero_documento'] = kwargs['nosso_numero'] for key, value in kwargs.items(): setattr(self, key, value) self.logo_image_path = "" if self.logo: self.logo_image_path = environ.find_resource('pixmaps', self.logo)
def add_delegate(self, delegate, attr): from kiwi.environ import environ from kiwi.ui.builderloader import BuilderWidgetTree import gtk if not delegate.gladefile: return f = environ.find_resource('glade', delegate.gladefile + '.ui') tree = BuilderWidgetTree(delegate, f, None) t = '' t += 'import kiwi\n' t += 'class %s(object):\n' % (attr, ) for widget in sorted(tree.get_widgets()): try: name = gtk.Buildable.get_name(widget) except TypeError: continue t += ' %s = %s.%s()\n' % (name, widget.__module__, widget.__class__.__name__) print t real_node = self.module[attr] self.module.body.remove(real_node) print vars(self.module) nodes = self.builder.string_build(t) for key, value in nodes.items(): self.module.locals[key] = [value] self.module.body.append(value) new_node = self.module.locals[attr][0] for key, value in real_node.locals.items(): print key new_node[key] = [value]
def _selector_new(self): """Return a new selector. The selector is a button used to switch between "widget selection" and "widget add" mode. This makes the cursor look change. When no widget is selected in the notebook then the selector button is pressed. """ hbox = gtk.HBox() # The selector is part of the widgets_button_group, so that when # no widget is selected, its button is pressed. self._selector = gtk.RadioButton(None) self._selector.set_name('Selector') self._selector.set_mode(False) self._selector.set_relief(gtk.RELIEF_NONE) # Each widget in a section has a button in the palette. This is the # button group, since only one may be pressed. self._widgets_button_group = self._selector.get_group() image = gtk.Image() image.set_from_file(environ.find_resource('pixmap', 'selector.png')) self._selector.add(image) self._selector.connect('toggled', self._on_button_toggled) # A label which contains the name of the class currently selected or # "Selector" if no widget class is selected self._label = gtk.Label(_('Selector')) self._label.set_alignment(0.0, 0.5) hbox.pack_start(self._selector, False, False) hbox.pack_start(self._label, padding=2) hbox.show_all() return hbox
def _read_resource(self, domain, name): try: data = environ.get_resource_string('stoq', domain, name) if data: return data except EnvironmentError: pass license = environ.find_resource(domain, name + '.gz') return gzip.GzipFile(license).read()
def _read_resource(self, domain, name): try: data = environ.get_resource_string("stoq", domain, name) if data: return data except EnvironmentError: pass license = environ.find_resource(domain, name + ".gz") return gzip.GzipFile(license).read()
def create_database_functions(): """Create some functions we define on the database This will simply read data/sql/functions.sql and execute it """ with tempfile.NamedTemporaryFile(suffix='stoqfunctions-') as tmp_f: with open(environ.find_resource('sql', 'functions.sql')) as f: tmp_f.write(render_template_string(f.read())) tmp_f.flush() if db_settings.execute_sql(tmp_f.name) != 0: error(u'Failed to create functions')
def testPNGFromString(self): if sys.platform == "win32": return file_name = environ.find_resource("pixmap", "validation-error-16.png") f = file(file_name) png_string = f.read() f.close() pixbuf = self.conv.from_string(png_string) self.assertEqual(pixbuf.get_width(), 17) self.assertEqual(pixbuf.get_height(), 17)
def _open_glade(view, gladefile, domain): if not gladefile: raise ValueError("A gladefile wasn't provided.") elif not isinstance(gladefile, basestring): raise TypeError( "gladefile should be a string, found %s" % type(gladefile)) if gladefile.endswith('.ui'): directory = os.path.dirname(namedAny(view.__module__).__file__) gladefile = os.path.join(directory, gladefile) else: filename = os.path.splitext(os.path.basename(gladefile))[0] gladefile = environ.find_resource("glade", filename + '.glade') fp = open(gladefile) sniff = fp.read(200) fp.close() # glade-2 #<?xml version="1.0" standalone="no"?> <!--*- mode: xml -*--> #<!DOCTYPE glade-interface SYSTEM "http://glade.gnome.org/glade-2.0.dtd"> # glade-3 # <?xml version="1.0" encoding="UTF-8" standalone="no"?> # <!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd"> if '<interface' in sniff: if not hasattr(gtk, 'Builder'): raise AssertionError( "PyGTK 2.12 or higher is required for builder support") WidgetTree = _get_builder() loader_name = 'builder' elif 'glade-2.0.dtd' in sniff: WidgetTree = _get_libglade() loader_name = 'libglade' elif 'gaxml-0.1.dtd' in sniff: WidgetTree = _get_gaxml() loader_name = 'gaxml' else: # gazpacho: #<?xml version="1.0" standalone="no"?> <!--*- mode: xml -*--> #<!DOCTYPE glade-interface SYSTEM "http://gazpacho.sicem.biz/gazpacho-0.1.dtd"> if not 'gazpacho-0.1.dtd' in sniff: log.warning("Could not determine type/dtd of gladefile %s" % gladefile) WidgetTree = _get_gazpacho() loader_name = 'gazpacho.loader' # None means, failed to import if WidgetTree is None: raise RuntimeError( "Could not find %s, it needs to be installed to " "load the gladefile %s" % (loader_name, gladefile)) return WidgetTree(view, gladefile, domain)
def populate_initial_data(store): from stoqlib.domain.system import SystemTable generation = store.find(SystemTable).max(SystemTable.generation) if generation < 4: # FIXME: Initial data can (and needs to) only be sourced on schemas # greater or equal than 4. Remove this in the future. return log.info('Populating initial data') initial_data = environ.find_resource('sql', 'initial.sql') if db_settings.execute_sql(initial_data) != 0: error(u'Failed to populate initial data')
def register_stock_icons(): """ Register the custom stock icons used by gazpacho """ icon_factory = None for fname, stock_id in [('gazpacho-icon.png', MISSING_ICON), ('sizegroup-both.png', STOCK_SIZEGROUP)]: filename = environ.find_resource('pixmap', fname) icon_factory = create_stock_icon(filename, stock_id, icon_factory) icon_factory.add_default()
def load_taxes_csv(): # Avoid load taxes more than once. if taxes_data: return filename = environ.find_resource('csv', 'tabela_ibpt.csv') csv_file = (csv.reader(open(filename, "r"))) for (ncm, ex, tabela, nac, imp, __) in csv_file: if tabela == '1': continue tax_dict = taxes_data.setdefault(ncm, {}) tax_dict[ex] = (nac, imp)
def testButtonPixbuf(self): if sys.platform == 'win32': return conv = converter.get_converter(gdk.Pixbuf) filename = environ.find_resource('pixmap', 'validation-error-16.png') pixbuf = gdk.pixbuf_new_from_file(filename) self.assertEqual(self.view.buttonpixbuf.data_type, 'Pixbuf') self.view.buttonpixbuf.update(pixbuf) self.assertEqual(type(self.view.buttonpixbuf.read()), gdk.Pixbuf) self.assertEqual(conv.as_string(self.model.buttonpixbuf), conv.as_string(pixbuf)) self.view.buttonpixbuf.update(None) self.assertEqual(self.view.buttonpixbuf.read(), None) self.assertEqual(self.model.buttonpixbuf, None)
def testPNGAsString(self): if sys.platform == "win32": return file_name = environ.find_resource("pixmap", "validation-error-16.png") f = file(file_name) png_string = f.read() f.close() pixbuf = self.conv.from_string(png_string) string = self.conv.as_string(pixbuf) # XXX Not always equal. need to investigate # self.assertEqual(string, png_string) # Compare png header self.assertEqual(string[0:8], "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a")
def get_banks(self): configfile = self.__module__.split('.')[-2] + '.ini' config = ConfigParser() filename = environ.find_resource("conf", configfile) if not config.read(filename): return None for section in config.sections(): # With this, we'll have a dictionary in this format: # CONFIG_NAME: "Y,X" items = dict(config.items(section)) try: bank = self._parse_bank(items) except ConfigError, errmsg: raise ConfigError("In section `%s' of `%s': %s" % (section, filename, errmsg)) self._banks[int(section)] = bank
def _open_glade(view, gladefile, domain): if not gladefile: raise ValueError("A gladefile wasn't provided.") elif not isinstance(gladefile, basestring): raise TypeError("gladefile should be a string, found %s" % type(gladefile)) if not os.path.sep in gladefile: filename = os.path.splitext(os.path.basename(gladefile))[0] gladefile = environ.find_resource("glade", filename + '.glade') else: # environ.find_resources raises EnvironmentError if the file # is not found, do the same here. if not os.path.exists(gladefile): raise EnvironmentError("glade file %s does not exist" % (gladefile, )) return FluLibgladeWidgetTree(view, gladefile, domain)
def _open_glade(view, gladefile, domain): if not gladefile: raise ValueError("A gladefile wasn't provided.") elif not isinstance(gladefile, basestring): raise TypeError( "gladefile should be a string, found %s" % type(gladefile)) if not os.path.sep in gladefile: filename = os.path.splitext(os.path.basename(gladefile))[0] gladefile = environ.find_resource("glade", filename + '.glade') else: # environ.find_resources raises EnvironmentError if the file # is not found, do the same here. if not os.path.exists(gladefile): raise EnvironmentError("glade file %s does not exist" % ( gladefile, )) return FluLibgladeWidgetTree(view, gladefile, domain)
def add_button(self, label, stock=None, image=None): """Adds a button in the bottom of the dialog. :param label: the text that will be displayed by the button. :param stock: the gtk stock id to be used in the button. :param image: the image filename. """ button = gtk.Button(label=label) if image: image_widget = gtk.Image() image_widget.set_from_file(environ.find_resource("pixmaps", image)) image_widget.show() button.set_image(image_widget) elif stock: button_set_image_with_label(button, stock, label) self.action_area.set_layout(gtk.BUTTONBOX_START) self.action_area.pack_start(button, False, False, 6) return button
def add_button(self, label, stock=None, image=None): """Adds a button in the bottom of the dialog. :param label: the text that will be displayed by the button. :param stock: the gtk stock id to be used in the button. :param image: the image filename. """ button = gtk.Button(label=label) if image: image_widget = gtk.Image() image_widget.set_from_file(environ.find_resource('pixmaps', image)) image_widget.show() button.set_image(image_widget) elif stock: button_set_image_with_label(button, stock, label) self.action_area.set_layout(gtk.BUTTONBOX_START) self.action_area.pack_start(button, False, False, 6) return button
def __init__(self): self.app = get_utility(IGazpachoApp) self.plugin_manager = get_utility(IPluginManager) ui_file = environ.find_resource('glade', 'preferences.glade') app_window = self.app.get_window() self.ob = ObjectBuilder(ui_file) self.dialog = self.ob.get_widget('dialog') # dialog setup self.dialog.set_modal(True) self.dialog.set_transient_for(app_window) # this should go into the glade file as soon as we get support for it close = self.ob.get_widget('close') close.connect('clicked', self.on_close__clicked) # setup each tab self._setup_plugins_tab()
def __init__(self, view, gladefile, widgets, gladename=None, domain=None): if not gladefile: raise ValueError("A gladefile wasn't provided.") elif not isinstance(gladefile, basestring): raise TypeError( "gladefile should be a string, found %s" % type(gladefile)) filename = os.path.splitext(os.path.basename(gladefile))[0] self._filename = filename + '.glade' self._view = view self._gladefile = environ.find_resource("glade", self._filename) self._widgets = (widgets or view.widgets or [])[:] self.gladename = gladename or filename ## self._showwarning = warnings.showwarning ## warnings.showwarning = self._on_load_warning self._tree = Builder(self._gladefile, domain=domain) ## warnings.showwarning = self._showwarning if not self._widgets: self._widgets = [w.get_data("gazpacho::object-id") for w in self._tree.get_widgets()] self._attach_widgets()
def _load_mode_icons(self): """ Load the pixbufs that are to be used as sizegroup mode icons. Mode constants: - gtk.SIZE_GROUP_HORIZONTAL - gtk.SIZE_GROUP_VERTICAL - gtk.SIZE_GROUP_BOTH @return: a mapping of sizegroup mode constants to pixbufs @rtype: map """ icon_names = {gtk.SIZE_GROUP_HORIZONTAL: 'sizegroup-horizontal.png', gtk.SIZE_GROUP_VERTICAL: 'sizegroup-vertical.png', gtk.SIZE_GROUP_BOTH: 'sizegroup-both.png'} icon_map = {} for key, name in icon_names.iteritems(): pixbuf = None filename = environ.find_resource('pixmap', name) if filename: pixbuf = gtk.gdk.pixbuf_new_from_file(filename) icon_map[key] = pixbuf return icon_map
def about_dialog(*args): """Run about dialog""" about = gtk.AboutDialog() # Set general info: version, authors and etc about.set_name(bbcalc.APP_NAME) about.set_version(bbcalc.APP_VERSION) about.set_copyright(bbcalc.APP_COPYRIGHT) about.set_website(bbcalc.APP_WEBSITE) about.set_authors([author + '\n' for author in bbcalc.APP_AUTHORS]) # Loading app logo icon_file = environ.find_resource('pixmaps', 'bbcalc_logo.png') logo = gtk.gdk.pixbuf_new_from_file(icon_file) about.set_logo(logo) # Set app license text if os.path.isfile('/usr/share/common-licenses/GPL-3'): about.set_license(open('/usr/share/common-licenses/GPL-3').read()) else: about.set_license(bbcalc.APP_LICENSE) about.set_comments(bbcalc.APP_DESCRIPTION) about.run() about.destroy()
def load(self, filename): ''' Given a filename open a project saved on disk. TODO: If returned value is None, there is an error! ''' prj = None try: #open the file for reading projfile = bz2.BZ2File(filename, 'r') except: #TODO: Treat error pass else: schemafile = open(environ.find_resource('xml', 'sacam.rng')) schema = etree.parse(schemafile) relax_schema = etree.RelaxNG(schema) # Parse the file, validate, and then iterate thru it # to build the project instance parser = etree.XMLParser(ns_clean=True) xml_tree = etree.parse(projfile, parser) if not relax_schema.validate(xml_tree): prj = None print 'error' # TODO: error handling else: prj = Project() prj.filename = filename # get the <project> tag root = xml_tree.getroot() # begin parsing of tree. # First step: build the attributes dictionary. element = root.find("{http://cnpdia.embrapa.br}attributes") for attr in element: key, value = attr.text.split(':') prj.attributes[key] = value # Second step: refimage property element = root.find("{http://cnpdia.embrapa.br}refimage") fln, tail = os.path.split(element.text) prj.refimage = gdk.pixbuf_new_from_file(fln + '/refimg.jpg') # Third step: bug_size property element = root.find("{http://cnpdia.embrapa.br}bug_size") prj.bug_size = float(element.text) # Fourth step: bug_max_speed property element = root.find("{http://cnpdia.embrapa.br}bug_max_speed") prj.bug_max_speed = float(element.text) # Fifth step: experiment list experiments = root.find( "{http://cnpdia.embrapa.br}experiments") prj.exp_list = [] for elt in experiments: new_exp = Experiment().build_from_xml(elt) prj.exp_list.append(new_exp) if prj.exp_list: prj.current_experiment = prj.exp_list[-1] schemafile.close() # we don't need the projfile anymore, it can be closed projfile.close() return prj
def _import_one(klass, filename): imp = klass() imp.feed_file(environ.find_resource('csv', filename)) imp.process()
def __init__(self, project): gladefile = environ.find_resource('glade', 'areas.glade') self.xml = gtk.glade.XML(gladefile, domain=APP_NAME) self.project = project self.output_handler = None # widgets to be used output = self.xml.get_widget("drawingareaAreas") area_name = self.xml.get_widget("entryAreaName") area_desc = self.xml.get_widget("entryAreaDesc") self.window = None # setting up the areas treeview view = self.xml.get_widget("treeviewAreas") # model columns: area name, area shape, area description model = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_PYOBJECT, gobject.TYPE_STRING) view.set_model(model) # renderer of the first column renderer = gtk.CellRendererText() renderer.props.editable = True renderer.connect("edited", self.edited_cb, area_name, view.get_model(), 0) column = gtk.TreeViewColumn(_("Name"), renderer, text=0) view.append_column(column) # renderer of the second column renderer = gtk.CellRendererText() renderer.props.editable = True renderer.connect("edited", self.edited_cb, area_desc, view.get_model(), 2) column = gtk.TreeViewColumn(_("Description"), renderer, text=2) view.append_column(column) # To treat single selection only selection = view.get_selection() selection.set_mode(gtk.SELECTION_SINGLE) view.connect("cursor_changed", self.select_area, output, area_name, area_desc) #connecting the callbacks of the areasDiag widget = self.xml.get_widget("buttonAddArea") widget.connect("clicked", self.shape_action, "add") widget = self.xml.get_widget("buttonRemoveArea") widget.connect("clicked", self.remove_area) widget = self.xml.get_widget("buttonResizeArea") widget.connect("clicked", self.shape_action, "resize") widget = self.xml.get_widget("buttonMoveArea") widget.connect("clicked", self.shape_action, "move") #buttons to define the shape that will be drawn widget = self.xml.get_widget("buttonRectangle") widget.connect("clicked", self.set_shape, "rectangle") widget = self.xml.get_widget("buttonEllipse") widget.connect("clicked", self.set_shape, "ellipse") widget = self.xml.get_widget("buttonSetReleaseArea") widget.connect("clicked", self.set_as_release_area) self.release_area = None #default shape to be drawn self.shape_type = "rectangle" #default action is to add an area self.action = "add" self.composing_shape = False self.moving_shape_started = False self.resizing_shape_started = False self.graphic_context = None self.red_gc = None self.start_point = None self.end_point = None self.first_point = None self.last_point = None self.initial_point = None self.final_point = None self.selected_shape = None self.resizing_shape = None self.temp_shape = None self.moving_shape = None output.add_events(gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK | gtk.gdk.BUTTON_MOTION_MASK | gtk.gdk.KEY_PRESS_MASK | gtk.gdk.KEY_RELEASE_MASK) #these three are necessary to draw something in the draw area output.connect("button-press-event", self.compose_shape) output.connect("motion-notify-event", self.compose_shape) output.connect("button-release-event", self.finish_shape, model, area_name, area_desc, view)
def find_resource(self, filename): return environ.find_resource("pixmaps", filename)
def _from_string(self, data): """Convert a string to the data type of the widget This may raise a L{kiwi.datatypes.ValidationError} if conversion failed @param data: data to convert """ conv = self._converter if conv is None: conv = converter.get_converter(str) return conv.from_string(data) VALIDATION_ICON_WIDTH = 16 MANDATORY_ICON = gtk.STOCK_EDIT ERROR_ICON = gdk.pixbuf_new_from_file( environ.find_resource('pixmap', 'validation-error-16.png')) class ValidatableProxyWidgetMixin(ProxyWidgetMixin): """Class used by some Kiwi Widgets that need to support mandatory input and validation features such as custom validation and data-type validation. Mandatory support provides a way to warn the user when input is necessary. The validatation feature provides a way to check the data entered and to display information about what is wrong. """ implements(IValidatableProxyWidget) gproperty('mandatory', bool, default=False)
def _install_invoice_templates(): log.info("Installing invoice templates") importer = InvoiceImporter() importer.feed_file(environ.find_resource('csv', 'invoices.csv')) importer.process()
def __init__(self): gladefile = environ.find_resource('glade', 'refimg.glade') self.xml = gtk.glade.XML(gladefile, domain=APP_NAME)
def __init__(self): gladefile = environ.find_resource('glade', 'insectsize.glade') self.xml = gtk.glade.XML(gladefile, domain=APP_NAME) self.project = None
def __init__(self, video_output): gladefile = environ.find_resource('glade', 'devicemanager.glade') windowname = "devicemanager" self.xml = gtk.glade.XML(gladefile, windowname, domain=APP_NAME) self.devicewindow = self.xml.get_widget(windowname) self.devicewindow.connect("delete-event", self.delete) self.outputarea = video_output self.processor = Videoprocessor("motiondetector") self.processor.output = video_output # self.processor = Videoprocessor("identity") self.outputarea.connect("expose-event", self.expose_cb) self.outputarea.add_events(gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK | gtk.gdk.BUTTON_MOTION_MASK | gtk.gdk.KEY_PRESS_MASK | gtk.gdk.KEY_RELEASE_MASK) self.outputarea.connect("button-press-event", self.position_change) self.device = '/dev/video0' self.width, self.height = 320, 240 self.outputarea.set_size_request(self.width, self.height) self.norm, self.channel = None, None self.pipeline_string = '' self.null = None self.pipeline_play = None widget = self.xml.get_widget('buttonDefaultPipeline') widget.connect('clicked', self.set_default_pipeline_string) widget = self.xml.get_widget('buttonTestingPipeline') widget.connect('clicked', self.set_testing_pipeline_string) self.counter = 0 input_type = self.xml.get_widget('comboboxInputType') input_type.set_active(0) input_type.connect('changed', self.input_combo_change) widget = self.xml.get_widget('comboboxWidth') input_type.connect('changed', self.set_combo_width, widget) widget.connect('changed', self.combo_width_change) widget = self.xml.get_widget('comboboxHeight') input_type.connect('changed', self.set_combo_height, widget) widget.connect('changed', self.combo_height_change) widget = self.xml.get_widget('comboboxDevice') input_type.connect('changed', self.set_combo_device, widget) widget.connect('changed', self.combo_device_change) widget = self.xml.get_widget('comboboxChannel') input_type.connect('changed', self.set_combo_channel, widget) widget.connect('changed', self.combo_channel_change) widget = self.xml.get_widget('comboboxNorm') input_type.connect('changed', self.set_combo_norm, widget) widget.connect('changed', self.combo_norm_change) self.textview = self.xml.get_widget("textviewPipeline") self.textview.set_wrap_mode(gtk.WRAP_WORD) self.set_testing_pipeline_string(None) self.show_window(None) #self.set_default_pipeline_string(None) if not self.set_pipelines(): print 'error!' #TODO
def __init__(self): gladefile = environ.find_resource('glade', 'sacam.glade') windowname = "mainwindow" self.xml = gtk.glade.XML(gladefile, domain=APP_NAME) self.window = self.xml.get_widget(windowname) outputarea = self.xml.get_widget("videoOutputArea") self.device_manager = DeviceManager(outputarea) self.project = Project() self.project.current_experiment.release_area = [ 0, 0, self.device_manager.frame["width"], self.device_manager.frame["height"] ] self.propdiag = PropDiag() self.refimgdiag = RefimgDiag() self.areasdiag = AreasDiag(self.project) self.scalediag = ScaleDiag(self.project) self.insectsizediag = InsectsizeDiag() self.tracksimulator = TrackSimulator(self.xml, self.project, self.device_manager) self.projectmanager = ProjectManager(self.xml, self.project) self.device_manager.connect_processor_props(self.xml, self.project) self.running = None widget = self.xml.get_widget("buttonNew") widget.connect("clicked", self.new_project) widget = self.xml.get_widget("buttonPreferences") widget.connect("clicked", self.device_manager.show_window) widget = self.xml.get_widget("buttonSave") widget.connect("clicked", self.save_project) widget = self.xml.get_widget("buttonOpen") widget.connect("clicked", self.load_project) widget = self.xml.get_widget("buttonProcess") widget.connect("clicked", self.process_lists) widget = self.xml.get_widget("buttonReport") widget.connect("clicked", self.report) self.hnd = {} self.hnd["video"] = None self.hnd["prop"] = None self.hnd["scale"] = None self.hnd["size"] = None self.hnd["refimg"] = None self.hnd["areas"] = None self.connect_project_signals() self.invalid = {} self.invalid["size"] = True self.invalid["areas"] = True self.invalid["scale"] = True self.invalid["refimg"] = True self.invalid["speed"] = True self.invalid["path"] = True #home dir home = os.curdir if 'HOME' in os.environ: home = os.environ['HOME'] elif os.name == 'posix': home = os.path.expanduser("~/") elif os.name == 'nt': if 'HOMEPATH' in os.environ: if 'HOMEDRIVE' in os.environ: home = os.environ['HOMEDRIVE'] + os.environ['HOMEPATH'] else: home = os.environ['HOMEPATH'] self.home = os.path.realpath(home) + os.sep self.project.refimage = self.device_manager.get_current_frame() self.window.connect("destroy", self.destroy) self.window.show() self.update_state()
def _application_window_create(self): application_window = gtk.Window(gtk.WINDOW_TOPLEVEL) application_window.set_name('ApplicationWindow') application_window.connect('delete-event', self._delete_event_cb) iconfilename = environ.find_resource('pixmap', 'gazpacho-icon.png') gtk.window_set_default_icon_from_file(iconfilename) # Layout them on the window main_vbox = gtk.VBox() application_window.add(main_vbox) main_vbox.show() # Create actions that are always enabled bar_manager.add_actions( 'Normal', # File menu ('FileMenu', None, _('_File')), ('New', gtk.STOCK_NEW, None, None, _('New Project'), self._new_cb), ('Open', gtk.STOCK_OPEN, None, None, _('Open Project'), self._open_cb), ('Quit', gtk.STOCK_QUIT, None, None, _('Quit'), self._quit_cb), # Edit menu ('EditMenu', None, _('_Edit')), ('Preferences', gtk.STOCK_PREFERENCES, None, None, _('Open the preferences dialog'), self._preferences_cb), # Object menu ('ObjectMenu', None, _('_Objects')), # Project menu ('ProjectMenu', None, _('_Project')), ('ProjectProperties', None, _('_Properties'), None, _('Project properties'), self._project_properties_cb), # (projects..) # Debug menu ('DebugMenu', None, _('_Debug')), ('DumpData', None, _('Dump data'), '<control>M', _('Dump debug data'), self._dump_data_cb), ('Preview', None, _('Preview'), None, _('Preview current window'), self._preview_cb), # Help menu ('HelpMenu', None, _('_Help')), ('About', gtk.STOCK_ABOUT, None, None, _('About Gazpacho'), self._about_cb), ) # Toggle actions bar_manager.add_toggle_actions( 'Normal', ('ShowStructure', None, _('Show _structure'), '<control><shift>t', _('Show container structure'), self._show_structure_cb, False), ('ShowCommandStack', None, _('Show _command stack'), 'F3', _('Show the command stack'), self._show_command_stack_cb, False), ('ShowClipboard', None, _('Show _clipboard'), 'F4', _('Show the clipboard'), self._show_clipboard_cb, False), ('ShowWorkspace', None, _('Show _workspace'), '<control><shift>t', _('Show container workspace'), self._show_workspace_cb, False), ) # Create actions that reqiuire a project to be enabled bar_manager.add_actions( 'ContextActions', # File menu ('Save', gtk.STOCK_SAVE, None, None, _('Save Project'), self._save_cb), ('SaveAs', gtk.STOCK_SAVE_AS, _('Save _As...'), '<shift><control>S', _('Save project with different name'), self._save_as_cb), ('Close', gtk.STOCK_CLOSE, None, None, _('Close Project'), self._close_cb), # Edit menu ('Undo', gtk.STOCK_UNDO, None, '<control>Z', _('Undo last action'), self._undo_cb), ('Redo', gtk.STOCK_REDO, None, '<shift><control>Z', _('Redo last action'), self._redo_cb) ) bar_manager.add_actions( 'AlwaysDisabled', # Edit menu ('Cut', gtk.STOCK_CUT, None, None, _('Cut'), None), ('Copy', gtk.STOCK_COPY, None, None, _('Copy'), None), ('Paste', gtk.STOCK_PASTE, None, None, _('Paste'), None), ('Delete', gtk.STOCK_DELETE, None, '<control>D', _('Delete'), None) ) bar_manager.build_interfaces() self._update_recent_project_items() application_window.add_accel_group(bar_manager.get_accel_group()) main_vbox.pack_start(bar_manager.get_menubar(), False) main_vbox.pack_start(bar_manager.get_toolbar(), False) hbox = gtk.HBox(spacing=6) main_vbox.pack_start(hbox) hbox.show() palette.connect('toggled', self._on_palette_toggled) hbox.pack_start(palette, False, False) palette.show_all() sw = gtk.ScrolledWindow() sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) sw.set_size_request(400, -1) hbox.pack_start(sw, True, True) self._workspace = WorkSpace() sw.add_with_viewport(self._workspace) self._workspace.show() self._workspace_sw = sw self._workspace_action = bar_manager.get_action( 'ui/MainMenu/EditMenu/ShowWorkspace') vpaned = gtk.VPaned() vpaned.set_position(150) hbox.pack_start(vpaned, True, True) vpaned.show() notebook = gtk.Notebook() vpaned.add1(notebook) notebook.show() # Widget view widget_view = WidgetTreeView(self) self._add_view(widget_view) page_num = notebook.append_page(widget_view, gtk.Label(_('Widgets'))) widget_view.show() state = WidgetUIMState() self._uim_states[page_num] = state # Action view self.gactions_view = GActionsView(self) self._add_view(self.gactions_view) page_num = notebook.append_page(self.gactions_view, gtk.Label(_('Actions'))) self.gactions_view.show() state = ActionUIMState(self.gactions_view) self._uim_states[page_num] = state # Sizegroup view self.sizegroup_view = SizeGroupView(self) self._add_view(self.sizegroup_view) page_num = notebook.append_page(self.sizegroup_view, gtk.Label(_('Size Groups'))) self.sizegroup_view.show() state = SizeGroupUIMState(self.sizegroup_view) self._uim_states[page_num] = state # Add property editor self._editor = PropertyEditor(self) vpaned.add2(self._editor) self._editor.show_all() notebook.connect('switch-page', self._on_notebook_switch_page) # Statusbar statusbar = gtk.Statusbar() self._statusbar_menu_context_id = statusbar.get_context_id("menu") self._statusbar_actions_context_id = statusbar.get_context_id("actions") main_vbox.pack_end(statusbar, False) self._statusbar = statusbar statusbar.show() # dnd doesn't seem to work with Konqueror, at least not when # gtk.DEST_DEFAULT_ALL or gtk.DEST_DEFAULT_MOTION is used. If # handling the drag-motion event it will work though, but it's # a bit tricky. application_window.drag_dest_set(gtk.DEST_DEFAULT_ALL, Application.targets, gtk.gdk.ACTION_COPY) application_window.connect('drag-data-received', self._dnd_data_received_cb) # Enable the current state self._active_uim_state = self._uim_states[0] self._active_uim_state.enable() return application_window
def __init__(self): gladefile = environ.find_resource('glade', 'projprop.glade') self.gui = gtk.glade.XML(gladefile, domain=APP_NAME)
def write_app_logo(sheet): filename = environ.find_resource("pixmaps", "stoq_logo.bmp") sheet.insert_bitmap(filename, 0, 0, x=2, y=2, scale_x=1.0, scale_y=0.35)
"""Convert a string to the data type of the widget This may raise a L{kiwi.datatypes.ValidationError} if conversion failed @param data: data to convert """ conv = self._converter if conv is None: conv = converter.get_converter(str) return conv.from_string(data) VALIDATION_ICON_WIDTH = 16 MANDATORY_ICON = gtk.STOCK_EDIT ERROR_ICON = gdk.pixbuf_new_from_file( environ.find_resource('pixmap', 'validation-error-16.png')) class ValidatableProxyWidgetMixin(ProxyWidgetMixin): """Class used by some Kiwi Widgets that need to support mandatory input and validation features such as custom validation and data-type validation. Mandatory support provides a way to warn the user when input is necessary. The validatation feature provides a way to check the data entered and to display information about what is wrong. """ implements(IValidatableProxyWidget) def __init__(self, widget=None):