def test_widget_root_from_code_with_kv(self): from kivy.lang import Builder from kivy.factory import Factory from kivy.properties import ObjectProperty, StringProperty from kivy.uix.floatlayout import FloatLayout Builder.load_string(""" <MyWidget>: Label: text: root.title <BaseWidget>: CallerWidget: """) class CallerWidget(FloatLayout): def __init__(self, **kwargs): super(CallerWidget, self).__init__(**kwargs) self.add_widget(MyWidget(title="Hello World")) class NestedWidget(FloatLayout): title = StringProperty('aa') class MyWidget(NestedWidget): pass class BaseWidget(FloatLayout): pass Factory.register('MyWidget', cls=MyWidget) Factory.register('CallerWidget', cls=CallerWidget) r = self.render root = BaseWidget() r(root)
def build_item(self, item, params, is_rule=False): self._push_ids() is_template = False if is_rule is False: if __debug__: trace('Builder: build item %s' % item) if item.startswith('<'): raise ParserError(params['__ctx__'], params['__line__'], 'Rules are not accepted inside widgets') no_apply = False if item[0] == '+': item = item[1:] no_apply = True # we are checking is the widget is a template or not # if yes, no child is allowed, and all the properties are used to # construct the context for the template. cls = Factory.get(item) if Factory.is_template(item): is_template = True self._push_widgets() else: try: widget = cls(__no_builder=True) except Exception, e: raise ParserError(params['__ctx__'], params['__line__'], str(e)) if not no_apply: self.listwidget.append(widget)
def build(*args): from fields import fieldDict, ShapeField, LinkedField from kivy.factory import Factory FE = Factory.get('FieldEntry') TFE = Factory.get("TmplFieldEntry") PFE = Factory.get('LinkedFieldEntry') for key in sorted(fieldDict): if "skip_designer" in fieldDict[key].__dict__ and fieldDict[key].skip_designer:#test of __dict__ ensure existencfe at the calss level,, not in its basis continue fe = FE() fe.text= key fe.target = self if issubclass(fieldDict[key], ShapeField): if fieldDict[key] == ShapeField: continue self.ids.shapes_stack.add_widget(fe) elif issubclass(fieldDict[key], LinkedField): if fieldDict[key] == LinkedField: continue pfe = PFE() pfe.target = self pfe.text = key self.ids.effects_stack.add_widget(pfe) else: self.ids.fields_stack.add_widget(fe) #Now add Template field tfe = TFE() tfe.target = self self.ids.fields_stack.add_widget(tfe)
def init_ui(self): ''' Initialize The Ux part of electrum. This function performs the basic tasks of setting up the ui. ''' #from weakref import ref self.funds_error = False # setup UX self.screens = {} #setup lazy imports for mainscreen Factory.register('AnimatedPopup', module='electrum_gui.kivy.uix.dialogs') Factory.register('QRCodeWidget', module='electrum_gui.kivy.uix.qrcodewidget') # preload widgets. Remove this if you want to load the widgets on demand #Cache.append('electrum_widgets', 'AnimatedPopup', Factory.AnimatedPopup()) #Cache.append('electrum_widgets', 'QRCodeWidget', Factory.QRCodeWidget()) # load and focus the ui self.root.manager = self.root.ids['manager'] self.history_screen = None self.contacts_screen = None self.send_screen = None self.invoices_screen = None self.receive_screen = None self.requests_screen = None self.address_screen = None self.icon = "icons/electrum.png" self.tabs = self.root.ids['tabs']
def init_ui(self): ''' Initialize The Ux part of electrum. This function performs the basic tasks of setting up the ui. ''' from weakref import ref set_language(self.electrum_config.get('language')) self.funds_error = False # setup UX self.screens = {} #setup lazy imports for mainscreen Factory.register('AnimatedPopup', module='electrum_ltc_gui.kivy.uix.dialogs') Factory.register('QRCodeWidget', module='electrum_ltc_gui.kivy.uix.qrcodewidget') # preload widgets. Remove this if you want to load the widgets on demand #Cache.append('electrum_ltc_widgets', 'AnimatedPopup', Factory.AnimatedPopup()) #Cache.append('electrum_ltc_widgets', 'QRCodeWidget', Factory.QRCodeWidget()) # load and focus the ui self.root.manager = self.root.ids['manager'] self.recent_activity_card = None self.history_screen = None self.contacts_screen = None self.icon = "icons/electrum-ltc.png" # connect callbacks if self.network: interests = ['update', 'status', 'new_transaction'] self.network.register_callback(self.on_network, interests) self.wallet = None
def find_diff(self,widget): '''A utility function to find differences in properties between a user-modified widget and a fresh instance of the same class. Currently its implemented by Factory building a fresh instance and comparing but later we should add a function in kivy.properties like getdefaultvalue() This returns a dictionary of {property:values} ''' #This dict will hold the comparable properties (We skip Alias, ReferenceList and _) comp_dict = {} #This dict will ultimately hold the properties which have changed from their defaults diff_dict = {} module_name = widget.__class__.__module__ class_name = widget.__class__.__name__ # TODO : Check if this class is already registered. If so, don't register again. Factory.register(class_name, module=module_name) factory_caller = getattr(Factory, class_name) new_widget = factory_caller() #Skipping certain types of properties for prop, value in new_widget.properties().iteritems(): if prop.startswith('_'): continue if isinstance(value, AliasProperty): continue if isinstance(value, ReferenceListProperty): continue comp_dict[prop] = getattr(new_widget, prop) #Now compare these properties with the user created one for prop,value in comp_dict.iteritems(): if value != getattr(widget, prop): diff_dict[prop] = getattr(widget, prop) # if len(diff_dict) != 0: # print "Diff in "+ class_name return diff_dict
def _clean_old_kv(self, path): ''' Removes widgets and rules already processed to this file :param path: file path - the same that in app_widgets ''' for key in dict(self.app_widgets): wd = self.app_widgets[key] if path != wd.kv_path: continue wdg = get_app_widget(wd) if wdg is None: continue if wd.is_dynamic: del self.app_widgets[key] rules = Builder.match(wdg) # Cleaning widget rules for _rule in rules: for _tuple in Builder.rules[:]: if _tuple[1] == _rule: Builder.rules.remove(_tuple) if wd.is_dynamic: Factory.unregister(wd.name.split('@')[0]) # Cleaning class rules for rule in Builder.rules[:]: if rule[1].name == '<' + wd.name + '>': Builder.rules.remove(rule) break
def init_ui(self): """ Initialize The Ux part of electrum. This function performs the basic tasks of setting up the ui. """ from weakref import ref self.funds_error = False # setup UX self.screens = {} # setup lazy imports for mainscreen Factory.register("AnimatedPopup", module="electrum_gui.kivy.uix.dialogs") Factory.register("QRCodeWidget", module="electrum_gui.kivy.uix.qrcodewidget") # preload widgets. Remove this if you want to load the widgets on demand # Cache.append('electrum_widgets', 'AnimatedPopup', Factory.AnimatedPopup()) # Cache.append('electrum_widgets', 'QRCodeWidget', Factory.QRCodeWidget()) # load and focus the ui self.root.manager = self.root.ids["manager"] self.recent_activity_card = None self.history_screen = None self.contacts_screen = None self.icon = "icons/electrum.png" # connect callbacks if self.network: interests = ["updated", "status", "new_transaction"] self.network.register_callback(self.on_network, interests) # self.wallet = None self.tabs = self.root.ids["tabs"]
def load_string(self, string, **kwargs): """Insert a string into the Language Builder :Parameters: `rulesonly`: bool, default to False If True, the Builder will raise an exception if you have a root widget inside the definition. """ kwargs.setdefault("rulesonly", False) self._current_filename = fn = kwargs.get("filename", None) try: # parse the string parser = Parser(content=string, filename=fn) # merge rules with our rules self.rules.extend(parser.rules) self._clear_matchcache() # add the template found by the parser into ours for name, cls, template in parser.templates: self.templates[name] = (cls, template, fn) Factory.register(name, cls=partial(self.template, name), is_template=True) # create root object is exist if kwargs["rulesonly"] and parser.root: filename = kwargs.get("rulesonly", "<string>") raise Exception("The file <%s> contain also non-rules " "directives" % filename) if parser.root: widget = Factory.get(parser.root.name)() self._apply_rule(widget, parser.root, parser.root) return widget finally: self._current_filename = None
def unload_file(self, filename): '''Unload all rules associated with a previously imported file. .. versionadded:: 1.0.8 .. warning:: This will not remove rules or templates already applied/used on current widgets. It will only effect the next widgets creation or template invocation. ''' # remove rules and templates filename = resource_find(filename) or filename self.rules = [x for x in self.rules if x[1].ctx.filename != filename] self._clear_matchcache() templates = {} for x, y in self.templates.items(): if y[2] != filename: templates[x] = y self.templates = templates if filename in self.files: self.files.remove(filename) # unregister all the dynamic classes Factory.unregister_from_filename(filename)
def _build_canvas(self, canvas, widget, rule, rootrule): global Instruction if Instruction is None: Instruction = Factory.get('Instruction') idmap = copy(self.rulectx[rootrule]['ids']) for crule in rule.children: name = crule.name if name == 'Clear': canvas.clear() continue instr = Factory.get(name)() if not isinstance(instr, Instruction): raise BuilderException( crule.ctx, crule.line, 'You can add only graphics Instruction in canvas.') try: for prule in crule.properties.itervalues(): key = prule.name value = prule.co_value if type(value) is CodeType: value = create_handler( widget, instr, key, value, prule, idmap) setattr(instr, key, value) except Exception, e: raise BuilderException(prule.ctx, prule.line, str(e))
def _build_canvas(self, canvas, widget, rule, rootrule): global Instruction if Instruction is None: Instruction = Factory.get('Instruction') idmap = copy(self.rulectx[rootrule]['ids']) for crule in rule.children: name = crule.name if name == 'Clear': canvas.clear() continue instr = Factory.get(name)() if not isinstance(instr, Instruction): raise BuilderException( crule.ctx, crule.line, 'You can add only graphics Instruction in canvas.') try: for prule in crule.properties.values(): key = prule.name value = prule.co_value if type(value) is CodeType: value, _ = create_handler( widget, instr.proxy_ref, key, value, prule, idmap, True) setattr(instr, key, value) except Exception as e: tb = sys.exc_info()[2] raise BuilderException( prule.ctx, prule.line, '{}: {}'.format(e.__class__.__name__, e), cause=tb)
def cleanup(self): """To clean all the children in self.custom_category. """ if self.custom_category: self.accordion.remove_widget(self.custom_category) Factory.register("BoxLayout", module="kivy.uix.boxlayout") self.custom_category = ToolboxCategory(title="App Widgets") self._list.append(self.custom_category)
def cleanup(self): '''To clean all the children in self.custom_category. ''' if self.custom_category: self.accordion.remove_widget(self.custom_category) Factory.register('BoxLayout', module='kivy.uix.boxlayout') self.custom_category = ToolboxCategory(title='App Widgets') self._list.append(self.custom_category)
def load_string(self, string, **kwargs): '''Insert a string into the Language Builder and return the root widget (if defined) of the kv string. :Parameters: `rulesonly`: bool, defaults to False If True, the Builder will raise an exception if you have a root widget inside the definition. ''' kwargs.setdefault('rulesonly', False) self._current_filename = fn = kwargs.get('filename', None) # put a warning if a file is loaded multiple times if fn in self.files: Logger.warning( 'Lang: The file {} is loaded multiples times, ' 'you might have unwanted behaviors.'.format(fn)) try: # parse the string parser = Parser(content=string, filename=fn) # merge rules with our rules self.rules.extend(parser.rules) self._clear_matchcache() # add the template found by the parser into ours for name, cls, template in parser.templates: self.templates[name] = (cls, template, fn) Factory.register(name, cls=partial(self.template, name), is_template=True, warn=True) # register all the dynamic classes for name, baseclasses in iteritems(parser.dynamic_classes): Factory.register(name, baseclasses=baseclasses, filename=fn, warn=True) # create root object is exist if kwargs['rulesonly'] and parser.root: filename = kwargs.get('rulesonly', '<string>') raise Exception('The file <%s> contain also non-rules ' 'directives' % filename) # save the loaded files only if there is a root without # template/dynamic classes if fn and (parser.templates or parser.dynamic_classes or parser.rules): self.files.append(fn) if parser.root: widget = Factory.get(parser.root.name)() self._apply_rule(widget, parser.root, parser.root) return widget finally: self._current_filename = None
def build(self): Factory.register('Playground', module='designer.playground') Factory.register('Toolbox', module='designer.toolbox') Factory.register('StatusBar', module='designer.statusbar') Factory.register('PropertyViewer', module='designer.propertyviewer') Factory.register('WidgetsTree', module='designer.nodetree') self._widget_focused = None self.root = Designer() self.bind(widget_focused=self.root.propertyviewer.setter('widget')) self.focus_widget(self.root.playground.root)
def on_last_selected(self, instance, field): tasks = self.ids.tasks tasks.clear_widgets() #Just make sure that the dos are aligned on the widget children = self.current_template.children for widget in children: widget.selected = widget in self.selections if field: if field in self.templates: self.current_template = field else: self.current_template = field.parent #Re add to make it at the top _p = field.parent _p.remove_widget(field) _p.add_widget(field) #Add some button around me from kivy.factory import Factory from kivy.uix.label import Label #Now for the big show text = field.name if field.name else field.Type from utils.fontello import FontIcon icon = FontIcon(icon=text, color=(0,0,0,1), font_size=24, size_hint_x=None, width=40) tasks.add_widget(icon) if text.lower().endswith('field'): text=text[:-5] label = Label(text=text, size_hint_x=None, width=100) tasks.add_widget(label) #Skip this if targetting current template if field != self.current_template: ftb = Factory.get('FieldTaskButton') data = [ (self.remove_selection, 'cancel'), (self.duplicate_selection, 'duplicate'), ] for cb, img in data: _button = ftb() #_button.source = img _button.icon = img _button.bind(on_press=cb) _button.designer = self tasks.add_widget(_button) ##self.insertMoveUpDownButton() PIMGS = Factory.get('PositionImageSpinner') SIMGS = Factory.get('SizeImageSpinner') img_spinner = PIMGS() img_spinner.bind(text=self.position_selection) tasks.add_widget(img_spinner) img_spinner = SIMGS() img_spinner.bind(text = self.align_selection) tasks.add_widget(img_spinner) #Now load the specific attributes matrix/tree for field 6> activated by a double tap on the field ##self.display_field_attributes(field) self.ids.fields.select_node(self.nodes[field])
def show_tx_details(self, item): ra_dialog = Cache.get('electrum_widgets', 'RecentActivityDialog') if not ra_dialog: Factory.register('RecentActivityDialog', module='electrum_gui.kivy.uix.dialogs.carousel_dialog') Factory.register('GridView', module='electrum_gui.kivy.uix.gridview') ra_dialog = ra_dialog = Factory.RecentActivityDialog() Cache.append('electrum_widgets', 'RecentActivityDialog', ra_dialog) ra_dialog.item = item ra_dialog.open()
def build_template(self, item, params): if __debug__: trace("Builder: build template for %s" % item) if item[0] != "[" or item[-1] != "]": raise ParserError(params["__ctx__"], params["__line__"], "Invalid template (must be inside [])") item_content = item[1:-1] if not "@" in item_content: raise ParserError(params["__ctx__"], params["__line__"], "Invalid template name (missing @)") template_name, template_root_cls = item_content.split("@") self.add_template(template_name, template_root_cls, params) Factory.register(template_name, cls=partial(self.template, template_name), is_template=True)
def animate(self, **animProps): class_spec = {'cls': self.orig_obj.__class__} Factory.register('HighLightObj', **class_spec) highlight_obj = Factory.HighLightObj(text=self.orig_obj.text, padding=self.orig_obj.padding, pos=(self.orig_obj.center_x - self.parent.center_x, self.orig_obj.center_y - self.parent.center_y), size=self.orig_obj.size, font_size=self.orig_obj.font_size, **self.kwargs) self.parent.add_widget(highlight_obj) if 'd' not in animProps: animProps['d'] = 1.0 if 't' not in animProps: animProps['t'] = 'out_cubic' Animation(**animProps).start(highlight_obj) Clock.schedule_once(lambda dt: self.parent.remove_widget(highlight_obj), animProps['d']) Factory.unregister('HighLightObj')
def build_template(self, item, params): if __debug__: trace('Builder: build template for %s' % item) if item[0] != '[' or item[-1] != ']': raise ParserError(params['__ctx__'], params['__line__'], 'Invalid template (must be inside [])') item_content = item[1:-1] if not '@' in item_content: raise ParserError(params['__ctx__'], params['__line__'], 'Invalid template name (missing @)') template_name, template_root_cls = item_content.split('@') self.add_template(template_name, template_root_cls, params) Factory.register(template_name, cls=partial(self.template, template_name), is_template=True)
def on_state(self, target, state): self.realise() if state == 'down': if self.name.lower().endswith('.kv'): f = Factory.get('FileItemOptionKV')() else: f = Factory.get('FileItemOption')() f.is_all_folder = self.is_all_folder self.add_widget(f) from kivy.animation import Animation anim = Animation(size_hint_y=0.2, duration=.1) anim.start(f) else: #remove the choice box self.remove_widget(self.children[0])
def cleanup(self, stop_watcher=True): '''To cleanup everything loaded by previous project. ''' if stop_watcher: self.proj_watcher.stop() # Remove all class rules and root rules of previous project rules = [] try: rules = Builder.match(self.root_rule.widget) for _rule in rules: for _tuple in Builder.rules[:]: if _tuple[1] == _rule: Builder.rules.remove(_tuple) except: pass for _tuple in Builder.rules[:]: for _rule in self.class_rules: if "<" + _rule.name + ">" == _tuple[1].name: Builder.rules.remove(_tuple) if self.root_rule and not self._is_root_already_in_factory and\ hasattr(Factory, self.root_rule.name): Factory.unregister(self.root_rule.name) self._app_file = None self._app_class = None self._app_module = None self._app = None # Remove previous project directories for _dir in self._dir_list: try: sys.path.remove(_dir) except: pass self.kv_file_list = [] self.file_list = [] self._dir_list = [] self.class_rules = [] self.list_comments = [] self.custom_widgets = [] self.dict_file_type_and_path = {} self.root_rule = None self._root_rule = None
def on_effect_cls(self, instance, cls): if isinstance(cls, string_types): cls = Factory.get(cls) self.effect_x = cls(target_widget=self._viewport) self.effect_x.bind(scroll=self._update_effect_x) self.effect_y = cls(target_widget=self._viewport) self.effect_y.bind(scroll=self._update_effect_y)
def create_settings(self): '''Create the settings panel. This method will normally be called only one time per application life-time and the result is cached internally, but it may be called again if the cached panel is removed by :meth:`destroy_settings`. By default, it will build a settings panel according to :attr:`settings_cls`, call :meth:`build_settings`, add a Kivy panel if :attr:`use_kivy_settings` is True, and bind to on_close/on_config_change. If you want to plug your own way of doing settings, without the Kivy panel or close/config change events, this is the method you want to overload. .. versionadded:: 1.8.0 ''' if self.settings_cls is None: from kivy.uix.settings import SettingsWithSpinner self.settings_cls = SettingsWithSpinner elif isinstance(self.settings_cls, string_types): self.settings_cls = Factory.get(self.settings_cls) s = self.settings_cls() self.build_settings(s) if self.use_kivy_settings: s.add_kivy_panel() s.bind(on_close=self.close_settings, on_config_change=self._on_config_change) return s
def template(self, *args, **ctx): '''Create a specialized template using a specific context. .. versionadded:: 1.0.5 With templates, you can construct custom widgets from a kv lang definition by giving them a context. Check :ref:`Template usage <template_usage>`. ''' # Prevent naming clash with whatever the user might be putting into the # ctx as key. name = args[0] if name not in self.templates: raise Exception('Unknown <%s> template name' % name) baseclasses, rule, fn = self.templates[name] key = '%s|%s' % (name, baseclasses) cls = Cache.get('kv.lang', key) if cls is None: rootwidgets = [] for basecls in baseclasses.split('+'): rootwidgets.append(Factory.get(basecls)) cls = type(name, tuple(rootwidgets), {}) Cache.append('kv.lang', key, cls) widget = cls() # in previous versions, ``ctx`` is passed as is as ``template_ctx`` # preventing widgets in it from be collected by the GC. This was # especially relevant to AccordionItem's title_template. proxy_ctx = {k: get_proxy(v) for k, v in ctx.items()} self._apply_rule(widget, rule, rule, template_ctx=proxy_ctx) return widget
def template(self, *args, **ctx): '''Create a specialized template using a specific context. .. versionadded:: 1.0.5 With template, you can construct custom widget from a kv lang definition by giving them a context. Check :ref:`Template usage <template_usage>`. ''' # Prevent naming clash with whatever the user might be putting into the # ctx as key. name = args[0] if not name in self.templates: raise Exception('Unknown <%s> template name' % name) baseclasses, defs, fn = self.templates[name] name, baseclasses key = '%s|%s' % (name, baseclasses) cls = Cache.get('kv.lang', key) if cls is None: rootwidgets = [] for basecls in baseclasses.split('+'): rootwidgets.append(Factory.get(basecls)) cls = ClassType(name, tuple(rootwidgets), {}) Cache.append('kv.lang', key, cls) widget = cls() self._push_widgets() self._push_ids() self.idmap = copy(global_idmap) self.idmap['root'] = widget self.idmap['ctx'] = QueryDict(ctx) self.build_item(widget, defs, is_rule=True) self._pop_ids() self._pop_widgets() return widget
def template(self, *args, **ctx): '''Create a specialized template using a specific context. .. versionadded:: 1.0.5 With template, you can construct custom widget from a kv lang definition by giving them a context. Check :ref:`Template usage <template_usage>`. ''' # Prevent naming clash with whatever the user might be putting into the # ctx as key. name = args[0] if name not in self.templates: raise Exception('Unknown <%s> template name' % name) baseclasses, rule, fn = self.templates[name] key = '%s|%s' % (name, baseclasses) cls = Cache.get('kv.lang', key) if cls is None: rootwidgets = [] for basecls in baseclasses.split('+'): rootwidgets.append(Factory.get(basecls)) cls = ClassType(name, tuple(rootwidgets), {}) Cache.append('kv.lang', key, cls) widget = cls() self._apply_rule(widget, rule, rule, template_ctx=ctx) return widget
def __init__(self, **kwargs): self._touch = None self._trigger_update_from_scroll = Clock.create_trigger( self.update_from_scroll, -1) super(ScrollView, self).__init__(**kwargs) effect_cls = self.effect_cls if isinstance(effect_cls, string_types): effect_cls = Factory.get(effect_cls) if self.effect_x is None and effect_cls is not None: self.effect_x = effect_cls(target_widget=self._viewport) if self.effect_y is None and effect_cls is not None: self.effect_y = effect_cls(target_widget=self._viewport) self.bind( width=self._update_effect_x_bounds, height=self._update_effect_y_bounds, viewport_size=self._update_effect_bounds, _viewport=self._update_effect_widget, scroll_x=self._trigger_update_from_scroll, scroll_y=self._trigger_update_from_scroll, pos=self._trigger_update_from_scroll, size=self._trigger_update_from_scroll) self._update_effect_widget() self._update_effect_x_bounds() self._update_effect_y_bounds()
def __init__(self, **kwargs): super(Container, self).__init__(**kwargs) self.previous_text = open(self.kv_file).read() parser = Parser(content=self.previous_text) widget = Factory.get(parser.root.name)() Builder._apply_rule(widget, parser.root, parser.root) self.add_widget(widget)
def setup(): from graphics.spaceBuilderMergeGameApp import SpaceBuilderMergeGameApp from graphics.customWidgets.screenManagerSwitcher import ScreenManagerSwitcher from graphics.preLoadScreenManager import PreLoadScreenManager from graphics.spaceBuilderMergeGameScreenManager import SpaceBuilderMergeGameScreenManager from graphics.screens.splashScreen1 import SplashScreen1 from graphics.screens.splashScreen2 import SplashScreen2 from graphics.screens.loadingScreen import LoadingScreen from graphics.screens.baseBuildScreen import BaseBuildScreen from graphics.screens.inventoryScreen import InventoryScreen from graphics.screens.settingsScreen import SettingsScreen from graphics.customWidgets.multiLangLabel import MultiLangLabel from graphics.customWidgets.baseLayout import BaseLayout from graphics.customWidgets.betterButton import BetterButton, TextBetterButton, FlatBetterButton from graphics.customWidgets.buildingButtonsHandler import BuildingButtonsHandler from graphics.customWidgets.mergeGUI import MergeGUI Factory.register("SpaceBuilderMergeGameApp", cls=SpaceBuilderMergeGameApp, module="graphics.spaceBuilderMergeGameApp") Factory.register("SpaceBuilderMergeGameScreenManager", cls=SpaceBuilderMergeGameScreenManager, module="graphics.SpaceBuilderMergeGameScreenManager") Factory.register("PreLoadScreenManager", cls=PreLoadScreenManager, module="graphics.preLoadScreenManager") Factory.register("SplashScreen1", cls=SplashScreen1, module="graphics.screens.splashScreen") Factory.register("SplashScreen2", cls=SplashScreen2, module="graphics.screens.splashScreen") Factory.register("LoadingScreen", cls=LoadingScreen, module="graphics.screens.loadingScreen") Factory.register("BaseBuildScreen", cls=BaseBuildScreen, module="graphics.screens.baseBuildScreen") Factory.register("InventoryScreen", cls=InventoryScreen, module="graphics.screens.inventoryScreen") Factory.register("SettingsScreen", cls=SettingsScreen, module="graphics.screens.settingsScreen") Factory.register("MultiLangLabel", cls=MultiLangLabel, module="graphics.customWidgets.multiLangLabel") Factory.register("BaseLayout", cls=BaseLayout, module="graphics.customWidgets.baseLayout") Factory.register("BetterScatter", cls=BetterScatter, module="graphics.customWidgets.betterScatter") Factory.register("BetterButton", cls=BetterButton, module="graphics.customWidgets.betterButton") Factory.register("TextBetterButton", cls=TextBetterButton, module="graphics.customWidgets.betterButton") Factory.register("FlatBetterButton", cls=FlatBetterButton, module="graphics.customWidgets.betterButton") Factory.register("BuildingButtonsHandler", cls=BuildingButtonsHandler, module="graphics.customWidgets.buildingButtonsHandler") Factory.register("MergeGUI", cls=MergeGUI, module="graphics.customWidgets.mergeItemHolder") Factory.register("ResourceMinerManager", cls=ResourceMinerManager, module="graphics.customWidgets.resourceMinerManager") Logger.info("All classes have been assigned to Factory")
def show_popup(self): self.pop_up = Factory.PopupBox() self.pop_up.update_pop_up_text('Running some task...') self.pop_up.open()
DS_KVS = os.path.join(DS_ROOT,'ds_kvs') DS_CLASSES = [c[:-3] for c in os.listdir(DS_KVS) class Root(FloatLayout): screen_manager = ObjectProperty(None) child = ObjectProperty(None) def change_kv(self,*largs): child = self.screen_manager.current_screen.children[0] with open(child.kv_file, 'rb') as file: text = file.read().decode('utf8') kv_container = self.screen_manager.current_screen try: parser = Parser(content = txt) kv_container.clear_widgets() widget = Factory.get(parser.root.name)() Builder._apply_rule(widget,parser.root,parser.root) kv_container.add_widget(widget) except (SyntaxError, ParserException) as e: self.show_error(e) except Exception as e: self.show_error(e) class DS(App): pass Factory.register('Root', cls=Root) if __name__=='__main__': DS().run()
def generate_screen(self, job_dict, item_ink_key_dict): self.clear_screen() self.add_widget(Factory.RunPageLayout(job_dict, item_ink_key_dict))
def unfocus(self): '''Unfocus the window ''' self.parent._bk.widget_unfocus(self._id) self._have_focus = 0 def on_widget_paint(self, texture): with self.canvas: self._g_color = Color(1, 1, 1) self._g_rect = Rectangle(texture = texture, size=self.size, pos = self.pos) self._g_rect.tex_coords = (0, 1, 1, 1, 1, 0, 0, 0) self.canvas.ask_update() Factory.register('Webbrowser', cls=Webbrowser) if __name__ == '__main__': from kivy.app import App class WebbrowserApp(App): def build(self): wb = Webbrowser(size_hint=(None, None), size=(300, 64), transparency=True) with open('bleh.html', 'w') as fd: fd.write('<h1><span style="color: #ff0000">Hello</span>' '<span style="color: #00ff00">World</span></h1>') wb.open_filename('bleh.html') return wb
self._stack_cont_action_view.pop() self.clear_widgets() if self._stack_cont_action_view == []: super(ActionBar, self).add_widget(self.action_view) else: super(ActionBar, self).add_widget(self._stack_cont_action_view[-1]) if __name__ == "__main__": from kivy.base import runTouchApp from kivy.uix.floatlayout import FloatLayout from kivy.factory import Factory # XXX clean the first registration done from '__main__' here. # otherwise kivy.uix.actionbar.ActionPrevious != __main__.ActionPrevious Factory.unregister('ActionPrevious') Builder.load_string(''' <MainWindow>: ActionBar: pos_hint: {'top':1} ActionView: use_separator: True ActionPrevious: title: 'Action Bar' with_previous: False ActionOverflow: ActionButton: text: 'Btn0' icon: 'atlas://data/images/defaulttheme/audio-volume-high' ActionButton:
def test_widget_popup(self, *args): EventLoop.ensure_window() self._win = EventLoop.window self.clean_garbage() # build the widget tree & add Window as the main EL self.root = self.builder.Builder.load_string( KV, filename="InspectorTestCase.KV") self.render(self.root) self.assertLess(len(self._win.children), 2) # checked widget popup = self.root.ids.popup popup_exp = self.root.ids.popup.text # activate inspector with root as ctx inspector.start(self._win, self.root) self.advance_frames(1) # pull the Inspector drawer from bottom, # but don't inspect yet! ins = self.root.inspector ins.inspect_enabled = False ins.activated = True self.assertTrue(ins.at_bottom) # touch button center to open the popup touch = UnitTestTouch(*popup.center) touch.touch_down() touch.touch_up() self.advance_frames(1) # start inspecting ins.inspect_enabled = True self.advance_frames(1) # inspect FirstModal's button touch.touch_down() touch.touch_up() self.advance_frames(1) # open Inspector properties ins.show_widget_info() self.advance_frames(2) # check if the popup is selected # stored instance self.assertIsInstance(ins.widget, Factory.Button) self.assertIsInstance(ins.widget.parent, Factory.FirstModal) # check with new Popup instance if the properties match temp_popup = Factory.FirstModal() temp_popup_exp = temp_popup.ids.firstmodal.text self.assertEqual(ins.widget.text, temp_popup_exp) # data in properties for node in ins.treeview.iterate_all_nodes(): lkey = getattr(node.ids, 'lkey', None) if not lkey: continue if lkey.text == 'text': ltext = node.ids.ltext # slice because the string is displayed with quotes self.assertEqual(ltext.text[1:-1], temp_popup_exp) break del temp_popup # close popup ins.inspect_enabled = False touch = UnitTestTouch(0, 0) touch.touch_down() touch.touch_up() self.advance_frames(10) # close Inspector ins.activated = False self.render(self.root) self.advance_frames(10) # stop Inspector completely inspector.stop(self._win, self.root) self.assertLess(len(self._win.children), 2) self.render(self.root)
def add_output(self, address, amount): b = Factory.OutputItem() b.address = address b.value = self.app.format_amount_and_units(amount) self.add_widget(b)
def __init__(self, **kwargs): # 起動時に各画面を作成して使い回す self.window1 = Factory.Window1() self.window2 = Factory.Window2() super(MainRoot, self).__init__(**kwargs)
from electrum.paymentrequest import PR_UNPAID, PR_PAID, PR_UNKNOWN, PR_EXPIRED from kivy.app import App from kivy.core.window import Window from kivy.logger import Logger from kivy.utils import platform from kivy.properties import (OptionProperty, AliasProperty, ObjectProperty, StringProperty, ListProperty, BooleanProperty) from kivy.cache import Cache from kivy.clock import Clock from kivy.factory import Factory from kivy.metrics import inch, metrics from kivy.lang import Builder # lazy imports for factory so that widgets can be used in kv Factory.register('InstallWizard', module='electrum_gui.kivy.uix.dialogs.installwizard') Factory.register('InfoBubble', module='electrum_gui.kivy.uix.dialogs') Factory.register('ELTextInput', module='electrum_gui.kivy.uix.screens') #from kivy.core.window import Window #Window.softinput_mode = 'below_target' # delayed imports: for startup speed on android notification = app = ref = None util = False # register widget cache for keeping memory down timeout to forever to cache # the data Cache.register('electrum_widgets', timeout=0) from kivy.uix.screenmanager import Screen
import kivy #kivy.require('1.10.0') # replace with your current Kivy version from kivy.uix.behaviors import ButtonBehavior from kivy.uix.image import Image from kivy.factory import Factory class ImageButton(ButtonBehavior, Image): pass Factory.register("ImageButton", cls=ImageButton)
self.runvalid = False # if(self.exportvalid == False): # self.exporttext = "Please selected an export location" # self.exportcolor = [1,0,0,1] # self.runvalid = False # ^ code that was not implemented return self.runvalid #Go button event def gopress(self): #checks if download location and a style has been selected if(self.runable() == True): self.finished = os.path.relpath(self.downloadtext,os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) c.go(self.finished,int(self.stylenum)) self.location = self.downloadtext.split('/') self.finishname = self.location[len(self.location)-1] self.finishname = self.finishname.split('.')[0] self.addfinished(self.finishname) # runs the application class MainGUIApp(App): def build(self): #imports the gui.kv file, so we can have the gui the way it looks self.load_kv('gui.kv') return MainGUI() Factory.register('DownloadDialog',cls=DownloadDialog) #run the application MGApp = MainGUIApp() MGApp.run()
#Window.softinput_mode = 'below_target' # delayed imports: for startup speed on android notification = app = ref = None util = False # register widget cache for keeping memory down timeout to forever to cache # the data Cache.register('electrum_mac_widgets', timeout=0) from kivy.uix.screenmanager import Screen from kivy.uix.tabbedpanel import TabbedPanel from kivy.uix.label import Label from kivy.core.clipboard import Clipboard Factory.register('TabbedCarousel', module='electrum_mac_gui.kivy.uix.screens') # Register fonts without this you won't be able to use bold/italic... # inside markup. from kivy.core.text import Label Label.register('Roboto', 'gui/kivy/data/fonts/Roboto.ttf', 'gui/kivy/data/fonts/Roboto.ttf', 'gui/kivy/data/fonts/Roboto-Bold.ttf', 'gui/kivy/data/fonts/Roboto-Bold.ttf') from electrum_mac.util import base_units class ElectrumWindow(App):
def build(self): self.bind(on_start=self.post_build_init) self.sm.add_widget(Factory.LoginScreen()) self.sm.add_widget(Factory.HomeScreen()) self.sm.current = "login_screen" return self.sm
current_time = component.current_time fade_out_start = component.fade_out_start time = component.time fade_out_time = time - fade_out_start if current_time >= time: self.gameworld.remove_entity(entity_id) self.make_entity() if current_time < fade_out_start: color_comp.a = lerp(0., 255., current_time / fade_out_start) else: color_comp.a = lerp(255., 0., (current_time - fade_out_start) / fade_out_time) Factory.register('FadingSystem', cls=FadingSystem) class TestGame(Widget): def on_kv_post(self, *args): self.gameworld.init_gameworld( ['color', 'position', 'renderer', 'fade'], callback=self.init_game) def init_game(self): self.setup_states() self.load_resources() self.set_state() self.draw_some_stuff() def load_resources(self):
self.border_point = pos self.hovered = inside if inside: self.dispatch('on_enter') else: self.dispatch('on_leave') def on_enter(self): pass def on_leave(self): pass from kivy.factory import Factory Factory.register('HoverBehavior', HoverBehavior) class HoverButton(Button, HoverBehavior): def on_enter(self, *args): print(self.text) print("You are in, through this point", self.border_point) Window.set_system_cursor('hand') def on_leave(self, *args): print("You left through this point", self.border_point) Window.set_system_cursor('arrow') class ButtonApp(App): def __init__(self, **kwargs):
"""Shake effect animation.""" Animation.stop_all(self) (Animation(translate_x=50, t="out_quad", d=0.02) + Animation(translate_x=0, t="out_elastic", d=0.5)).start(self) def wobble(self): """Wobble effect animation.""" Animation.stop_all(self) ((Animation(scale_y=0.7, t="out_quad", d=0.03) & Animation(scale_x=1.4, t="out_quad", d=0.03)) + (Animation(scale_y=1, t="out_elastic", d=0.5) & Animation(scale_x=1, t="out_elastic", d=0.4))).start(self) def twist(self): """Twist effect animation.""" Animation.stop_all(self) (Animation(rotate=25, t="out_quad", d=0.05) + Animation(rotate=0, t="out_elastic", d=0.5)).start(self) def shrink(self): """Shrink effect animation.""" Animation.stop_all(self) Animation(scale_x=0.95, scale_y=0.95, t="out_quad", d=0.1).start(self) Factory.register("MagicBehavior", cls=MagicBehavior)
def load_string(self, string, **kwargs): '''Insert a string into the Language Builder and return the root widget (if defined) of the kv string. :Parameters: `rulesonly`: bool, defaults to False If True, the Builder will raise an exception if you have a root widget inside the definition. `filename`: str, defaults to None If specified, the filename used to index the kv rules. The filename parameter can be used to unload kv strings in the same way as you unload kv files. This can be achieved using pseudo file names e.g.:: Build.load_string(""" <MyRule>: Label: text="Hello" """, filename="myrule.kv") can be unloaded via:: Build.unload_file("myrule.kv") ''' kwargs.setdefault('rulesonly', False) self._current_filename = fn = kwargs.get('filename', None) # put a warning if a file is loaded multiple times if fn in self.files: Logger.warning('Lang: The file {} is loaded multiples times, ' 'you might have unwanted behaviors.'.format(fn)) try: # parse the string parser = Parser(content=string, filename=fn) # merge rules with our rules self.rules.extend(parser.rules) self._clear_matchcache() # add the template found by the parser into ours for name, cls, template in parser.templates: self.templates[name] = (cls, template, fn) Factory.register(name, cls=partial(self.template, name), is_template=True, warn=True) # register all the dynamic classes for name, baseclasses in parser.dynamic_classes.items(): Factory.register(name, baseclasses=baseclasses, filename=fn, warn=True) # create root object is exist if kwargs['rulesonly'] and parser.root: filename = kwargs.get('rulesonly', '<string>') raise Exception('The file <%s> contain also non-rules ' 'directives' % filename) # save the loaded files only if there is a root without # template/dynamic classes if fn and (parser.templates or parser.dynamic_classes or parser.rules): self.files.append(fn) if parser.root: widget = Factory.get(parser.root.name)(__no_builder=True) rule_children = [] widget.apply_class_lang_rules(root=widget, rule_children=rule_children) self._apply_rule(widget, parser.root, parser.root, rule_children=rule_children) for child in rule_children: child.dispatch('on_kv_post', widget) widget.dispatch('on_kv_post', widget) return widget finally: self._current_filename = None
def build(self): Window.bind(on_keyboard=self.key_input) self.root = Factory.MainLayout()
def generate_ink_key(self, ink_key_dict): self.clear_widgets() self.add_widget(Factory.InkKeyBoxLayout(ink_key_dict))
class FirebaseLoginScreen(Screen, EventDispatcher): """Use this widget as a complete module to incorporate Firebase user authentication in your app. To use this module, instantiate the login screen in the KV language like so: FirebaseLoginScreen: web_api_key: "your_firebase_web_api_key" debug: True # Not necessary, but will print out debug information on_login_success: # do something here In your main App class, set the three following fields to dictate the color scheme of the login screens. Example: class MainApp(App): primary_color: (1, 0, 0, 1) secondary_color: (0, 1, 0, 1) tertiary_color: (0, 0, 1, 1) pass NOTES: 1) You MUST set the web api key or it is impossible for the login screen to function properly. 2) You probably want to wrap the FirebaseLoginScreen in a ScreenManager. 3) You probably want to switch screens to a Screen in your project once the user has logged in (write that code in the on_login_success function shown in the example above). 4) You can set the colors (primary_color, secondary_color, tertiary_color) to be whatever you like. """ # Firebase Project meta info - MUST BE CONFIGURED BY DEVELOPER web_api_key = StringProperty() # From Settings tab in Firebase project # Firebase Authentication Credentials - what developers want to retrieve refresh_token = "" localId = "" idToken = "" # Properties used to send events to update some parts of the UI login_success = BooleanProperty(False) # Called upon successful sign in sign_up_msg = StringProperty() sign_in_msg = StringProperty() email_exists = BooleanProperty(False) email_not_found = BooleanProperty(False) debug = True popup = Factory.LoadingPopup() popup.background = folder + "/transparent_image.png" def on_login_success(self, *args): """Overwrite this method to switch to your app's home screen. """ print("Logged in successfully", args) def on_web_api_key(self, *args): """When the web api key is set, look for an existing account in local memory. """ # Try to load the users info if they've already created an account self.refresh_token_file = App.get_running_app().user_data_dir + "/refresh_token.txt" if self.debug: print("Looking for a refresh token in:", self.refresh_token_file) if os.path.exists(self.refresh_token_file): self.load_saved_account() def sign_up(self, email, password): """If you don't want to use Firebase, just overwrite this method and do whatever you need to do to sign the user up with their email and password. """ if self.debug: print("Attempting to create a new account: ", email, password) signup_url = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=" + self.web_api_key signup_payload = dumps( {"email": email, "password": password, "returnSecureToken": "true"}) UrlRequest(signup_url, req_body=signup_payload, on_success=self.successful_login, on_failure=self.sign_up_failure, on_error=self.sign_up_error) def successful_login(self, urlrequest, log_in_data): """Collects info from Firebase upon successfully registering a new user. """ self.hide_loading_screen() self.refresh_token = log_in_data['refreshToken'] self.localId = log_in_data['localId'] self.idToken = log_in_data['idToken'] self.save_refresh_token(self.refresh_token) self.login_success = True if self.debug: print("Successfully logged in a user: "******"""Displays an error message to the user if their attempt to log in was invalid. """ self.hide_loading_screen() self.email_exists = False # Triggers hiding the sign in button print(failure_data) msg = failure_data['error']['message'].replace("_", " ").capitalize() # Check if the error msg is the same as the last one if msg == self.sign_up_msg: # Need to modify it somehow to make the error popup display msg = " " + msg + " " self.sign_up_msg = msg if msg == "Email exists": self.email_exists = True if self.debug: print("Couldn't sign the user up: ", failure_data) def sign_up_error(self, *args): self.hide_loading_screen() if self.debug: print("Sign up Error: ", args) def sign_in(self, email, password): """Called when the "Log in" button is pressed. Sends the user's email and password in an HTTP request to the Firebase Authentication service. """ if self.debug: print("Attempting to sign user in: ", email, password) sign_in_url = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=" + self.web_api_key sign_in_payload = dumps( {"email": email, "password": password, "returnSecureToken": True}) UrlRequest(sign_in_url, req_body=sign_in_payload, on_success=self.successful_login, on_failure=self.sign_in_failure, on_error=self.sign_in_error) def sign_in_failure(self, urlrequest, failure_data): """Displays an error message to the user if their attempt to create an account was invalid. """ self.hide_loading_screen() self.email_not_found = False # Triggers hiding the sign in button print(failure_data) msg = failure_data['error']['message'].replace("_", " ").capitalize() # Check if the error msg is the same as the last one if msg == self.sign_in_msg: # Need to modify it somehow to make the error popup display msg = " " + msg + " " self.sign_in_msg = msg if msg == "Email not found": self.email_not_found = True if self.debug: print("Couldn't sign the user in: ", failure_data) def sign_in_error(self, *args): self.hide_loading_screen() if self.debug: print("Sign in error", args) def reset_password(self, email): """Called when the "Reset password" button is pressed. Sends an automated email on behalf of your Firebase project to the user with a link to reset the password. This email can be customized to say whatever you want. Simply change the content of the template by going to Authentication (in your Firebase project) -> Templates -> Password reset """ if self.debug: print("Attempting to send a password reset email to: ", email) reset_pw_url = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/getOobConfirmationCode?key=" + self.web_api_key reset_pw_data = dumps({"email": email, "requestType": "PASSWORD_RESET"}) UrlRequest(reset_pw_url, req_body=reset_pw_data, on_success=self.successful_reset, on_failure=self.sign_in_failure, on_error=self.sign_in_error) def successful_reset(self, urlrequest, reset_data): """Notifies the user that a password reset email has been sent to them. """ self.hide_loading_screen() if self.debug: print("Successfully sent a password reset email", reset_data) self.sign_in_msg = "Reset password instructions sent to your email." def save_refresh_token(self, refresh_token): """Saves the refresh token in a local file to enable automatic sign in next time the app is opened. """ if self.debug: print("Saving the refresh token to file: ", self.refresh_token_file) with open(self.refresh_token_file, "w") as f: f.write(refresh_token) def load_refresh_token(self): """Reads the refresh token from local storage. """ if self.debug: print("Loading refresh token from file: ", self.refresh_token_file) with open(self.refresh_token_file, "r") as f: self.refresh_token = f.read() def load_saved_account(self): """Uses the refresh token to get the user's idToken and localId by sending it as a request to Google/Firebase's REST API. Called immediately when a web_api_key is set and if the refresh token file exists. """ if self.debug: print("Attempting to log in a user automatically using a refresh token.") self.load_refresh_token() refresh_url = "https://securetoken.googleapis.com/v1/token?key=" + self.web_api_key refresh_payload = dumps({"grant_type": "refresh_token", "refresh_token": self.refresh_token}) UrlRequest(refresh_url, req_body=refresh_payload, on_success=self.successful_account_load, on_failure=self.failed_account_load, on_error=self.failed_account_load) def successful_account_load(self, urlrequest, loaded_data): """Sets the idToken and localId variables upon successfully loading an account using the refresh token. """ self.hide_loading_screen() if self.debug: print("Successfully logged a user in automatically using the refresh token") self.idToken = loaded_data['id_token'] self.localId = loaded_data['user_id'] self.login_success = True def failed_account_load(self, *args): self.hide_loading_screen() if self.debug: print("Failed to load an account.", args) def display_loading_screen(self, *args): self.popup.color = self.tertiary_color self.popup.open() def hide_loading_screen(self, *args): self.popup.dismiss()
def build(self): return Factory.ScreenManager()
def render_conditions(self, conditions_description): conditions_widget = Factory.UnknownConditions() # <3> conditions_widget.conditions = conditions_description self.conditions.clear_widgets() self.conditions.add_widget(conditions_widget) # <4>
def show_popup(self, title, content): popup = Factory.Popup(title=title, content=Label(text=content, text_size=(Window.size[0] * 3/4, None)), size_hint=(3/4, 3/4)) popup.open()
#Window.softinput_mode = 'below_target' # delayed imports: for startup speed on android notification = app = ref = None util = False # register widget cache for keeping memory down timeout to forever to cache # the data Cache.register('electrum_bitcoinprivate_widgets', timeout=0) from kivy.uix.screenmanager import Screen from kivy.uix.tabbedpanel import TabbedPanel from kivy.uix.label import Label from kivy.core.clipboard import Clipboard Factory.register('TabbedCarousel', module='electrum_bitcoinprivate_gui.kivy.uix.screens') # Register fonts without this you won't be able to use bold/italic... # inside markup. from kivy.core.text import Label Label.register('Roboto', 'gui/kivy/data/fonts/Roboto.ttf', 'gui/kivy/data/fonts/Roboto.ttf', 'gui/kivy/data/fonts/Roboto-Bold.ttf', 'gui/kivy/data/fonts/Roboto-Bold.ttf') from electrum_bitcoinprivate.util import base_units class ElectrumWindow(App):
def build(self): self.theflag = 0 self.theflag0 = 0 self.distan = 1000 # дистанция до начальной точки (0,0,-50) что бы ничего не было за экраном (надо будет выстваить на изменение) bl = BoxLayout(orientation='vertical', size_hint=(.15, 1), spacing=10, padding=10) # левая панель al = AnchorLayout(anchor_x='left', anchor_y='center') # основная система интерфейса layout = GridLayout(cols=2, spacing=3, size_hint=(1, 1)) #сетка для кнопок поворота matrix = np.load('matrix0.npy', allow_pickle=True) print(matrix) #a=matrix['self.a'] print(a) counter = int(int(matrix.size) / 2) x = np.zeros(counter) y = np.zeros(counter) z = np.zeros(counter) soe = np.zeros((counter, counter)) for i in range(2): if (i == 0): for j in range(counter): for k in range(3): #a=matrix[i,j] if (k == 0): x[j] = a[k] * 10 elif (k == 1): y[j] = a[k] * 10 else: z[j] = a[k] * 10 else: for j in range(counter): a = matrix[i, j] for k in range(counter): soe[j][k] = a[k] print(x, y, z) print(soe) # кнопка загрузки координат loader = Button(text='Load', on_press=self.load) bl.add_widget(loader) #starter = Button(text='Построить', on_press = self.letstart) #bl.add_widget(starter) bl.add_widget(Widget()) # create renderer self.renderer = Renderer() # create scene scene = Scene() #lines k0 = 0 k1 = 0 lines_list = [] for i in soe: for j in i: if (j == 1): line0_geo = BoxGeometry( 1, int(((y[k0] - y[k1])**2 + (x[k0] - x[k1])**2 + (z[k0] - z[k1])**2)**0.5), 1) #print(int(((abs(x[k0]-x[k1]) + abs(y[k0]-y[k1])+ abs(z[k0]-z[k1]))**0.5)),'length') #print(int(abs(y[k0]-y[k1]) + abs(x[k0]-x[k1])+ abs(z[k0]-z[k1]))) line0_mat = Material() self.line0 = Mesh( geometry=line0_geo, material=line0_mat) # default pos == (0, 0, 0) self.line0.pos.x = int((x[k0] + x[k1]) / 2) self.line0.pos.y = int((y[k0] + y[k1]) / 2) self.line0.pos.z = int((z[k0] + z[k1]) / 2) - self.distan if y[k0] - y[k1] == 0 and x[k0] - x[ k1] == 0 and z[k0] - z[k1] != 0: self.line0.rotation.x = 90 elif y[k0] - y[k1] == 0 and x[k0] - x[k1] != 0 and z[ k0] - z[k1] == 0: self.line0.rotation.z = 90 elif y[k0] - y[k1] != 0 and x[k0] - x[k1] == 0 and z[ k0] - z[k1] == 0: ### fff = 0 elif y[k0] - y[k1] != 0 and x[k0] - x[k1] != 0 and z[ k0] - z[k1] == 0: self.line0.rotation.z = math.atan( (x[k0] - x[k1]) / (y[k0] - y[k1])) / math.pi * 180 elif y[k0] - y[k1] != 0 and x[k0] - x[ k1] == 0 and z[k0] - z[k1] != 0: #self.line0.rotation.x = math.atan((z[k0]-z[k1])/(y[k0]-y[k1]))/math.pi*180 self.line0.rotation.x = math.acos( abs(y[k0] - y[k1]) / ((x[k0] - x[k1])**2 + (y[k0] - y[k1])**2 + (z[k0] - z[k1])**2)**0.5) / math.pi * 180 #print() elif y[k0] - y[k1] == 0 and x[k0] - x[k1] != 0 and z[ k0] - z[k1] != 0: self.line0.rotation.z = math.atan( (x[k0] - x[k1]) / (z[k0] - z[k1])) / math.pi * 180 * -1 self.line0.rotation.x = 90 ### elif y[k0] - y[k1] != 0 and x[k0] - x[k1] != 0 and z[ k0] - z[k1] != 0: if ((x[k0] < x[k1] and y[k0] < y[k1]) or (x[k0] > x[k1] and y[k0] > y[k1])): #self.line0.rotation.z = math.atan((abs(z[k0]-z[k1]))/1.5/(abs(y[k0]-y[k1])))/math.pi*180 self.line0.rotation.z = math.acos( abs(y[k0] - y[k1]) / ((x[k0] - x[k1])**2 + (y[k0] - y[k1])**2 + (0)**2)**0.5) / math.pi * 180 * -1 #проблема else: self.line0.rotation.z = math.acos( abs(y[k0] - y[k1]) / ((x[k0] - x[k1])**2 + (y[k0] - y[k1])**2 + (0)**2)**0.5) / math.pi * 180 #self.line0.rotation.x = math.atan((1.25*abs(x[k0]-x[k1]))/(abs(y[k0]-y[k1])))/math.pi*180*-1 if ((z[k0] < z[k1] and y[k0] < y[k1]) or (z[k0] > z[k1] and y[k0] > y[k1])): self.line0.rotation.x = math.acos( abs(y[k0] - y[k1]) / ((0)**2 + (y[k0] - y[k1])**2 + (z[k0] - z[k1])**2)**0.5) / math.pi * 180 #проблема else: self.line0.rotation.x = math.acos( abs(y[k0] - y[k1]) / ((0)**2 + (y[k0] - y[k1])**2 + (z[k0] - z[k1])**2)**0.5) / math.pi * 180 * -1 #self.line0.rotation.x = math.acos(abs(y[k0]-y[k1])/((0)**2+(y[k0]-y[k1])**2+(z[k0]-z[k1])**2)**0.5)/math.pi*180*-1#there print(self.line0.rotation.z) print(self.line0.rotation.x) lines_list.append(self.line0) k1 += 1 k0 += 1 k1 = 0 line0_geo = BoxGeometry(1, y[1] - y[0], 1) line0_mat = Material() self.line0 = Mesh(geometry=line0_geo, material=line0_mat) # default pos == (0, 0, 0) self.line0.pos.z = int(z[0]) - self.distan #self.line3.rotation.x = 90 #points point_list = [] sumx = 0 sumy = 0 sumz = 0 sumcount = 0 loader = OBJLoader() for i in range(counter): point_geom = SphereGeometry(1.1) point_mat = Material() self.point0 = Mesh(geometry=point_geom, material=point_mat) self.point0.pos.x = int(x[i]) self.point0.pos.y = int(y[i]) self.point0.pos.z = int(z[i]) - self.distan self.point0.scale = (1, 1, 1) point_list.append(self.point0) sumx += self.point0.pos.x sumy += self.point0.pos.y sumz += self.point0.pos.z sumcount += 1 #scene.add(self.point0) point_geom = SphereGeometry() point_mat = Material() self.point1 = Mesh(geometry=point_geom, material=point_mat) self.point1.pos.x = sumx / sumcount self.point1.pos.y = sumy / sumcount self.point1.pos.z = sumz / sumcount self.point1.scale = (1, 1, 1) #scene.add(self.point1) self.camera = PerspectiveCamera( fov=100, # размер окна т.е. чем больше фов тем больше масштаб aspect=0, # "screen" ratio near=1, # рендер от far=10000 # дистанция рендера ) k0 = 0 self.ll = [] for i in soe: for j in i: if (j == 1): self.ll.append(lines_list[k0]) scene.add(lines_list[k0]) k0 += 1 for i in range(counter): scene.add(point_list[i]) pass self.pp = point_list self.renderer.render(scene, self.camera) self.renderer.bind(size=self._adjust_aspect) al.add_widget(self.renderer) bl.add_widget(Factory.Fov()) bl.add_widget(Factory.CamNav()) al.add_widget(bl) return al
from kivy.app import App from kivy.factory import Factory from kivy.lang import Builder Factory.register('QRScanner', module='electrum_cesc_gui.kivy.qr_scanner') class QrScannerDialog(Factory.AnimatedPopup): __events__ = ('on_complete', ) def on_symbols(self, instance, value): instance.stop() self.dismiss() data = value[0].data self.dispatch('on_complete', data) def on_complete(self, x): ''' Default Handler for on_complete event. ''' print x Builder.load_string(''' <QrScannerDialog> title: _(\ '[size=18dp]Hold your QRCode up to the camera[/size][size=7dp]\\n[/size]') title_size: '24sp' border: 7, 7, 7, 7 size_hint: None, None
def __init__(mcs, name, bases, attrs): super(WidgetMetaclass, mcs).__init__(name, bases, attrs) Factory.register(name, cls=mcs)
def do_save(self): gro_list = ListState.instance.convert_to_pool() Factory.SaveDialog(gro_list).open() self.dismiss()
""" A program to register Kivy Cupertino widgets for use in kv lang """ from kivy.factory import Factory Factory.register('CupertinoNavigationBar', module='kivycupertino.uix.bar') Factory.register('CupertinoTabBar', module='kivycupertino.uix.bar') Factory.register('CupertinoButton', module='kivycupertino.uix.button') Factory.register('CupertinoSystemButton', module='kivycupertino.uix.button') Factory.register('CupertinoSymbolButton', module='kivycupertino.uix.button') Factory.register('CupertinoSegmentedControls', module='kivycupertino.uix.control') Factory.register('CupertinoStepper', module='kivycupertino.uix.control') Factory.register('CupertinoProgressBar', module='kivycupertino.uix.indicator') Factory.register('CupertinoAlertDialog', module='kivycupertino.uix.indicator') Factory.register('CupertinoLabel', module='kivycupertino.uix.label') Factory.register('CupertinoScrollView', module='kivycupertino.uix.scrollview') Factory.register('CupertinoSlider', module='kivycupertino.uix.slider') Factory.register('CupertinoSwitch', module='kivycupertino.uix.switch') Factory.register('CupertinoSymbol', module='kivycupertino.uix.symbol') Factory.register('CupertinoTextField', module='kivycupertino.uix.textfield') Factory.register('CupertinoTextView', module='kivycupertino.uix.textfield')