def show_load_popup(self, *args): if os.path.exists(os.path.abspath('saves/')): file_chooser = FileChooserIconView(path="saves") elif os.path.exists(os.path.abspath('../saves')): file_chooser = FileChooserIconView(path="../saves") else: file_chooser = FileChooserIconView(path=".") load_btn = Button(font_name='src/fonts/Enchanted_Land.otf', font_size=24, text='Load', size_hint=(.08, .05)) back_btn = Button(font_name='src/fonts/Enchanted_Land.otf', font_size=24, text='Back', size_hint=(.08, .05), pos_hint={'center_x': .95, 'bottom_y': .05}) content = FloatLayout() content.clear_widgets() content.add_widget(file_chooser) content.add_widget(load_btn) content.add_widget(back_btn) popup = Popup(title="Load a file", content=content) load_callback = lambda load: self.load( file_chooser.path, file_chooser.selection, popup) load_btn.bind(on_release=load_callback) back_btn.bind(on_release=popup.dismiss) popup.open()
def build(self): layout_main = BoxLayout( orientation='vertical', ) text_input = TextInput( font_size=150, height=200, size_hint_y=None, text='default', ) layout = FloatLayout() scatter = Scatter() label = Label( text="default", font_size=150, ) text_input.bind(text=label.setter('text')) layout.add_widget(scatter) scatter.add_widget(label) # Order is important - first is top/left layout_main.add_widget(text_input) layout_main.add_widget(layout) return layout_main
class ScatterLayout(Scatter): '''ScatterLayout class, see module documentation for more information. ''' content = ObjectProperty() def __init__(self, **kw): self.content = FloatLayout() super(ScatterLayout, self).__init__(**kw) if self.content.size != self.size: self.content.size = self.size super(ScatterLayout, self).add_widget(self.content) self.bind(size=self.update_size) def update_size(self, instance, size): self.content.size = size def add_widget(self, *l): self.content.add_widget(*l) def remove_widget(self, *l): self.content.remove_widget(*l) def clear_widgets(self): self.content.clear_widgets()
class Char(Widget): def __init__(self): super(Char, self).__init__() self.layout = FloatLayout() self.sprite = Image( source="assets/morgan-freeman.jpg", texture_size=(30, 50), size=(30, 50), #center_x=Window.width / 2, #center_y=(Window.height / 2) + 150 ) #player = ObjectProperty(None) self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keyboard_down) self.layout.add_widget(self.sprite) def _keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_keyboard_down) self._keyboard = None def _on_keyboard_down(self, keyboard, keycode, text, modifiers): if keycode[1] == 'd': self.player.center_x += 10 elif keycode[1] == 'a': self.player.center_x -= 10 elif keycode[1] == 'w': self.player.center_y += 10 time.sleep(.5) self.player.center_y -= 10 return True
class Workflow: def __init__(self): self.root = FloatLayout() self.states = {} def add_state(self, step, name): self.states[name] = step def set_handler(self, handler): self.handler = handler def return_state(self, parameters): name, parameters = self.handler.send(parameters) self.next_step(name, parameters) def start(self): name, parameters = self.handler.send(None) self.next_step(name, parameters) return self.root def next_step(self, name, parameters): step = self.states[name] widget = step.called_with(self, parameters) self.root.clear_widgets() self.root.add_widget(widget)
def set_background(self): graphics_widget = FloatLayout() for td in self.textures_data: filename,xpos,ypos,width,height = td.split(":") xpos = float(xpos) ypos = float(ypos) image = MyImage(keep_ratio=True, allow_stretch=False, color=(0,0,0,0)) image.set_shadow(False) with image.canvas: Rectangle(texture=self.textures[filename].texture, size=(float(width) * X_BLOCK, float(height) * Y_BLOCK)) scatter = Scatter(do_rotation=False, do_scale=False, do_translation=False) scatter.pos = (xpos * X_BLOCK, ypos * Y_BLOCK) scatter.add_widget(image) graphics_widget.add_widget(scatter) #for td in self.sprites_data: # filename,xpos,ypos,width,height = td.split(":") # xpos = float(xpos) # ypos = float(ypos) # image = MyImage(texture = self.sprites[filename].texture, keep_ratio=True, allow_stretch=False) # image.set_shadow(False) # scatter = Scatter(do_rotation=False, do_scale=False, do_translation=False) # scatter.pos = (xpos * X_BLOCK, (ypos + 4) * Y_BLOCK / 2) # scatter.add_widget(image) # graphics_widget.add_widget(scatter) # scatter.scale = 6 - ypos * 1.5 return graphics_widget
def build(self): # prepare shader list available_shaders = ( shader_pulse, shader_postprocessing, shader_monochrome) self.shader_index = 0 # create our widget tree root = FloatLayout() sw = ShaderWidget() root.add_widget(sw) # add a button and scatter image inside the shader widget btn = Button(text='Hello world', size_hint=(None, None), pos_hint={'center_x': .25, 'center_y': .5}) sw.add_widget(btn) center = Window.width * 0.75 - 256, Window.height * 0.5 - 256 scatter = ScatterImage(source='tex3.jpg', size_hint=(None, None), size=(512, 512), pos=center) sw.add_widget(scatter) # create a button outside the shader widget, to change the current used # shader btn = Button(text='Change fragment shader', size_hint=(1, None), height=50) def change(*largs): sw.fs = available_shaders[self.shader_index] self.shader_index = (self.shader_index + 1) % len(available_shaders) btn.bind(on_release=change) root.add_widget(btn) return root
def build(self): f = FloatLayout() s = Scatter() l = Label(text="Hello!", font_size=150) f.add_widget(s) s.add_widget(l) return f
class CelticKnotwork(App): '''Main tabbed interface, each tab contains its own instance of CelticKnotwork2''' def build(self): ##Instance Variables self.showDots = True self.showGrid = True self.showBreaklines = True self.showSkeleton = True self.showKnot = True self.knotX = 4 self.knotY = 4 self.knotWidth = 8 self.knotWidthView = 8 self.gridUnits = 50 self.gridUnitsView = 50 self.offsetX = 150 self.offsetY = 50 self.totTabs = 1 self.tabNo = 1 ##Main Layout self.layout_main = AnchorLayout(anchor_x = "left", anchor_y="top") self.layout_tabs= FloatLayout(size=(Window.width, Window.height), size_hint=(0.1, 0.08)) ##Top Tab Bar - allowing multiple knots self.tp = TabbedPanel() self.tp.default_tab_text = "Knot 1" self.layout_main.add_widget(self.tp) self.addTab = TabbedPanelHeader(text='+') self.addTab.bind(on_release = self.onPressAddTab) self.addTab = Button(text='+', pos =(Window.width*.9,Window.height*.92)) self.addTab.bind(on_press = self.onPressAddTab) self.tp.default_tab_content = CelticKnotwork2().build() #get tab content from CelticKnotwork2 self.layout_tabs.add_widget(self.addTab) self.layout_main.add_widget(self.layout_tabs) Window.bind(on_resize=self.on_resize) return self.layout_main def onPressAddTab(self, instance): '''Add a tab when "+" button pressed''' self.totTabs += 1 self.tabNo = self.totTabs self.th = TabbedPanelHeader(text='Knot '+str(self.totTabs)) self.th.content = CelticKnotwork2().build() self.tp.add_widget(self.th) self.tp.switch_to(self.th) def on_resize(self, window, height, somethingesle): '''Handles window resize''' self.layout_main.remove_widget(self.layout_tabs) self.layout_tabs= FloatLayout(size=(Window.width, Window.height), size_hint=(0.1, 0.05)) self.addTab = Button(text='+', pos =(Window.width*.9,Window.height*.95)) self.addTab.bind(on_press = self.onPressAddTab) self.layout_tabs.add_widget(self.addTab) self.layout_main.add_widget(self.layout_tabs)
def build(self): root = FloatLayout() self.renderer = Renderer() scene = Scene() camera = PerspectiveCamera(15, 1, 1, 1000) # load obj file loader = OBJLoader() obj_path = os.path.join(os.path.dirname(__file__), "./testnurbs.obj") obj = loader.load(obj_path) scene.add(*obj.children) for obj in scene.children: obj.pos.z = -20 obj.material.specular = .35, .35, .35 # set colors to 3d objects scene.children[0].material.color = 0., .7, 0. # green scene.children[1].material.color = .7, 0., 0. # red scene.children[2].material.color = 0., 0., .7 # blue scene.children[3].material.color = .7, .7, 0. # yellow scene.children[0].material.diffuse = 0., .7, 0. # green scene.children[1].material.diffuse = .7, 0., 0. # red scene.children[2].material.diffuse = 0., 0., .7 # blue scene.children[3].material.diffuse = .7, .7, 0. # yellow self.renderer.render(scene, camera) root.add_widget(self.renderer) self.renderer.bind(size=self._adjust_aspect) return root
def build(self): layout = FloatLayout() cam = Camera( play=True, resolution=(640,480), size_hint=(1.0, 1.0), pos=(0, 0) ) def save_camera_snapshot(*args): import time name = time.asctime() # This requires Kivy v1.9.0 (I'm using v1.7.2) cam.export_to_png( name ) btnSave = Button( text = 'Save', size_hint = (1.0,0.1) ) btnSave.bind( on_press = save_camera_snapshot ) layout.add_widget( cam ) layout.add_widget( btnSave ) return layout
def setup_battle(self, dt=None): self.graphics_widget.remove_widget(self.button_reset) self.graphics_widget.remove_widget(self.image_score) self.graphics_widget.remove_widget(self.progress_bar) if self.level == 11: graphics_widget = FloatLayout() image = Image(source = PATH + "end.png", keep_ratio=False, allow_stretch=True,\ size=(SCREEN_WIDTH, SCREEN_HEIGHT), size_hint=(None, None), pos=(0,0)) graphics_widget.add_widget(image) graphics_widget.add_widget(self.button_reset) screen = Screen(name="end") screen.add_widget(graphics_widget) self.add_widget(screen) self.current=screen.name else: self.get_level_data() graphics_widget = self.set_background() screen = Screen(name=str(self.level)) screen.add_widget(graphics_widget) self.graphics_widget = graphics_widget self.add_widget(screen) self.current=screen.name if self.score_threshold > 0: self.level_score = - self.score_threshold else: self.level_score = 0 self.image_score.set_score(self.level_score) if self.level < 3: self.start_battle() else: self.schedule(self.start_battle, 0) #WAS 2 self.graphics_widget.add_widget(self.button_reset) self.graphics_widget.add_widget(self.progress_bar) self.graphics_widget.add_widget(self.image_score)
class SettingPicture(SettingFile): ''' let the user select a picture from a folder ''' def __init__(self, **kwargs): self.oLayout =FloatLayout(size_hint=(1, 1)) super(SettingPicture, self).__init__(**kwargs) uPicFN=self.value try: uPicFN = AdjustPathToOs(ReplaceVars(self.value)) self.oPic=Image(source=ToAtlas(uPicFN),size_hint=(1, 1), pos_hint={'x':0.0, 'y':0.0}) oBackFN=AdjustPathToOs(oORCA.uResourcesPath+"/pics/imagepicker_background.png") self.oBack=Image(source=ToAtlas(oBackFN),size_hint=(1, 1), pos_hint={'x':0.0, 'y':0.0}) self.oLayout.add_widget(self.oBack) self.oLayout.add_widget(self.oPic) self.add_widget(self.oLayout) self.content.children[1].text='' except Exception as e: uMsg=u'Settings: Picture: can\'t load image file: '+ToUnicode(e)+ " "+uPicFN Logger.error (uMsg) def _validate(self, instance): ''' displays the folder ''' SettingFile._validate(self,instance) self.oPic.source=ToAtlas(AdjustPathToOs(self.value)) self.content.children[1].text=''
def build(self): wid = StencilTestWidget(size_hint=(None, None), size=Window.size) label = Label(text='0') btn_add500 = Button(text='+ 200 rects') btn_add500.bind(on_press=partial(self.add_rects, label, wid, 200)) btn_reset = Button(text='Reset Rectangles') btn_reset.bind(on_press=partial(self.reset_rects, label, wid)) btn_stencil = Button(text='Reset Stencil') btn_stencil.bind(on_press=partial(self.reset_stencil, wid)) layout = BoxLayout(size_hint=(1, None), height=50) layout.add_widget(btn_add500) layout.add_widget(btn_reset) layout.add_widget(btn_stencil) layout.add_widget(label) root = BoxLayout(orientation='vertical') rfl = FloatLayout() rfl.add_widget(wid) root.add_widget(rfl) root.add_widget(layout) return root
class TextAlignApp(App): def select(self, case): for _child in self.selector.grid.children[:]: self.selector.grid.remove_widget(_child) for valign in ('bottom', 'middle', 'top'): for halign in ('left', 'center', 'right'): label = BoundedLabel(text='V: %s\nH: %s' % (valign, halign), size_hint=(None, None), size=(150, 150), halign=halign, valign=valign) if case == 0: label.text_size = (None, None) elif case == 1: label.text_size = (label.width, None) elif case == 2: label.text_size = (None, label.height) else: label.text_size = label.size self.selector.grid.add_widget(label) self.selector.grid.bind(minimum_size=self.selector.grid.setter('size')) def build(self): self.root = FloatLayout() self.selector = Selector(app=self) self.root.add_widget(self.selector) self.grid = None self.select(0) return self.root
def build(self): root = FloatLayout() bx = BoxLayout() bx.add_widget(Button()) bx.add_widget(Button()) bx2 = BoxLayout() bx2.add_widget(Button()) bx2.add_widget(Button()) bx2.add_widget(Button()) spl = Splitter( size_hint=(1, .25), pos_hint = {'top': 1}, sizable_from = 'bottom') spl1 = Splitter( sizable_from='left', size_hint=(None, 1), width=90) spl1.add_widget(Button()) bx.add_widget(spl1) spl.add_widget(bx) spl2 = Splitter(size_hint=(.25, 1)) spl2.add_widget(bx2) spl2.sizable_from = 'right' root.add_widget(spl) root.add_widget(spl2) return root
def build(self): # 'atlas://VFX/smoke_particles/VFX_SmokeParticle' fl = FloatLayout(pos=(0,0),size=Window.size) fl.add_widget(CBL_DebugPanel(pos=(0,0),size=(100,50))) for dummy in range(5): fl.add_widget(ParticleEmitter(size = (128,128), size_hint=(None,None), pos = (randint(100,Window.width-100),randint(100,Window.height-100)))) return fl
class bitfluiApp(App): def build(self): self.root = FloatLayout() self.selector = Selector(app=self) self.root.add_widget(self.selector) return self.root
class KeyPadApp(App): kps = None def build(self): self.root = FloatLayout() self.kps=KeyPadScreen() self.root.add_widget(self.kps) return self.root
def build(self): name1 = 'Name1' lastname1 = 'Last1' name2 = 'Name2' name3 = 'Name3' name4 = 'Name4' name5 = 'Name5' f = FloatLayout() button_layout = BoxLayout(pos_hint={'x': 0, 'center_y': .5}, size_hint=(1, 1), orientation='vertical') with button_layout.canvas.before: Color(.5, .5, .5, .2) self.rect = Rectangle(size=button_layout.size, pos=button_layout.pos) name1_button = Button(font_size=25, text=name1+lastname1, size=(150,150)) name2_button = Button(font_size=25, text=name2, size=(150,150)) name3_button = Button(font_size=25, text=name3, size=(150,150)) name4_button = Button(font_size=25, text=name4, size=(150,150)) name5_button = Button(font_size=25, text=name5, size=(150,150)) #name1_button.bind(on_release=self.get_flickr_images(name1)) name2_button.bind(on_release=self.on_touch_down) button_layout.add_widget(name1_button) button_layout.add_widget(name2_button) button_layout.add_widget(name3_button) button_layout.add_widget(name4_button) button_layout.add_widget(name5_button) #s = Scatter(size_hint=(None, None), size=(450,250), pos=(300, 300), do_rotation=False, do_scale=False) #s.add_widget(button_layout) #f.add_widget(s) f.add_widget(button_layout) return f
def build(self): # create root widget root_widget = FloatLayout() box = BoxLayout(orientation='vertical', size_hint=(None, None), size=(400, 200), spacing=dp(20), padding=dp(20), pos_hint={'center_x': .5, 'center_y':.5}) # create the labels and the textinputs lbl_user = Label(text='User Name:') lbl_password = Label(text='Password') ti_user = TextInput() ti_password = TextInput(password=True) # create the containers for the labels and textinputs grid_user_pass = GridLayout(rows=2, cols=2, spacing=dp(20)) # create the ok button my_but_is_ok = Button(text='OK') my_but_is_ok.bind(on_release=lambda *args: self.check_user(ti_user.text, ti_password.text)) # add the labels and input fields to the container grid_user_pass.add_widget(lbl_user) grid_user_pass.add_widget(ti_user) grid_user_pass.add_widget(lbl_password) grid_user_pass.add_widget(ti_password) # add the grid_container into it's container box.add_widget(grid_user_pass) root_widget.add_widget(box) # add the ok button at the bottom of the grid box.add_widget(my_but_is_ok) return root_widget
class AnnotatorApp(App): def build(self): self.root = FloatLayout() box = BoxLayout( padding=10, spacing=10, size_hint=(1,None), pos_hint={'top':1}, height=44) image = Image( size_hint=(None,None), size=(30,30), source='hand-icon.png') label = Label( height=24, text='Annotator') with label.canvas: Color(1,1,1,.8) box.add_widget(image) box.add_widget(label) self.root.add_widget(box) imd = ImageDisplay() self.root.add_widget(imd) self.icon = 'hand-icon.png'
def __init__(self, **kwargs): super(case, self).__init__(**kwargs) box = FloatLayout() graph = Graph(xlabel='X', ylabel='Y', x_ticks_minor=5, x_ticks_major=25, y_ticks_major=1, y_grid_label=True, x_grid_label=True, padding=5, x_grid=True, y_grid=True, xmin=-0, xmax=20, ymin=0, ymax=10) plot = LinePlot() # plot.points = [(x, sin(x / 10.)) for x in range(0, 101)] # data = np.array([[0,0], [1,1],[2,2]]) data = collections.deque(maxlen = 20) time = collections.deque(maxlen = 20) d = (0,1,2,3,4,5,6,7,8,9) t = (0,1,2,3,4,5,6,7,8,9) data.append(d) time.append(t) toplot = np.vstack((time,data)).T print toplot plot.points = tuple(map(tuple, toplot)) graph.add_plot(plot) box.add_widget(graph) self.add_widget(box)
def build(self): f = FloatLayout() b = Button(pos_hint={'x': 0.5, 'center_y': .5},text='Hello world', font_size=14) s = Scatter() l = Label(text="Hello!",font_size=150) def select_to(*args): try: print args[1][0] except: pass fi = FileChooserIconView() f.add_widget(s) s.add_widget(l) l.add_widget(b) def callback(instance): print('The button <%s> is being pressed' % instance.text) f.add_widget(fi) b.bind(on_press=callback) fi.bind(on_selection=select_to) return f
def mail_pop(self): """Popup with features to mail timesheet """ f=FloatLayout() global popup2 popup2 = Popup(title='Mail Timesheet',content=f, size_hint=(1.0, 0.6), size=(400, 400)) g=GridLayout(cols=1,row_force_default=True, row_default_height=40,pos_hint={'center_x':.5}) global msg msg=Label(text="ENTER AN EMAIL ID") global mail_id mail_id=TextInput(write_tab=False) g.add_widget(msg) g.add_widget(mail_id) btn1=Button(text='MAIL',size_hint=(0.2,0.1), pos=(popup2.width-350,popup2.height-250) ) btn1.bind(on_press=(MyApp.mail_timesheet)) btn2=Button(text='CLOSE',size_hint=(0.2,0.1), pos=(popup2.width-50,popup2.height-250)) f.add_widget(btn1) f.add_widget(btn2) f.add_widget(g) popup2.open() btn2.bind(on_press=popup2.dismiss)
def __init__(self, **kwargs): self.imageToSave = None super(DestinationPopup, self).__init__(**kwargs) self.title = "Save Image" # create popup layout containing a boxLayout text_input = TextInput(text='./DestFileName.jpg') self.text_input = text_input content = FloatLayout() text_and_buttons_layout = BoxLayout(orientation='vertical',size_hint=(.6, .3),pos_hint={'x':.2, 'y':.5}) text_and_buttons_layout.add_widget(text_input) text_and_buttons_layout.add_widget(Widget(size_hint_y=None, size_hint=(1, .2))) # 2 buttons are created for accept or cancel the current value btnlayout = BoxLayout(size_hint_y=None, height=40, spacing=5) okbutton = Button(text='Ok') okbutton.bind(on_release=self._validate) btnlayout.add_widget(okbutton) cancelbutton = Button(text='Cancel') cancelbutton.bind(on_release=self.cancel) btnlayout.add_widget(cancelbutton) text_and_buttons_layout.add_widget(btnlayout) content.add_widget(text_and_buttons_layout) self.content = content
def build(self): root = FloatLayout(size=(600,600), pos=(0,0)) with root.canvas: Color(1,1,0) Rectangle(pos=root.pos, size=root.size) widget1 = Widget(id='magenta', size=(50,50), pos=(0,0)) with widget1.canvas: Color(1,0,1) Rectangle(pos=widget1.pos, size=widget1.size) widget2 = Widget(id='cyan', size=(50,50), pos=(0,100)) with widget2.canvas: Color(0,1,1) Rectangle(pos=widget2.pos, size=widget2.size) widget3 = Widget(id='red', size=(50,50), pos=(100, 200)) with widget3.canvas: Color(1,0,0) Rectangle(pos=widget3.pos, size=widget3.size) widget4 = Widget(id='green', size=(50,50), pos=(200,200)) with widget4.canvas: Color(0,1,0) Rectangle(pos=widget4.pos, size=widget4.size) root.add_widget(widget1) root.add_widget(widget2) root.add_widget(widget3) root.add_widget(widget4) return root
def build(self): # the environment for all 2D shapes scene = FloatLayout() # list of 2D shapes, starting with regular ones shapes = [ RegularShape( name='Shape {}'.format(x), edges=x ) for x in range(3, 13) ] shapes.append(MeshShape(name='DefaultMesh')) shapes.append(MeshShape(name='Cloud', poly=cloud_poly)) shapes.append(MeshShape( name='3QuarterCloud', poly=cloud_poly[:110] )) # move shapes to some random position for shape in shapes: shape.pos = [randint(50, i - 50) for i in Window.size] scene.add_widget(shape) # check for simple collisions between the shapes Clock.schedule_interval( lambda *t: self.collision_circles(shapes, debug=True), 0.1) return scene
def build(self): root = FloatLayout() root.add_widget(Grid()) game = Game() root.add_widget(game) Clock.schedule_interval(game.update, 1./60.) return root
class TextAlignApp(App): def select(self, case): grid = GridLayout(rows=3, cols=3, spacing=10, size_hint=(None, None), pos_hint={'center_x': .5, 'center_y': .5}) for valign in ('bottom', 'middle', 'top'): for halign in ('left', 'center', 'right'): label = BoundedLabel(text='V: %s\nH: %s' % (valign, halign), size_hint=(None, None), halign=halign, valign=valign) if case == 0: label.text_size = (None, None) elif case == 1: label.text_size = (label.width, None) elif case == 2: label.text_size = (None, label.height) else: label.text_size = label.size grid.add_widget(label) if self.grid: self.root.remove_widget(self.grid) grid.bind(minimum_size=grid.setter('size')) self.grid = grid self.root.add_widget(grid) def build(self): self.root = FloatLayout() self.selector = Selector(app=self) self.root.add_widget(self.selector) self.grid = None self.select(0) return self.root
class ReadBox(BoxLayout): """ This class demonstrates various techniques that can be used for binding to events. Although parts could me made more optimal, advanced Python concepts are avoided for the sake of readability and clarity. """ def _keyboard_closed(self): print('My keyboard have been closed!') self._keyboard.unbind(on_key_down=self._on_keyboard_down) self._keyboard = None def _on_keyboard_down(self, keyboard, keycode, text, modifiers): if text == ' ': self.answer(keyboard) def __init__(self, **kwargs): super(ReadBox, self).__init__(**kwargs) self._keyboard =self._keyboard = Window.request_keyboard( self._keyboard_closed, self, 'text') self._keyboard.bind(on_key_down=self._on_keyboard_down) self.orientation = "horizontal" self.readbool = True self.padding = 10 # We start with binding to a normal event. The only argument # passed to the callback is the object which we have bound to. self.label = Button(text="my man!", size_hint=(1, 0.85), background_normal="", background_color=(0, 0, 0, 1)) self.label.bind(on_press=self.answer) self.label.bind(pos=self.updatelabelsize, size=self.updatelabelsize) self.answerbox = Label(text="Answer:", size_hint=(1, 0.11), color=(0, 0, 0, 1)) self.boxone = BoxLayout(size_hint=(0.85, 1), padding=10) self.boxone.orientation = "vertical" self.anotherbox = BoxLayout(size_hint=(0.143, 1), orientation="vertical", padding = 8) with self.canvas: Color(0.4, 0.4, 0.4) self.rectangle = Rectangle(pos = self.pos, size = self.size) self.answerbox.bind(pos=self.updaterectOG, size=self.updaterectOG) with self.answerbox.canvas.before: Color(255, 255, 255) self.answerbox.rect = RoundedRectangle(pos=self.answerbox.pos, size=self.answerbox.size) self.answerbox.bind(pos=self.updaterect, size=self.updaterect) with self.label.canvas.before: Color(0, 0, 0) self.label.rect = RoundedRectangle(pos=self.label.pos, size=self.label.size) self.label.bind(pos=self.updatelabelrect, size=self.updatelabelrect) with self.anotherbox.canvas.before: Color(0, 0, 0) self.anotherbox.rect = RoundedRectangle(pos=self.anotherbox.pos, size=self.anotherbox.size) self.anotherbox.bind(pos=self.updateanotherboxrect, size=self.updateanotherboxrect) self.boxone.add_widget(self.label) self.boxone.add_widget(Label(size_hint = (1,0.04))) self.boxone.add_widget(self.answerbox) self.add_widget(self.boxone) self.status = BoxLayout(size_hint=(1, 0.35), orientation="vertical") self.statustext = Label(size_hint=(1, 0.7), color=(0, 0.75, 1, 1)) self.statustext.bind(pos=self.updatestatussize, size=self.updatestatussize) self.status.add_widget(self.statustext) self.moreoptions = Button(text="More Options", size_hint=(1, 0.3), background_normal="", background_color=(0, 0.35, 1, 1), color=(1, 1, 1, 1)) self.moreoptions.bind(on_press=self.moreoptionsmethod) self.status.add_widget(self.moreoptions) self.anotherbox.add_widget(self.status) self.emptyspace = Label(size_hint=(1, 0.02)) self.anotherbox.add_widget(self.emptyspace) self.correctbuttons = StackLayout(size_hint=(1, 0.4), orientation='bt-lr', spacing=10) self.btn2 = Button(text="Right", size_hint=(1, 0.5), background_normal="", background_color=(0, 1, 0, 1), color=(0, 0, 0, 1)) self.btn = Button(text="Wrong", size_hint=(1, 0.5), background_normal="", background_color=(1, 0, 0, 1), color=(0, 0, 0, 1)) self.tossupinfo = Button(text="Tossup Info", size_hint=(1, 0.13)) self.tossupinfo.bind(on_press = self.tossupinfomethod) self.moreemptyspace = Label(size_hint=(1, 0.02)) self.btn2.bind(on_press=self.correct) self.btn.bind(on_press=self.incorrect) self.correctbuttons.add_widget(self.btn) self.correctbuttons.add_widget(self.btn2) self.anotherbox.add_widget(self.correctbuttons) self.anotherbox.add_widget(self.moreemptyspace) self.anotherbox.add_widget(self.tossupinfo) self.add_widget(Label(size_hint = (0.007,1))) self.add_widget(self.anotherbox) self.questionsright = 0 self.questionswrong = 0 def deletetopic(self, obj): global queue global queue2 global queue3 topic = "" if len(queue) > 0: topic = queue[0][1] del queue[0] elif len(queue2) > 0: topic = queue2[0][1] del queue2[0] elif len(queue3) > 0: topic = queue3[0][1] del queue3[0] else: print("idk man") brain.removetopic(topic) self.clear_widgets() self.orientation = 'horizontal' self.add_widget(self.boxone) self.add_widget(Label(size_hint = (0.007,1))) self.add_widget(self.anotherbox) if len(queue) > 0: self.updatetopics() elif len(queue2) > 0: self.updatetopics() queue = [] elif len(queue3) > 0: self.updatetopics() queue = [] queue2 = [] else: print('idk man') self.read() def tossupinfomethod(self, obj): topic = "" if len(queue) > 0: topic = queue[0][1] elif len(queue2) > 0: topic = queue2[0][1] elif len(queue3) > 0: topic = queue3[0][1] else: print("idk man") self.remove_widget(self.anotherbox) self.remove_widget(self.boxone) self.tossupinfoFloat = FloatLayout(size_hint = (1,1)) self.tossupinfo1 = Label(text = "", size_hint = (1,0.6), pos_hint={'x': 0, 'y': 0.3}) self.backbutton = Button(text = "back", size_hint = (0.3, 0.2), pos_hint={'x': 0.0, 'y': 0.0}) self.backbutton.bind(on_press = self.back) self.deletebutton = Button(text = "delete this topic: \n" + topic, size_hint = (0.3, 0.2), pos_hint={'x': 0.7, 'y': 0.0}) self.deletebutton.bind(on_press = self.deletetopic) infolist = brain.tossupinfo(topic) tossupstring = "topic = " + topic + "\n" for str in infolist: tossupstring += str + "\n" self.tossupinfo1.text = tossupstring self.tossupinfo1.text_size = self.size self.tossupinfo1.font_size = 0.03 * sqrt(self.width * self.height) self.tossupinfo1.halign = 'center' self.tossupinfo1.valign = "center" self.tossupinfoFloat.add_widget(self.tossupinfo1) self.tossupinfoFloat.add_widget(self.backbutton) self.tossupinfoFloat.add_widget(self.deletebutton) self.add_widget(self.tossupinfoFloat) def updatetopics(self): global queue global queue2 global queue3 global numtopics queue = brain.tieronequeue(3) queue2 = brain.tiertwoqueue() queue3 = brain.selectrandomquestion(10) numtopics = brain.numtopics() def answer(self, obj): global queue global queue2 global queue3 if len(queue) > 0: self.answerbox.text = queue[0][0][1] self.label.text = queue[0][0][0] elif len(queue2) > 0: self.answerbox.text = queue2[0][0][1] self.label.text = queue2[0][0][0] elif len(queue3) > 0: self.answerbox.text = queue3[0][0][1] self.label.text = queue3[0][0][0] else: print("idk man") if len(self.answerbox.text.split()) > 20: textlist = self.answerbox.text.split() textlist = textlist[:20] self.answerbox.text = " ".join(textlist) self.answerbox.text_size = self.answerbox.size self.answerbox.font_size = 1.5 * sqrt(self.answerbox.width) * sqrt(sqrt(5 / (len(self.answerbox.text)))) self.answerbox.halign = 'center' self.answerbox.valign = "center" self.readbool = False self.label.text_size = self.label.size self.label.font_size = 0.035 * sqrt(self.label.height * self.label.width) self.label.halign = 'left' self.label.valign = "top" try: self.anotherbox.add_widget(self.correctbuttons) self.anotherbox.add_widget(self.moreemptyspace) self.anotherbox.add_widget(self.tossupinfo) self.status.add_widget(self.moreoptions) except: pass def moreoptionsmethod(self, obj): self.remove_widget(self.anotherbox) self.remove_widget(self.boxone) self.box = FloatLayout(size_hint=(1, 1)) self.btn7 = Button(text="Add or Remove Topics", size_hint=(0.4, 0.4), pos_hint={'x': 0.55, 'y': 0.55}) self.btn6 = Button(text="Change Settings", size_hint=(0.4, 0.4), pos_hint={'x': 0.55, 'y': 0.05}) self.btn5 = Button(text="Statistics", size_hint=(0.4, 0.4), pos_hint={'x': 0.05, 'y': 0.55}) self.btn4 = Button(text="Back", size_hint=(0.4, 0.4), pos_hint={'x': 0.055, 'y': 0.055}) self.btn7.bind(on_press=self.changetopics) self.btn4.bind(on_press=self.back) self.box.add_widget(self.btn7) self.box.add_widget(self.btn6) self.box.add_widget(self.btn5) self.box.add_widget(self.btn4) self.add_widget(self.box) def changetopics(self, obj): self.clear_widgets() self.orientation = 'vertical' space = Label(size_hint=(1, 0.02)) self.inputtext = TextInput(hint_text='Add Topics, one comma separating each topic.', size_hint=(0.95, 0.25), pos_hint={'x': 0.025}) moreemptyspace = Label(size_hint=(1, 0.07)) addtopicsbutton = Button(text="Add Topics!", size_hint=(0.4, 0.25), pos_hint={'x': 0.3}) addtopicsbutton.bind(on_press=self.jsondumptopics) global numtopics self.evenmore = Label(size_hint=(1, 0.31), text=str(numtopics) + " Topics Available", font_size=18) backandclearbuttons = BoxLayout(size_hint=(1, 0.15)) backbutton = Button(text="Back", size_hint=(0.2, 1)) bottombuttonsspace = Label(size_hint=(0.6, 1)) clearbutton = Button(text="Clear topics", size_hint=(0.2, 1), pos_hint={'x': 0.79}) backbutton.bind(on_press=self.back) clearbutton.bind(on_press=self.cleartopics) backandclearbuttons.add_widget(backbutton) backandclearbuttons.add_widget(bottombuttonsspace) backandclearbuttons.add_widget(clearbutton) lst = [space, self.inputtext, moreemptyspace, addtopicsbutton, self.evenmore, backandclearbuttons] for element in lst: self.add_widget(element) def jsondumptopics(self, obj): txt = self.inputtext.text topics = txt.split(',') self.evenmore.halign = 'center' self.evenmore.valign = 'center' self.evenmore.text = "Adding " + str(len(topics)) + " topics. May take a while..." self.evenmore.text_size = self.evenmore.size self.evenmore.font_size = 18 a = threading.Thread(target=self.jsondumphelper, daemon=True) a.start() def jsondumphelper(self): txt = self.inputtext.text topics = txt.split(',') bruh = [] for topic in topics: bruh.append(topic.strip().lower()) x = 0 for topic in bruh: try: brain.jsondump(topic) x = x + 1 except: print('failed!') self.evenmore.text = "Added " + str(x) + "/" + str(len(topics)) + " topics! Dropped " + str( len(topics) - x) + " topics. \n Topics are dropped because zero tossups were found, or quizdb is tripping" self.evenmore.text_size = self.evenmore.size self.updatetopics() sleep(5) self.evenmore.text = str(numtopics) + " Topics Available" def cleartopics(self, obj): brain.cleartopics() if brain.numtopics() == 0: self.evenmore.text = "Successfully cleared all topics. No Going back lmao" self.evenmore.text_size = self.evenmore.size self.evenmore.font_size = 13 global numtopics numtopics = 0 self.start() else: self.evenmore.text = "Failed to clear topics for some dumb reason." self.evenmore.text_size = self.evenmore.size self.evenmore.font_size = 13 def back(self, obj): self.clear_widgets() self.orientation = 'horizontal' self.add_widget(self.boxone) self.add_widget(Label(size_hint = (0.007,1))) self.add_widget(self.anotherbox) self.answer(obj) def correct(self, obj): # updates queue global queue global queue2 global queue3 if len(queue) > 0: brain.correct(queue[0][1]) del queue[0] self.read() elif len(queue2) > 0: brain.correct(queue2[0][1]) del queue2[0] self.read() elif len(queue3) > 0: brain.correct(queue3[0][1]) del queue3[0] self.read() else: print("idk man") self.questionsright = self.questionsright + 1 self.updatestatus() def incorrect(self, obj): global queue global queue2 global queue3 if len(queue) > 0: brain.wrong(queue[0][1]) queue.append(brain.selectquestions(brain.parsetopic(queue[0][1]), 1)[0]) del queue[0] self.read() elif len(queue2) > 0: brain.wrong(queue2[0][1]) del queue2[0] self.read() elif len(queue3) > 0: brain.wrong(queue3[0][1]) del queue3[0] self.read() else: print("idk man") self.questionswrong = self.questionswrong + 1 self.updatestatus() def updatelabel(self): # outputs text to screen global queue global queue2 global queue3 sleep(0.01) # if len(queue) > 0: # text = brain.split_into_sentences(queue[0][0][0]) # elif len(queue2) > 0: # text = brain.split_into_sentences(queue2[0][0][0]) # elif len(queue3) == 1: # self.updatetierthree() # text = brain.split_into_sentences(queue3[0][0][0]) # else: # text = brain.split_into_sentences(queue3[0][0][0]) if len(queue) > 0: text = queue[0][0][0].split() elif len(queue2) > 0: text = queue2[0][0][0].split() elif len(queue3) == 1: self.updatetierthree() text = queue3[0][0][0].split() else: text = queue3[0][0][0].split() x = 0 # self.label.text = queue[0][0][0] self.label.text_size = self.label.size print(self.label.height, self.label.width) self.label.font_size = 0.035 * sqrt(self.label.height * self.label.width) self.label.halign = 'left' self.label.valign = "top" self.label.text = "" while x < len(text): if x > 0: sleep(.115) if not self.readbool: break self.label.text = self.label.text + text[x] + " " x = x + 1 print(x) if self.readbool: try: self.anotherbox.add_widget(self.tossupinfo) self.anotherbox.add_widget(self.moreemptyspace) self.status.add_widget(self.moreoptions) self.anotherbox.add_widget(self.correctbuttons) except: pass def updaterect(self, instance, value): self.answerbox.rect.pos = instance.pos[0] - 7.5, instance.pos[1] - 7.5 self.answerbox.rect.size = instance.size[0] + 15, instance.size[1] + 7.5 def updaterectOG(self, instance, value): self.rectangle.pos = self.pos self.rectangle.size = self.size def updatelabelrect(self, instance, value): position = self.label.center_x, self.label.center_y size = self.label.size[0] + 20, self.label.size[1] + 20 self.label.rect.size = size self.label.rect.pos = position[0] - (self.label.rect.size[0] / 2), position[1] - (self.label.rect.size[1] / 2) def updateanotherboxrect(self, instance, value): self.anotherbox.rect.pos = instance.pos[0], instance.pos[1] self.anotherbox.rect.size = instance.size[0], instance.size[1] def updatelabelsize(self, instance, value): self.label.text_size = self.label.size print(self.label.height, self.label.width) self.label.font_size = 0.035 * sqrt(self.label.height * self.label.width) self.answerbox.text_size = self.answerbox.size self.answerbox.font_size = 0.035 * sqrt(self.label.height * self.label.width) self.answerbox.halign = 'center' self.answerbox.valign = "center" self.label.halign = 'left' self.label.valign = "top" def updatestatussize(self, instance, value): self.updatestatus() def updatestatus(self): global queue if len(queue) > 0: self.statustext.text = "Tier one: " + str(len(queue)) + " tossups left" elif len(queue2) > 0: self.statustext.text = "Tier Two: " + str(len(queue2)) + " tossups left" elif weightedplay: self.statustext.text = "Tier Three: Weighted Play" else: self.statustext.text = "Tier Three: Normal Play" if self.questionswrong == 0 and self.questionsright == 0: self.statustext.text = "Status:\n" + self.statustext.text else: a = "\n" + str(self.questionsright) + "/" + str(self.questionswrong + self.questionsright) + " = " + str( int((100 * self.questionsright) / (self.questionsright + self.questionswrong))) + "%" self.statustext.text = "Status:\n" + self.statustext.text + a print(a) self.statustext.text_size = self.statustext.size self.statustext.font_size = self.statustext.width * 0.17 self.statustext.halign = 'center' self.statustext.valign = 'top' def updatetierthree(self): global queue3 global weightedplay if weightedplay: queue3 = brain.selectweightedquestion(10) else: queue3 = brain.selectrandomquestion(10) def read(self): self.readbool = True self.answerbox.text = "Answer:" self.answerbox.text_size = self.answerbox.size self.answerbox.font_size = 0.035 * sqrt(self.label.height * self.label.width) self.anotherbox.remove_widget(self.correctbuttons) self.anotherbox.remove_widget(self.tossupinfo) self.anotherbox.remove_widget(self.moreemptyspace) self.status.remove_widget(self.moreoptions) thread = threading.Thread(target=self.updatelabel) thread.daemon = True thread.start() def start(self): global numtopics sleep(0.01) self.updatestatus() self.statustext.font_size = self.statustext.width * self.statustext.height * 0.0008 if numtopics > 1: self.read() else: self.clear_widgets() button = Button( text="There are no topics. Download Topics to play.\n If you try to play wuthout downloading at least TWO topics,\n the program will bork.") button.bind(on_press=self.changetopics) self.add_widget(button) def on_event1(self, obj): print("Typical event from", obj)
def build(self): layout = FloatLayout() ti = TextInput(text='Hello world', multiline=False) layout.add_widget(ti) return layout
Rectangle(pos=(150, 150), size=(160, 320)) Color(0.3, 0.3, 0.3, 0.9) Rectangle(pos=(415, 150), size=(250, 320)) Color(0.2, 0.2, 0.2, 1) Rectangle(pos=(505, 150), size=(160, 320)) Account.add_widget(label(50, 400, "Userid")) Account.add_widget(label(65, 320, "Password")) Account.add_widget(label(405, 400, "Userid")) Account.add_widget(label(420, 320, "Password")) Account.add_widget(label(455, 240, "Re-Enter Password")) Account.add_widget(textinput(440, 235, password)) Account.add_widget(textinput(80, 400, userid)) Account.add_widget(textinput(80, 320, password)) Account.add_widget(textinput(440, 400, userid)) Account.add_widget(textinput(440, 320, password)) Account.add_widget(button(180, 250, "Login", Login)) Account.add_widget(button(550, 165, "Register", Register)) return Account root.add_widget(Account()) class App(App): def build(self): return root if __name__ == "__main__": App().run()
class ViewSegment(Widget): def __init__(self, movie, labels, **kwargs): super().__init__(**kwargs) self.movie = movie self.labels = labels self.view = 'seg_view' # Buttons for choosing between whether to view labelled segments or export labelled images self.layout_choice = GridLayout(cols=3, size_hint=(.45, .05), pos_hint={ 'x': .52, 'y': .925 }) self.view_button = ToggleButton(text='View Labels', group='view') self.export_button = ToggleButton(text='Export Labels', group='view') self.ring_button = ToggleButton(text='Ring Region') self.view_button.bind(on_press=self.view_segment) self.export_button.bind(on_press=self.export_data) self.ring_button.bind(on_press=self.ring_toggle) self.layout_choice.add_widget(self.view_button) self.layout_choice.add_widget(self.export_button) self.layout_choice.add_widget(self.ring_button) self.label_layout = FloatLayout(size=(Window.width, Window.height)) self.save_layout = FloatLayout(size=(Window.width, Window.height)) im_temp = self.labels[0, :, :] # Label Viewing Widgets self.im_disp = ImDisplay(size_hint=(.8, .73), pos_hint={ 'x': .1, 'y': .14 }) self.im_disp.create_im(im_temp, 'Random') self.frame_slider = guitools.FrameSlider(self.movie.frames, self.change_frame, size_hint=(.37, .06), pos_hint={ 'x': .13, 'y': .91 }) self.label_layout.add_widget(self.frame_slider) self.label_layout.add_widget(self.im_disp) self.label_layout.add_widget(self.layout_choice) # File Viewing Widgets self.file_choose = FileChooserListView(size_hint=(.9, .6), pos_hint={ 'x': .05, 'y': .14 }) self.save_layout.add_widget(self.file_choose) # Widgets for creating directory self.folder_input = TextInput(text='Directory Name', multiline=False, size_hint=(.65, .05), pos_hint={ 'x': .31, 'y': .85 }) self.folder_input.bind(on_text_validate=self.make_folder) self.folder_label = Label( text='[b][color=000000]Create directory name: [/b][/color]', markup=True, size_hint=(.25, .05), pos_hint={ 'x': .05, 'y': .85 }) self.save_layout.add_widget(self.folder_input) self.save_layout.add_widget(self.folder_label) # Widgets for exporting labels to tif files self.text_file_input = TextInput(text='File Name', multiline=False, size_hint=(.65, .05), pos_hint={ 'x': .31, 'y': .79 }) self.text_file_input.bind(on_text_validate=self.export_files) self.file_label = Label( text='[b][color=000000]Choose file name: [/b][/color]', markup=True, size_hint=(.25, .05), pos_hint={ 'x': .05, 'y': .79 }) self.save_layout.add_widget(self.text_file_input) self.save_layout.add_widget(self.file_label) with self.canvas: self.add_widget(self.label_layout) def make_folder(self, instance): os.makedirs(os.path.join(self.file_choose.path, instance.text)) self.folder_input.text = 'Directory made, re-enter present dir to view it' def export_files(self, instance): temp_path = self.file_choose.path digits = len(str(self.movie.frames)) for i in range(self.movie.frames): num = str(i) num = num.zfill(digits) fname = os.path.join(temp_path, instance.text + '_' + num + '.tif') tifffile.imsave(fname, self.labels[i, :, :]) self.text_file_input.text = 'Images written, re-enter present dir to view them' def export_data(self, instance): if self.view == 'seg_view': self.label_layout.remove_widget(self.layout_choice) self.save_layout.add_widget(self.layout_choice) self.remove_widget(self.label_layout) self.add_widget(self.save_layout) self.view = 'file_view' def view_segment(self, instance): if self.view == 'file_view': self.save_layout.remove_widget(self.layout_choice) self.label_layout.add_widget(self.layout_choice) self.remove_widget(self.save_layout) self.add_widget(self.label_layout) self.view = 'seg_view' def change_frame(self, val): im_temp = self.labels[int(val), :, :] self.im_disp.update_im(im_temp) def update_size(self, window, width, height): self.label_layout.width = width self.label_layout.height = height self.save_layout.width = width self.save_layout.height = height def ring_toggle(self, instance): # Toggle button for whether to extract intensity of ring region in feature extraction if instance.state == 'down': self.parent.ring_flag = True else: self.parent.ring_flag = False
class HongBao(PageLayout): def __init__(self, **kwargs): super(HongBao, self).__init__(**kwargs) self.filename = kivy.resources.resource_find( '/mnt/sdcard/com.hipipal.qpyplus/projects/hongbao/hb.jpg') self.init_ui() def add_arrt(self, gridLayout, attr_name, value): gridLayout.add_widget(Label(text=attr_name)) attr_input = TextInput(text=value, multiline=False) gridLayout.add_widget(attr_input) return attr_input def init_ui(self): self.gridLayout = GridLayout(cols=1, spacing=[0, 4]) self.gridLayout1 = GridLayout(cols=2, spacing=[0, 9]) self.color_min_input = self.add_arrt(self.gridLayout1, 'color_min', '20') self.color_max_input = self.add_arrt(self.gridLayout1, 'color_max', '120') self.fangcha_input = self.add_arrt(self.gridLayout1, 'fangcha', '15000') self.up_down_input = self.add_arrt(self.gridLayout1, 'up_down', '8') #self.left_right_input=self.add_arrt(self.gridLayout1,'left_right','0') self.jisuan_btn_a = Button(text='chick_a', ) self.gridLayout1.add_widget(self.jisuan_btn_a) self.jisuan_btn_b = Button(text='chick_b', ) self.gridLayout1.add_widget(self.jisuan_btn_b) self.gridLayout.add_widget(self.gridLayout1) self.jisuan_btn_a.bind(on_press=self.jisuan_a) self.jisuan_btn_b.bind(on_press=self.jisuan_b) self.image_hb = Image(source=self.filename) self.gridLayout.add_widget(self.image_hb) self.floatlayout = FloatLayout() self.fc = FileChooserListView() self.fc.path = '/mnt/sdcard/DCIM/' self.floatlayout.add_widget(self.fc) self.get_file_btn = Button(text='chick_a', size_hint=(0.2, .1), pos=(20, 20)) self.floatlayout.add_widget(self.get_file_btn) self.get_file_btn.bind(on_press=self.get_file) self.add_widget(self.floatlayout) self.add_widget(self.gridLayout) def get_file(self, instance): filename = os.path.join(os.path.dirname(self.filename), os.path.basename(self.fc.selection[0])) print self.fc.selection[0], ' -' * 20 im_tmp = PIL.Image.open(self.fc.selection[0]) w, h = im_tmp.size minx = int(w * 230.0 / 720) maxx = int(w * 487 / 720) miny = int(h * (1280 - 520) / 1280) maxy = int(h * (1280 - 264) / 1280) if h > 1000: im_tmp = im_tmp.crop([minx, miny, maxx, maxy]) im_tmp.save(filename, 'jpeg') self.filename = filename self.floatlayout.opacity = 0 self.updata_image() self.page = 1 print 'filename :', self.filename def remove_line(self, mode='a'): im2 = PIL.Image.open(self.filename) im3 = im2.copy() w2, h2 = im2.size im2_pix = im2.load() im3_pix = im3.load() color_min = int(self.color_min_input.text) color_max = int(self.color_max_input.text) fangcha_max = int(self.fangcha_input.text) up_down = int(self.up_down_input.text) black_in_line = False current_y = 0 for y in range(up_down + 1, h2): x_color_r = 0 x_color_g = 0 x_color_b = 0 for x in range(0, w2): r, g, b = im2_pix[x, y] x_color_r += r x_color_g += g x_color_b += b pingjun_r = x_color_r / w2 pingjun_g = x_color_g / w2 pingjun_b = x_color_b / w2 fangcha_r = 0 fangcha_g = 0 fangcha_b = 0 for x in range(0, w2): r, g, b = im2_pix[x, y] fangcha_r += abs(pingjun_r - r) fangcha_g += abs(pingjun_g - g) fangcha_b += abs(pingjun_b - b) if ( fangcha_r + fangcha_g + fangcha_b ) < fangcha_max and color_min < pingjun_r < color_max and color_min < pingjun_g < color_max and color_min < pingjun_b < color_max: #print y, '****' * 30, ' ', fangcha_r + fangcha_g + fangcha_b, pingjun_r, pingjun_g, pingjun_r if black_in_line == False: current_y = y black_in_line = True for x2 in range(0, w2): if mode == 'a': im3_pix[x2, y] = im2_pix[x2, current_y - 2] else: im3_pix[x2, y] = im2_pix[x2, y - up_down] else: if black_in_line == True: black_in_line = False if mode == 'a': for x2 in range(0, w2): im3_pix[x2, y] = im2_pix[x2, current_y - up_down] #print y, '----' * 30, ' ', fangcha_r + fangcha_g + fangcha_b, pingjun_r, pingjun_g, pingjun_r return im3 def jisuan_a(self, instance): im3 = self.remove_line().resize([600, 600]) filenamea = self.filename.rsplit('.', 1)[0] + 'a.jpg' im3.save(filenamea, 'jpeg') self.updata_image(filenamea) def jisuan_b(self, instance): im3 = self.remove_line('b').resize([600, 600]) filenamea = self.filename.rsplit('.', 1)[0] + 'a.jpg' im3.save(filenamea, 'jpeg') self.updata_image(filenamea) def updata_image(self, filenamea=None): if filenamea is None: filenamea = self.filename image_hb2 = Image(source=filenamea) self.gridLayout.remove_widget(self.image_hb) self.image_hb = image_hb2 self.gridLayout.add_widget(self.image_hb, 0) self.image_hb.reload()
class unipage(object): def __init__(self, kivy, screen_size): self.kivy = kivy self.screen_size = screen_size self.unibuttons = [] self.unitexts = [] self.unilabels = [] self.unimages = [] self.uniframes = [] self.xratio = self.screen_size[0] / 800.0 self.yratio = self.screen_size[1] / 600.0 def setscreen(self): if self.kivy: from kivy.uix.floatlayout import FloatLayout from kivy.core.window import Window self.root = FloatLayout() if (self.xratio == 0) or (self.yratio == 0): from kivy.utils import platform as core_platform if core_platform == 'android': self.screen_size = Window.size else: self.screen_size = (800, 600) self.xratio = self.screen_size[0] / 800.0 self.yratio = self.screen_size[1] / 600.0 Window.size = self.screen_size else: import ui if (self.xratio == 0) or (self.yratio == 0): ss1 = ui.get_screen_size()[0] ss3 = ui.get_screen_size()[1] notoptimal = True while notoptimal: if ss1 % 8 == 0: notoptimal = False else: ss1 -= 1 ss1 = ss1 - 124 ss2 = (ss1 / 4) * 3 if ss2 > ss3: print('yes') ss2 = ss3 - ss2 - ((ss3 - ss2) % 3) ss1 = (ss2 / 3) * 4 self.screen_size = (ss1, ss2) self.xratio = self.screen_size[0] / 800 self.yratio = self.screen_size[1] / 600 self.root = ui.View(frame=(0,0,self.screen_size[0], \ self.screen_size[1])) def unibutton(self, params): self.unibuttons.append([]) if len(params) == 6: function = params[5] else: function = nofunction if self.kivy: from kivy.uix.button import Button self.unibuttons[len(self.unibuttons) - 1] = Button( text = params[4], size_hint_y = None, size_hint_x = None, height = params[3] * self.yratio, width = params[2] * self.xratio, pos = (params[0] * self.xratio, params[1] * self.yratio), on_press = function ) self.root.add_widget(self.unibuttons[len(self.unibuttons) - 1]) else: import ui self.unibuttons[len(self.unibuttons) - 1] = ui.Button(frame= \ (params[0] * self.xratio, (600 - params[1] - params[3]) * self.yratio, \ params[2] * self.xratio, params[3] * self.yratio), title = params[4]) self.unibuttons[len(self.unibuttons) - 1].background_color \ = (0.4,0.4,0.4) self.unibuttons[len(self.unibuttons) - 1].action = function self.unibuttons[len(self.unibuttons) - 1].height = params[3] * self.xratio self.unibuttons[len(self.unibuttons) - 1].width = params[2] * self.yratio self.unibuttons[len(self.unibuttons) - 1].tint_color = 'white' self.root.add_subview(self.unibuttons[len(self.unibuttons) - 1]) def unitext(self, params): self.unitexts.append([]) if self.kivy: from kivy.uix.textinput import TextInput self.unitexts[len(self.unitexts) - 1] = TextInput ( id = 'text' + str(len(self.unitexts) - 1), size_hint_y = None, size_hint_x = None, height = params[3] * self.yratio, width = params[2] * self.xratio, text = params[4], multiline = True, pos = (params[0] * self.xratio, params[1] * self.yratio)) self.root.add_widget(self.unitexts[len(self.unitexts) - 1]) else: import ui self.unitexts[len(self.unitexts) - 1] = ui.TextField(frame= (params[0] * self.xratio, (600 - params[1] - params[3]) * \ self.yratio, params[2] * self.xratio, params[3] * self.yratio)) self.unitexts[len(self.unitexts) - 1].bordered = False self.unitexts[len(self.unitexts) - 1].background_color = 'white' self.unitexts[len(self.unitexts) - 1].font = ('<system>', 23 * self.xratio) self.unitexts[len(self.unitexts) - 1].text = params[4] self.root.add_subview(self.unitexts[len(self.unitexts) - 1]) def unilabel(self, params): self.unilabels.append([]) if self.kivy: from kivy.uix.label import Label self.unilabels[len(self.unilabels) - 1] = Label(pos = \ (params[0] * self.xratio, params[1] * self.yratio), \ size_hint=(1.0,1.0), halign="left", \ valign="bottom", text = params[4]) self.unilabels[len(self.unilabels) - 1].bind(size= \ self.unilabels[len(self.unilabels) - 1].setter('text_size')) self.root.add_widget(self.unilabels[len(self.unilabels) - 1]) else: import ui self.unilabels[len(self.unilabels) - 1] = ui.Label(frame= \ (params[0] * self.xratio, (600 - params[1] - params[3]) * self.yratio, \ params[2] * self.xratio, params[3] * self.yratio)) self.unilabels[len(self.unilabels) - 1].text = params[4] self.unilabels[len(self.unilabels) - 1].text_color = 'white' self.unilabels[len(self.unilabels) - 1].alignment = ALIGN_LEFT = True self.unilabels[len(self.unilabels) - 1].font = ('<system>', 18 * self.xratio) self.root.add_subview(self.unilabels[len(self.unilabels) - 1]) def unimage(self, params): self.unimages.append([]) if self.kivy: from kivy.uix.image import Image self.unimages[len(self.unimages) - 1] = Image( source= params[4], allow_stretch = True, size_hint = (None, None), size=(params[2] * self.xratio, params[3] * self.yratio), pos=(params[0] * self.xratio, params[1] * self.yratio)) self.root.add_widget(self.unimages[len(self.unitexts) - 1]) else: import ui self.unimages[len(self.unimages) - 1] = (ui.ImageView (name = 'Image', frame = (params[0] * self.xratio, \ (600 - params[1] - params[3]) * self.yratio, \ params[2] * self.xratio, params[3] * self.yratio))) self.root.add_subview (self.unimages[len(self.unimages) - 1]) self.unimages[len(self.unitexts) - 1].image = ui.Image.named(params[4]) def uniframe(self, params): if self.kivy: from kivy.graphics import Color from kivy.graphics import Rectangle self.root.canvas.add(Color (params[4][0],params[4][1], params[4][2])) self.root.canvas.add(Rectangle(pos = (params[0] * self.xratio, \ params[1] * self.yratio), size = (params[2] * self.xratio, \ params[3] * self.yratio))) else: import ui self.uniframes.append([]) self.uniframes[len(self.uniframes) - 1] = \ ui.View(frame=(params[0] * self.xratio, \ (600 - params[1] - params[3]) * self.yratio, \ params[2] * self.xratio, params[3] * self.yratio)) self.uniframes[len(self.uniframes) - 1].background_color = \ (params[4][0],params[4][1], params[4][2],1.0) self.root.add_subview(self.uniframes[len(self.uniframes) - 1]) def showpage(self): if self.kivy: from kivy.base import runTouchApp runTouchApp(self.root) else: self.root.present('sheet')
def build(self): interface = FloatLayout() self.data = Data() if self.config.get('Maslow Settings', 'colorScheme') == 'Light': self.data.iconPath = './Images/Icons/normal/' self.data.fontColor = '[color=7a7a7a]' self.data.drawingColor = [.47, .47, .47] Window.clearcolor = (1, 1, 1, 1) self.data.posIndicatorColor = [0, 0, 0] self.data.targetInicatorColor = [1, 0, 0] elif self.config.get('Maslow Settings', 'colorScheme') == 'Dark': self.data.iconPath = './Images/Icons/highvis/' self.data.fontColor = '[color=000000]' self.data.drawingColor = [1, 1, 1] Window.clearcolor = (0, 0, 0, 1) self.data.posIndicatorColor = [1, 1, 1] self.data.targetInicatorColor = [1, 0, 0] elif self.config.get('Maslow Settings', 'colorScheme') == 'DarkGreyBlue': self.data.iconPath = './Images/Icons/darkgreyblue/' self.data.fontColor = '[color=000000]' self.data.drawingColor = [1, 1, 1] Window.clearcolor = (0.06, 0.10, 0.2, 1) self.data.posIndicatorColor = [0.51, 0.93, 0.97] self.data.targetInicatorColor = [1, 0, 0] Window.maximize() self.frontpage = FrontPage(self.data, name='FrontPage') interface.add_widget(self.frontpage) self.nonVisibleWidgets = NonVisibleWidgets() ''' Load User Settings ''' # force create an ini no matter what. self.config.write() if self.config.get('Advanced Settings', 'encoderSteps') == '8148.0': self.data.message_queue.put( "Message: This update will adjust the the number of encoder pulses per rotation from 8,148 to 8,113 in your settings which improves the positional accuracy.\n\nPerforming a calibration will help you get the most out of this update." ) self.config.set('Advanced Settings', 'encoderSteps', '8113.73') #up the maximum feedrate if self.config.get('Advanced Settings', 'maxFeedrate') == '700': self.data.message_queue.put( "Message: This update will increase the maximum feedrate of your machine. You can adjust this value under the Advanced settings." ) self.config.set('Advanced Settings', 'maxFeedrate', '800') self.config.write() self.data.comport = self.config.get('Maslow Settings', 'COMport') self.data.gcodeFile = self.config.get('Maslow Settings', 'openFile') offsetX = float(self.config.get('Advanced Settings', 'homeX')) offsetY = float(self.config.get('Advanced Settings', 'homeY')) self.data.gcodeShift = [offsetX, offsetY] self.data.config = self.config self.config.add_callback(self.configSettingChange) # Background image setup self.data.backgroundFile = self.config.get('Background Settings', 'backgroundFile') self.data.backgroundManualReg = json.loads( self.config.get('Background Settings', 'manualReg')) if self.data.backgroundFile != "": BackgroundMenu(self.data).processBackground() ''' Initializations ''' self.frontpage.setUpData(self.data) self.nonVisibleWidgets.setUpData(self.data) self.frontpage.gcodecanvas.initialize() ''' Scheduling ''' Clock.schedule_interval(self.runPeriodically, .01) ''' Push settings to machine ''' self.data.bind(connectionStatus=self.requestMachineSettings) self.data.pushSettings = self.requestMachineSettings return interface
class MenuScreen(App): def build(self): self.layout = FloatLayout() with self.layout.canvas.before: Color(0.784, 0.878, 0.984, 1) self.layout.rect = Rectangle(size=(800, 540), post=self.layout.pos) self.image0 = Image(source='logo.png', pos=(-230, 270)) self.label1 = Label(text="[b]Bin NO:[/b]" + "\n" + "1.3A", markup=True, color=(0, 0, 0, 1), font_size=32, pos=(-240, 0)) self.label2 = Label(text="[b]Building 1 Level 3[/b]", markup=True, color=(0, 0, 0, 1), font_size=36, pos=(230, 200)) self.label3 = Label(text='0 %', color=(0, 1, 0, 1), font_size=40, pos=(20, -220)) self.image1 = Image(source='happydust bin.png') self.image2 = Image(source='saddustbin.png') self.image3 = Image(source='filleddustbin1.png') self.image4 = Image(source='shocking-bubble1.png', pos=(250, -100)) self.image5 = Image(source='happy-bubble1.png', pos=(240, 0)) self.image6 = Image(source='sad-bubble1.png', pos=(240, 0)) self.quitbutton = Button(text='Quit', size_hint=(0.1, 0.1), font_size=24, pos=(100, 120), on_press=self.quit_app) self.state = 0 self.layout.add_widget(self.label1) self.layout.add_widget(self.label2) self.layout.add_widget(self.label3) self.layout.add_widget(self.image1) self.layout.add_widget(self.image5) self.layout.add_widget(self.image0) self.layout.add_widget(self.quitbutton) Clock.schedule_interval(self.update, 2) return self.layout def update(self, instance): binstatus = firebase.get('/B1L3A') self.label3.text = str(round(binstatus, 1)) + " %" if float(binstatus) < 50: self.layout.remove_widget(self.image1) self.layout.remove_widget(self.image2) self.layout.remove_widget(self.image3) self.layout.remove_widget(self.image4) self.layout.remove_widget(self.image5) self.layout.remove_widget(self.image6) self.layout.add_widget(self.image1) self.layout.add_widget(self.image5) elif 50 <= float(binstatus) < 80: self.layout.remove_widget(self.image1) self.layout.remove_widget(self.image2) self.layout.remove_widget(self.image3) self.layout.remove_widget(self.image4) self.layout.remove_widget(self.image5) self.layout.remove_widget(self.image6) self.label3.color = (1, 0.549, 0, 1) self.layout.add_widget(self.image2) self.layout.add_widget(self.image6) elif float(binstatus) >= 80: self.layout.remove_widget(self.image1) self.layout.remove_widget(self.image2) self.layout.remove_widget(self.image3) self.layout.remove_widget(self.image4) self.layout.remove_widget(self.image5) self.layout.remove_widget(self.image6) self.label3.color = (1, 0, 0, 1) self.layout.add_widget(self.image3) self.layout.add_widget(self.image4) def quit_app(self, value): App.get_running_app().stop()
class DeleteUser(Popup): ## # Class Constructor: __init__ # --------------------------- # This method is called during creation of the DeleteUser class. # This function creates the layout for the popup as well as initializes all the # popup attributes. # # @params # (DeleteUser) self This instance of DeleteUser # (Various) **kwargs Arguments for constuction of internal Popup object ## def __init__(self, **kwargs): self.layout = FloatLayout(size=(Window.width, 200)) super(DeleteUser, self).__init__(title='Delete User', content=self.layout, size_hint=(None, None), size=(400, 200), background=BKGD_DCHRC, pos_hint={ "center_x": .5, 'top': .7 }, auto_dismiss=False, **kwargs) ## # Class Method: draw_layout # ------------------------- # This method creates the entire layout for the popup including creating the information # labels as well as the delete and cancel buttons. This function also checks to see if a user # is selected and responds accordingly. # # @params # (DeleteUser) self This instance of DeleteUser ## def draw_layout(self): self.button_x = .5 self.message = "No user currently selected" if manager.CURRENT_USER != None: self.message = "Are you sure you want to delete user " \ + manager.CURRENT_USER + "?" self.button_x = .35 self.layout.add_widget( Label(text=self.message, pos_hint={ "center_x": .5, 'top': 1.25 })) self.layout.add_widget( HoverButton(text="Cancel", button_down=BTN_DCHRC[1], button_up=BTN_DCHRC[0], font_size=14, size_hint=(None, None), size=(100, 40), pos_hint={ "center_x": self.button_x, 'top': .35 }, on_press=self.dismiss)) if manager.CURRENT_USER: self.layout.add_widget( HoverButton(text="Delete", button_down=BTN_DCHRC[1], button_up=BTN_DCHRC[0], font_size=14, size_hint=(None, None), size=(100, 40), pos_hint={ "center_x": .65, 'top': .35 }, on_press=self.delete_user)) ## # Class Method: open_popup # ------------------------ # This method is called to clear the widgets of the current popup layout and redraw the # layout according to the current situation. # # @params # (DeleteUser) self This instance of DeleteUser ## def open_popup(self): self.layout.clear_widgets() self.draw_layout() self.open() ## # Class Method: delete_user # ------------------------- # This method closes the popup panel while also deleting the currently selected user from the # database and clearing the screen of any trace of the deleted user. # # @params # (DeleteUser) self This instance of DeleteUser # (HoverButton) instance This is the button pressed to cause delete_user to be called ## def delete_user(self, instance): self.dismiss() database.delete_user(manager.CURRENT_USER) manager.CURRENT_USER = None manager.menu.clear_info_panel() manager.menu.show_users()
class TwistedClientApp(App): ''' ''' connection = None user_os = None user = None labelmsg = "" chat_online_details = "" haha = [] y = 0 notify_events = [] available_users = [] def build(self): root = self.initialise_setup() self.start_thread() return root def initialise_setup(self): '''variable initialisation''' self.layout = FloatLayout(size=(800, 800)) self.Mainlabel = Label(text="SharePy", color=(0.6, 0.7, 0.2, 1), font_size="65sp", pos=(280, 450), size_hint=(.3, .3)) self.layout.add_widget(self.Mainlabel) self.cont_but = Button(text="Cont...", background_color=(0.2, 0.3, 0.88, 1), pos=(700, 30), size_hint=(.12, .1)) self.layout.add_widget(self.cont_but) self.INFO = Label(size_hint=(.3, .3), pos=(230, 300), color=(0.6, 0.3, 0.1, 1), font_size="21dp") self.INFO2 = Label(size_hint=(.3, .3), pos=(230, 150), color=(0.3, 0.3, 0.7, 1), font_size="21dp") self.INFO.text = "SharePy is a project based on File Sharing.\nIts a project developed in Kivy using Python.\n\nBasic Features include:\n " self.INFO2.text = self.INFO2.text + "\n-> Zero Configuration\n-> File Transfering\n-> File Syncing\n-> File Searching\n-> Notification Broadcasting on File Events\n-> ChatBot for communication between Clients\n-> File Listing" self.INFO3 = Label( text="Members:\nVarun Malhotra\nMayank Bhola\nHarsh Bhatia", color=(0.7, 0.1, 0.1, 1), pos=(150, 40), size_hint=(0.2, 0.2), font_size="21dp") self.layout.add_widget(self.INFO) self.layout.add_widget(self.INFO2) self.layout.add_widget(self.INFO3) self.anim_info2 = Animation(x=80,y=150, opacity=0.4, d=0.4,t ='in_quad') +\ Animation(x=230,y=150, opacity=1, d=0.5) self.anim_info2.start(self.INFO2) self.anim_info3 = Animation(x=80,y=20, opacity=0.4, d=0.6,t ='in_quad') +\ Animation(x=150,y=20, opacity=1, d=0.8) self.anim_info3.start(self.INFO3) self.cont_but.bind(on_press=self.setup_gui) return self.layout def setup_gui(self, object): ''' The layout for the app goes here ''' global user user = getpass.getuser() global user_os user_os = platform.system() self.Mainlabel = Label(text="SharePy", color=(0.6, 0.7, 0.2, 1), font_size="65sp", pos=(280, 450), size_hint=(.3, .3)) self.label = TextInput(hint_text='Connecting...\n', size_hint=(.68, .5), pos=(20, 120), readonly=True, focus=True) self.dir_loc = TextInput(hint_text='Your root directory is: ', size_hint=(.68, .07), pos=(20, 430), readonly=True, background_color=(192, 192, 192, 0.3), foreground_color=(255, 255, 255, 1)) self.button = Button(text="Start Client", size_hint=(.2, .2), background_color=(0.7, 0.2, 0.3, 1), pos=(50, 100)) self.ctexthost = TextInput(text="localhost", hint_text="Enter host", size_hint=(.2, .1), pos=(-150, 350), multiline=False, background_color=(0.4, 0.5, 1, 0.9), foreground_color=(255, 255, 255, 1)) self.ctextport = TextInput(text="8000", hint_text="Enter port", size_hint=(.2, .1), pos=(-150, 250), multiline=False, background_color=(0.4, 0.5, 1, .9), foreground_color=(255, 255, 255, 1)) self.button1 = ToggleButton(text="Search a File", size_hint=(.2, .2), pos=(10, 500), group="file_share", font_size='18sp') self.button2 = ToggleButton(text="Get a File", size_hint=(.2, .2), pos=(210, 500), group="file_share", font_size="18sp") self.button3 = Button(text="Search a File", size_hint=(.17, .15), pos=(20, 520), background_color=(0.5, 0.7, 1, 1), font_size="18sp") self.button4 = Button(text="List Directory", size_hint=(.17, .15), pos=(150, 520), background_color=(0.4, 1, 0.3, 1), font_size="18sp") self.button4.bind(on_press=self.opentextinput) self.closeclient = Button(text="Close Client", pos=(425, 520), size_hint=(0.17, 0.15), background_color=(0.8, 0.3, 0.1, 1), font_size="18sp") self.closeclient.bind(on_press=self.CloseClient) self.notify_ground = TextInput(text="I notify events", pos=(600, 0), background_color=(0.7, 0.5, 0.9, 1), size_hint=(.3, 1), readonly=True, scroll_y=10) self.chat_ground = TextInput(text="CHAT BOX", pos=(600, 0), background_color=(0.7, 0.5, 0.9, 1), size_hint=(.3, 1), readonly=True, scroll_y=10) self.chatbox = Button(text="Chat Box", pos=(563, 520), size_hint=(0.17, 0.15), background_color=(0.3, 0.3, 0.7, 1), font_size="18sp") self.chatbox.bind(on_press=self.chathistory) self.reponame = TextInput(text="Hellosnp", hint_text="Enter RepoName", pos=(200, 300), size_hint=(0.5, 0.1), multiline=False, focus=True) self.button.bind(on_press=self.connect_to_server) self.label_info = TextInput(text="Hi i'm a alebe;", pos=(0, 610), background_color=(0.7, 0, 0, 1), size_hint=(1, .2), readonly=True) self.notify_but = Button(text="Recent events", size_hint=(.17, .15), pos=(290, 520), background_color=(0.8, 0.2, 0.3, 1), font_size="18sp") self.notify_but.bind(on_press=self.recent_act) self.cancel_event = Button(text="Close", size_hint=(0.27, 0.06), pos=(600, 0), background_color=(255, 0, 0, 0.6)) self.cancel_chat = Button(text="Close", size_hint=(0.27, 0.06), pos=(600, 0), background_color=(255, 0, 0, 0.6)) self.repolabel = Label( text= "Create your own Repository/New Folder by providing the name below", pos=(210, 320), size_hint=(0.5, 0.5), color=(0.6, 0.3, 0.1, 1), font_size="20dp") self.update = Button(text="Update", background_color=(0.3, 0.3, 0.9, 1), size_hint=(.25, .1), pos=(600, 550)) self.fetching_server() return self.layout def fetching_server(self): ''' Start server on desired port''' self.layout.clear_widgets() self.layout.add_widget(self.button) self.layout.add_widget(self.Mainlabel) self.layout.add_widget(self.ctexthost) self.layout.add_widget(self.ctextport) self.anim_host = Animation(x=280,y=550, opacity=0.4, d=0.2,t ='in_quad') +\ Animation(x=280,y=450, opacity=1, d=0.2) self.anim_host.start(self.Mainlabel) self.anim_host = Animation(x=0,y=350, opacity=0.4, d=0.5,t ='in_quad') +\ Animation(x=50,y=350, opacity=1, d=0.6) self.anim_host.start(self.ctexthost) self.anim_port = Animation(x=0,y=250, opacity=0.4, d=0.5,t ='in_quad') +\ Animation(x=50,y=250, opacity=1, d=0.6) self.anim_port.start(self.ctextport) self.anim_startbut = Animation(x=0,y=100, opacity=0.4, d=0.5,t ='in_quad') +\ Animation(x=50,y=100, opacity=1, d=0.6) self.anim_startbut.start(self.button) def repo_creation(self): ''' creation of repo to work in''' self.layout.clear_widgets() self.layout.add_widget(self.repolabel) self.layout.add_widget(self.reponame) self.reponame.bind(on_text_validate=self.building_utilities) return self.layout def building_utilities(self, *args): ''' providing the services to the client''' root_dirname = self.reponame.text if not os.path.exists(root_dirname): os.makedirs(root_dirname) os.chdir(root_dirname) self.dir_loc.text = os.getcwd() self.layout.clear_widgets() self.layout.add_widget(self.button3) self.layout.add_widget(self.button4) self.layout.add_widget(self.closeclient) self.layout.add_widget(self.notify_but) self.layout.add_widget(self.chatbox) self.layout.add_widget(self.label) self.layout.add_widget(self.dir_loc) self.layout.add_widget(self.label_info) self.anim_host = Animation(x=20,y=520, opacity=0.4, d=0.5,t ='in_quad') +\ Animation(x=20,y=480, opacity=1, d=0.6) self.anim_host.start(self.button3) self.anim_port = Animation(x=155,y=520, opacity=0.1, d=0.5,t ='in_quad') +\ Animation(x=155,y=480, opacity=1, d=0.6) self.anim_port.start(self.button4) self.anim_button = Animation(x=290,y=520, opacity=0.1, d=0.5,t ='in_quad') +\ Animation(x=290,y=480, opacity=1, d=0.6) self.anim_button.start(self.notify_but) self.anim_close = Animation(x=425,y=520, opacity=0.1, d=0.5,t ='in_quad') +\ Animation(x=425,y=480, opacity=1, d=0.6) self.anim_close.start(self.closeclient) self.anim_chat = Animation(x=563,y=520, opacity=0.1, d=0.5,t ='in_quad') +\ Animation(x=563,y=480, opacity=1, d=0.6) self.anim_chat.start(self.chatbox) return self.layout def connect_to_server(self, *args): ''' connection establishing (handshaking)''' if ((self.ctextport.text).isdigit()): self.conn = reactor.connectTCP(str(self.ctexthost.text), int(self.ctextport.text), EchoFactory(self)) self.label.text = "Connecting...\n" else: self.label.text = "Not Connected...\nPlease enter valid port" def on_connection(self, connection): ''' on successful establishment with server''' self.print_message("Connected Succesfully!") self.connection = connection self.repo_creation() def send_message(self, connection): ''' client demands resources ''' msg = self.textbox.text if msg and self.connection: msg = "2$#" + user + "@" + user_os + ": " + msg self.connection.write(str(msg)) self.textbox.text = "" def print_message(self, msg): ''' the processed output client gets on demanding resources ''' copr = msg.split("$#")[0] if copr.isdigit(): if (int(copr) == 2): self.label.text = msg.split("$#")[1] + "\n" #print msg.split("$#")[1] elif (int(copr) == 8): self.sendarea.text = self.sendarea.text + msg.split( "8$#")[1] + "\n" print "recveived msg - " + ( msg.split("8$#")[1]).split("##")[1] + " from ip add" + ( msg.split("8$#")[1]).split("##")[0] elif (int(copr) == 4): msg = msg.split("$#")[1] g = msg.split(": <")[1] o = g.split(": ")[0] if o == "FileMovedEvent": d = g.split(": src_path=")[1] e = d.split(", ")[0] f = d.split(", ")[1] f1 = f.split(">")[0] msg = "A file at\n" + e + "\nis moved to\n" + f1 else: of = g.split(": ")[1] print o f = g.split("src_path=")[1] f1 = f.split(">")[0] msg = "A file at\n" + f1 + "\n is " + o self.layout.remove_widget(self.label_info) self.layout.add_widget(self.label_info) self.label_info.text = str(msg) self.anim = Animation(x=0,y=550, opacity=0, d=1, t='in_back') +\ Animation(x=0,y=480, d=1, opacity=0.8) +\ Animation(x=0,y=480, d=4,opacity=1) +\ Animation(x=0,y=650, opacity=0, d=2) self.anim.start(self.label_info) self.notify_events.append(str(msg)) elif (int(copr) == 5): msg = msg.split("$#")[1] msg = msg.split(',') self.chat_ground.text = " " self.haha = [0] * 30 self.y = 0 for on in range(0, len(msg) - 1): self.haha[on] = Button(text=str(msg[on]), background_color=(0, 1, 0, 1), pos=(600, 515 - self.y), size_hint=(0.25, 0.07)) self.layout.add_widget(self.haha[on]) self.haha[on].bind( on_press=partial(self.open_chat_for, msg[on])) self.y = self.y + 45 self.layout.add_widget(self.update) return self.layout else: self.label.text = msg + "\n" def opentextinput(self, *args): ''' for sending a message to server or searching for ''' self.textbox = TextInput(size_hint=(.9, .1), pos=(0, 0), multiline=False, focus=True) self.textbox.bind(on_text_validate=self.send_message) self.closebutton = Button(text="Close", size_hint=(.1, .1), pos=(720, 0), background_color=(255, 0, 0, 1)) self.closebutton.bind(on_press=self.close_input_editor) self.layout.add_widget(self.textbox) self.layout.add_widget(self.closebutton) def close_input_editor(self, *args): ''' closing the requester -- textbox ''' self.layout.remove_widget(self.closebutton) self.layout.remove_widget(self.textbox) def CloseClient(self, *args): ''' client wants to disconnect with the server ''' self.conn.disconnect() self.layout.clear_widgets() #os.chdir(cd..) self.repo_creation() path = os.path.dirname(os.getcwd()) os.chdir(path) #output = subprocess.Popen(["cd.."],stdout=subprocess.PIPE).communicate()[0] print os.getcwd() return self.layout def chathistory(self, *args): ''' maintaining conversational history ''' self.layout.remove_widget(self.chatbox) self.layout.clear_widgets() self.sendarea = Label(text=" ", size_hint=(.2, .2), pos=(80, 400), font_size="19dp", color=(0.7, 0.5, 0.6, 1)) self.layout.add_widget(self.sendarea) self.update.bind(on_press=self.cancel_chat_box) self.layout.add_widget(self.chat_ground) self.backbutton = Button(text="Back <-", background_color=(1, 0.1, 0.1, 1), size_hint=(.11, .1), pos=(30, 500), font_size="20dp") self.layout.add_widget(self.backbutton) self.backbutton.bind(on_press=self.building_utilities) #self.layout.add_widget(self.cancel_chat) #self.cancel_chat.bind(on_press=self.cancel_chat_box) self.chat_online_details = "5$#" + user + "@" + user_os + ": " + "Ready to chat" #print self.chat_online_details self.connection.write(str(self.chat_online_details)) #return self.layout def stimulate_on_repo_changes(self): ''' checking for any file events in the current repo ''' while True: #self.logging.basicConfig(level=logging.INFO,format='%(asctime)s - %(message)s',datefmt='%Y-%m-%d %H:%M:%S') self.path = sys.argv[1] if len(sys.argv) > 1 else os.getcwd() self.event_handler = ChangeHandler(self) self.observer = Observer() self.observer.schedule(self.event_handler, self.path, recursive=True) self.observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: self.observer.stop() self.observer.join() def start_thread(self): t = Thread(target=self.stimulate_on_repo_changes) t.start() def notify(self, textevent): textevent1 = "4$#" + user + "@" + user_os + ": " + str(textevent) #textevent = "4$#" + textevent self.connection.write(str(textevent1)) return self.layout def dismiss_popup(instance): return False def recent_act(self, textevent): self.layout.remove_widget(self.notify_but) self.layout.add_widget(self.notify_ground) self.anim_ground = Animation(x=700,y=0, opacity=0.3, d=0.2,t ='in_quad') +\ Animation(x=600,y=0, opacity=1, d=0.2) self.anim_ground.start(self.notify_ground) self.layout.add_widget(self.cancel_event) self.cancel_event.bind(on_press=self.cancel_event_window) self.notify_ground.text = "" for l in self.notify_events: self.notify_ground.text = self.notify_ground.text + str(l) + '\n' return self.layout def cancel_event_window(self, *args): self.layout.remove_widget(self.notify_ground) self.layout.remove_widget(self.cancel_event) self.layout.add_widget(self.notify_but) return self.layout def cancel_chat_box(self, args): self.layout.clear_widgets() self.chathistory() return self.layout def open_chat_for(self, ipadd, args): self.chat_lid = TextInput(hint_text="Send msg", pos=(100, 50), size_hint=(.6, .1), multiline=False, focus=True) self.layout.add_widget(self.chat_lid) self.chat_lid.bind(on_text_validate=partial(self.send_to_ip, ipadd)) def send_to_ip(self, ipadd, args): print "send msg - '" + self.chat_lid.text + "' to ip address - " + ipadd self.connection.write("8$#" + str(ipadd) + "##" + str(self.chat_lid.text)) self.chat_lid.text = "" self.chat_lid.focus = True
class SegmentationUI(Widget): def __init__(self, movie, params, **kwargs): super().__init__(**kwargs) # Movie object self.movie = movie # How far the user has progressed through segmentation self.current_state = 0 self.prior_state = 0 # Current frame self.frame = 0 # Parameters for segmentation and channels to segment on self.params = params['seg_param'][...] self.seg_channels = self.params[15:18].astype(int) # Set classifier, label window and classified image to None to prevent them being prematurely used self.clf = None self.label_window = None self.im_class = None # Master layout for segmentation UI self.s_layout = FloatLayout(size=(Window.width, Window.height)) # Add image widgets to visualize segmentation results and the original image self.im_disp = ImDisplay(size_hint=(.76, .76), pos_hint={ 'x': .23, 'y': .14 }) self.s_layout.add_widget(self.im_disp) self.mov_disp = ImDisplay(size_hint=(.2, .2), pos_hint={ 'x': .78, 'y': .14 }) self.s_layout.add_widget(self.mov_disp) self.im = movie.read_im(0, 0) self.im_disp.create_im(self.im, 'PastelHeat') self.mov_disp.create_im(self.im, 'PastelHeat') # Add frame slider widget for choosing frames self.frame_slider = guitools.FrameSlider(self.movie.frames, self.change_frame, size_hint=(.29, .06), pos_hint={ 'x': .23, 'y': .91 }) self.s_layout.add_widget(self.frame_slider) # Add button for optional segmentation using multiple cores self.parallel_button = ToggleButton(text=' Multiple Cores ', size_hint=(.15, .04), pos_hint={ 'x': .682, 'y': .923 }) self.parallel_button.bind(on_press=self.update_parallel) self.s_layout.add_widget(self.parallel_button) # Add button to optionally filter out segments touching the edge self.edge_button = ToggleButton(text=' Filter edge ', size_hint=(.15, .04), pos_hint={ 'x': .53, 'y': .923 }) self.edge_button.bind(on_press=self.update_edge) self.s_layout.add_widget(self.edge_button) if self.params[9] == 1: self.edge_button.state = 'down' # Drop down menu for choosing which channel to segment on self.channel_choice = DropDown() for i in range(self.movie.channels): channel_btn = ToggleButton(text='Channel ' + str(i + 1), size_hint_y=None) if self.params[15 + i] == 1: channel_btn.state = 'down' channel_btn.bind(on_press=partial(self.change_channel, i)) self.channel_choice.add_widget(channel_btn) self.main_button = Button(text=' Channel ', size_hint=(.15, .04), pos_hint={ 'x': .834, 'y': .923 }) self.main_button.bind(on_release=self.channel_choice.open) self.channel_choice.bind( on_select=lambda instance, x: setattr(self.main_button, 'text', x)) self.s_layout.add_widget(self.main_button) # Sliders for updating parameters layout2 = GridLayout(cols=1, padding=2, size_hint=(.2, .84), pos_hint={ 'x': .01, 'y': .14 }) s1 = Slider(min=0, max=1, step=0.002, value=float(self.params[0])) s2 = Slider(min=0, max=300, step=5, value=float(self.params[1])) s3 = Slider(min=0, max=10, step=1, value=float(self.params[2])) s4 = Slider(min=0, max=1, step=0.005, value=float(self.params[3])) s5 = Slider(min=0, max=200, step=10, value=float(self.params[4])) s6 = Slider(min=0, max=1, step=0.05, value=float(self.params[5])) s7 = Slider(min=0, max=50, step=2, value=float(self.params[6])) s8 = Slider(min=0, max=10, step=1, value=float(self.params[7])) s9 = Slider(min=0, max=1, step=0.02, value=float(self.params[8])) s1.bind(value=partial(self.segment_script, state=2)) s2.bind(value=partial(self.segment_script, state=3)) s3.bind(value=partial(self.segment_script, state=4)) s4.bind(value=partial(self.segment_script, state=5)) s5.bind(value=partial(self.segment_script, state=6)) s6.bind(value=partial(self.segment_script, state=7)) s7.bind(value=partial(self.segment_script, state=8)) s8.bind(value=partial(self.segment_script, state=1)) s9.bind(value=partial(self.segment_script, state=9)) # Slider labels self.s1_label = guitools.ntlabel(text='Clipping Limit: ' + str(self.params[0]), style=2) self.s2_label = guitools.ntlabel(text='Background Blur: ' + str(self.params[1]), style=2) self.s3_label = guitools.ntlabel(text='Image Blur: ' + str(self.params[2]), style=2) self.s4_label = guitools.ntlabel(text='Threshold: ' + str(self.params[3]), style=2) self.s5_label = guitools.ntlabel(text='Smallest Object: ' + str(self.params[4]), style=2) self.s6_label = guitools.ntlabel(text='Distance to Intensity: ' + str(self.params[5]), style=2) self.s7_label = guitools.ntlabel(text='Separation Distance: ' + str(self.params[6]), style=2) self.s8_label = guitools.ntlabel(text='Edge Blur: ' + str(self.params[7]), style=2) self.s9_label = guitools.ntlabel(text='Watershed Ratio: ' + str(self.params[8]), style=2) # Button for using pixel classifier on images self.b1 = ToggleButton(text='Classify Pixels') self.b1.bind(on_press=self.ml_segment) self.spacer = Label(text='') # Button to save parameters for segmentation b2 = Button(text='Save Params') b2.bind(on_press=self.save_params) # Add widgets to layout layout2.add_widget(s1) layout2.add_widget(self.s1_label) layout2.add_widget(s2) layout2.add_widget(self.s2_label) layout2.add_widget(s3) layout2.add_widget(self.s3_label) layout2.add_widget(self.b1) layout2.add_widget(self.spacer) layout2.add_widget(s4) layout2.add_widget(self.s4_label) layout2.add_widget(s5) layout2.add_widget(self.s5_label) layout2.add_widget(s6) layout2.add_widget(self.s6_label) layout2.add_widget(s7) layout2.add_widget(self.s7_label) layout2.add_widget(s8) layout2.add_widget(self.s8_label) layout2.add_widget(s9) layout2.add_widget(self.s9_label) layout2.add_widget(b2) self.layout2 = layout2 with self.canvas: self.add_widget(self.s_layout) self.s_layout.add_widget(self.layout2) def ml_segment(self, instance): # Ensure that image is at correct stage of segmentation self.segment_script([], self.params[2], state=4) # Swap layouts to ml layout self.s_layout.remove_widget(self.layout2) self.ml_layout = GridLayout(cols=1, padding=2, size_hint=(.2, .84), pos_hint={ 'x': .01, 'y': .14 }) # Add widget that allows user to paint foreground and background pixels, stores list of central pixel and brush # size for each brush stroke self.label_window = LabelWindow(size_hint=(.76, .76), pos_hint={ 'x': .23, 'y': .14 }) self.s_layout.add_widget(self.label_window) # Set default size of paint brush and attach widget to adjust this size self.brush_size = 20 btn_size = Slider(min=1, max=100, step=1, value=30) btn_size.bind(value=self.change_size) self.ml_layout.add_widget(btn_size) self.brush_lbl = Label(text='[color=000000]Brush Size ' + str(self.brush_size) + '[/color]', markup=True) self.ml_layout.add_widget(self.brush_lbl) # Toggle buttons to select whether foreground or background is being labelled self.select_fg = ToggleButton(text='Select Nuclei', group='label_data') self.ml_layout.add_widget(self.select_fg) self.select_bg = ToggleButton(text='Select Background', group='label_data') self.ml_layout.add_widget(self.select_bg) # Button to clear current selection clear = Button(text='Clear Selection') clear.bind(on_press=self.label_window.clear) self.ml_layout.add_widget(clear) # Button to add training examples to list of all training data and output probability map classify = Button(text='Calculate Probability') classify.bind(on_press=self.classify) self.ml_layout.add_widget(classify) # Button to restore image and if the user wants to add more training data rev_image = Button(text='Revert Image') rev_image.bind(on_press=self.revert_image) self.ml_layout.add_widget(rev_image) # Open close parameter to reduce noise in pixel level classification soc = Slider(min=0, max=20, step=1, value=int(self.params[12])) soc.bind(value=self.open_close) self.ml_layout.add_widget(soc) self.oc_lbl = Label(text='[color=000000]Open Close ' + str(self.params[12]) + '[/color]', markup=True) self.ml_layout.add_widget(self.oc_lbl) # Reset all training data reset = Button(text='Reset Training') reset.bind(on_press=self.reset_train) self.ml_layout.add_widget(reset) # Leave the ml window and return to normal segmentation cont = Button(text='Continue Segmentation') cont.bind(on_press=self.continue_seg) self.ml_layout.add_widget(cont) # Counter which gives the number of training examples for pixel level classification self.train_count = Label(text='[color=000000]Train pxls ' + str(0) + '[/color]', markup=True) if 'seg_training' in self.parent.params: count = self.parent.params['seg_training']['X'].shape[0] self.train_count.text = '[color=000000]Train pxls ' + str( count) + '[/color]' self.ml_layout.add_widget(self.train_count) # Add the ml_layout self.s_layout.add_widget(self.ml_layout) def reset_train(self, instance): if 'seg_training' in self.parent.params: del self.parent.params['seg_training'] self.train_count.text = '[color=000000]Train pxls ' + str( 0) + '[/color]' self.clf = None self.im_disp.update_im(self.im) def continue_seg(self, instance): self.s_layout.remove_widget(self.ml_layout) self.s_layout.remove_widget(self.label_window) self.s_layout.add_widget(self.layout2) self.label_window = None def change_size(self, instance, val): self.brush_size = val self.brush_lbl.text = '[color=000000]Brush Size ' + str( np.round(val)) + '[/color]' def classify(self, instance): self.segment_script([], self.params[2], state=4) dims = self.movie.dims # Parameters for stride and width of MLP region of interest self.params[13] = 12 self.params[14] = 2 wsize = int(self.params[13]) stride = int(self.params[14]) # Initialize arrays for foreground and background pixels P = np.zeros((1, 2)) N = np.zeros((1, 2)) pixel_bg = self.label_window.pixel_list_bg pixel_fg = self.label_window.pixel_list_fg if len(pixel_fg) > 0 and len(pixel_bg) > 0: # Scale pixel lists in range 0 to 1 to image dimensions pixel_bg = np.asarray(pixel_bg) pixel_fg = np.asarray(pixel_fg) pixel_bg[:, [0, 2]] = pixel_bg[:, [0, 2]] * dims[1] pixel_bg[:, [1, 3]] = pixel_bg[:, [1, 3]] * dims[0] pixel_fg[:, [0, 2]] = pixel_fg[:, [0, 2]] * dims[1] pixel_fg[:, [1, 3]] = pixel_fg[:, [1, 3]] * dims[0] pixel_bg = pixel_bg.astype(int) pixel_fg = pixel_fg.astype(int) # Identify pixels within elliptical roi around central pixel defined by brush size for i in range(pixel_bg.shape[0]): pixls = classifypixels.ellipse_roi(pixel_bg[i, :], dims) N = np.vstack((N, pixls)) for i in range(pixel_fg.shape[0]): pixls = classifypixels.ellipse_roi(pixel_fg[i, :], dims) P = np.vstack((P, pixls)) # Calculate necessary expansion of image needed to perform pixel convolution conv_im = segmentimages.expand_im(self.im3, self.params[13]) # Add expansion amount to pixels in list to center on new image P = P[1:, :] + self.params[13] + 1 N = N[1:, :] + self.params[13] + 1 # Take unique pixel values P = classifypixels.unique_pixls(P) N = classifypixels.unique_pixls(N) P = P.astype(int) N = N.astype(int) X = [] y = [] # Extract intensity values for given pixels for i in range(P.shape[0]): roi = conv_im[P[i, 0] - wsize:P[i, 0] + wsize, P[i, 1] - wsize:P[i, 1] + wsize] roi = roi[::stride, ::stride] X.append(roi.flatten()) y.append(1) for i in range(N.shape[0]): roi = conv_im[N[i, 0] - wsize:N[i, 0] + wsize, N[i, 1] - wsize:N[i, 1] + wsize] roi = roi[::stride, ::stride] X.append(roi.flatten()) y.append(0) # Convert to numpy arrays for classification X = np.asarray(X) y = np.asarray(y) R = np.random.permutation(np.arange(X.shape[0])) R = R.astype(int) X = X[R, :] y = y[R] self.label_window.clear([]) # Create new training data hdf5 file if no prior data exists else append if len(pixel_fg) > 0 and len(pixel_bg) > 0: if 'seg_training' in self.parent.params: X1 = self.parent.params['seg_training']['X'][...] y1 = self.parent.params['seg_training']['y'][...] if len(pixel_fg) > 0 and len(pixel_bg) > 0: X = np.vstack((X, X1)) y = np.hstack((y, y1)) else: X = X1 y = y1 del self.parent.params['seg_training'] # Update training pixel counts self.train_count.text = '[color=000000]Train pxls ' + str( X.shape[0]) + '[/color]' training_hdf5 = self.parent.params.create_group('seg_training') training_hdf5.create_dataset('X', data=X) training_hdf5.create_dataset('y', data=y) else: self.train_count.text = '[color=000000]Train pxls ' + str( X.shape[0]) + '[/color]' training_hdf5 = self.parent.params.create_group('seg_training') training_hdf5.create_dataset('X', data=X) training_hdf5.create_dataset('y', data=y) # Perform classification is training data is present if 'seg_training' in self.parent.params: self.clf = classifypixels.train_clf( self.parent.params['seg_training']) self.im_class = segmentimages.im_probs(self.im3.copy(), self.clf, wsize, stride) # Also perform open and closing here if the parameter is greater than 0 if self.params[12] > 0: self.im_open_close = segmentimages.open_close( self.im_class, self.params[12]) else: self.im_open_close = self.im_class.copy() self.im_disp.update_im(self.im_open_close) def revert_image(self, instance): self.im_disp.update_im(self.im3) def open_close(self, instance, val): if self.im_class is None: self.im_class = self.im3 # users can call open close prior to classification as well if val > 0: self.oc_lbl.text = '[color=000000]Open Close ' + str( np.round(val)) + '[/color]' self.im_open_close = segmentimages.open_close(self.im_class, val) self.im_disp.update_im(self.im_open_close) self.params[12] = val else: self.params[12] = val def segment_script(self, instance, val, **kwargs): # Dynamically update segmentation image and parameters state = kwargs['state'] self.current_state = state if state != 0: if state >= 2 >= self.prior_state or state == 2: if state == 2: # if state is equal to stage of segmentation modify parameter if not val == -1: self.params[0] = val guitools.ntchange(label=self.s1_label, text='Clipping Limit ' + str(np.round(val, 2)), style=2) self.im1 = segmentimages.clipping( self.im, self.params[0]) # perform image analysis operation if state == 2: # if state is equal to stage of segmentation update display image self.im_disp.update_im(self.im1) self.prior_state = 2 if state >= 3 >= self.prior_state or state == 3: if state == 3: if not val == -1: self.params[1] = val guitools.ntchange(label=self.s2_label, text='Background blur: ' + str(np.round(val, 2)), style=2) self.im2 = segmentimages.background(self.im1, self.params[1]) if state == 3: self.im_disp.update_im(self.im2) self.prior_state = 3 if state >= 4 >= self.prior_state or state == 4: if state == 4: if not val == -1: self.params[2] = val guitools.ntchange(label=self.s3_label, text='Image blur: ' + str(np.round(val, 2)), style=2) self.im3 = segmentimages.blur(self.im2, self.params[2]) if state == 4: self.im_disp.update_im(self.im3) self.prior_state = 4 # Pixel classifier state sits optionally between blurring and threshold if state >= 4.5 >= self.prior_state: if self.clf is None: if 'seg_training' in self.parent.params: self.clf = classifypixels.train_clf( self.parent.params['seg_training']) if self.clf is not None: self.im3b = segmentimages.im_probs(self.im3, self.clf, int(self.params[13]), int(self.params[14])) else: self.im3b = self.im3 if self.params[12] > 0: self.im3c = segmentimages.open_close( self.im3b, self.params[12]) else: self.im3c = self.im3b self.prior_state = 4.5 if state >= 5 >= self.prior_state or state == 5: if state == 5: if not val == -1: self.params[3] = val guitools.ntchange(label=self.s4_label, text='Threshold: ' + str(np.round(val, 2)), style=2) self.im_bin_uf = segmentimages.threshold( self.im3c, self.params[3]) if state == 5: self.im_disp.update_im(self.im_bin_uf.astype(float)) self.prior_state = 5 if state >= 6 >= self.prior_state or state == 6: if state == 6: if not val == -1: self.params[4] = val guitools.ntchange(label=self.s5_label, text='Smallest Object: ' + str(np.round(val, 2)), style=2) self.im_bin = segmentimages.object_filter( self.im_bin_uf, self.params[4]) if state == 6: self.im_disp.update_im(self.im_bin.astype(float)) self.prior_state = 6 if state >= 7 >= self.prior_state or state == 7: if state == 7: if not val == -1: self.params[5] = val guitools.ntchange(label=self.s6_label, text='Distance to Intensity: ' + str(np.round(val, 2)), style=2) if self.params[11] == 1: [self.cell_center, self.d_mat ] = segmentimages.cell_centers(self.im_open_close, self.im_bin, self.params[5]) else: [self.cell_center, self.d_mat ] = segmentimages.cell_centers(self.im3, self.im_bin, self.params[5]) if state == 7: self.im_disp.update_im(self.cell_center) self.prior_state = 7 if state >= 8 >= self.prior_state or state == 8: if state == 8: if not val == -1: self.params[6] = val guitools.ntchange(label=self.s7_label, text='Separation Distance: ' + str(np.round(val, 2)), style=2) self.markers = segmentimages.fg_markers( self.cell_center, self.im_bin, self.params[6], self.params[9]) if state == 8: self.im_disp.update_im(self.cell_center + (self.markers > 0)) self.prior_state = 8 if state == 1 or 9: if state == 1: if not val == -1: self.params[7] = val guitools.ntchange(label=self.s8_label, text='Edge Blur: ' + str(np.round(val, 2)), style=2) self.im_edge = segmentimages.sobel_edges( self.im1, self.params[7]) if state == 1: self.im_disp.update_im(self.im_edge) if state == 9: if not val == -1: self.params[8] = val guitools.ntchange(label=self.s9_label, text='Watershed Ratio: ' + str(np.round(val, 2)), style=2) self.labels = segmentimages.watershed(self.markers, self.im_bin, self.im_edge, self.d_mat, self.params[8], self.params[9]) self.im_disp.update_im(self.labels.astype(float)) def save_params(self, instance): self.parent.params['seg_param'][...] = self.params[...] def update_parallel(self, instance): if instance.state == 'down': self.parent.parallel = True else: self.parent.parallel = False def update_edge(self, instance): if instance.state == 'down': self.params[9] = 1 else: self.params[9] = 0 def change_frame(self, val): self.frame = val self.update_im() self.prior_state = 0 def change_channel(self, val, instance): if instance.state == 'down': self.seg_channels[val] = 1 self.params[15 + val] = 1 else: if sum(self.seg_channels) > 1: self.seg_channels[val] = 0 self.params[15 + val] = 0 self.update_im() self.prior_state = 0 def update_im(self): self.im = self.movie.comb_im(self.seg_channels, self.frame) self.imml = self.im.copy() if self.current_state > 0: self.segment_script([], -1, state=self.current_state) else: self.im_disp.update_im(self.im) self.mov_disp.update_im(self.im) if self.label_window is not None: self.label_window.clear([]) def update_size(self, window, width, height): self.s_layout.width = width self.s_layout.height = height
class BatchSegment(Widget): def __init__(self, movie, labels, params, parallel, **kwargs): super().__init__(**kwargs) self.params = params['seg_param'][...] # Classifier is used if training data is present self.clf = 0 if 'seg_training' in params: self.clf = classifypixels.train_clf(params['seg_training']) self.movie = movie self.labels = labels self.layout = FloatLayout(size=(Window.width, Window.height)) if parallel: # Cannot provide loading bar if parallel processing is used with current structure self.seg_message = Label(text='[b][color=000000]Parallel Processing' \ '\n No Loading Bar[/b][/color]', markup=True, size_hint=(.2, .05), pos_hint={'x': .4, 'y': .65}) with self.canvas: self.add_widget(self.layout) self.layout.add_widget(self.seg_message) else: # Add loading bar to canvas and initiate scheduling of segmentation self.seg_message = Label( text='[b][color=000000]Segmenting Images[/b][/color]', markup=True, size_hint=(.2, .05), pos_hint={ 'x': .4, 'y': .65 }) self.layout2 = GridLayout(rows=1, padding=2, size_hint=(.9, .1), pos_hint={ 'x': .05, 'y': .5 }) self.pb = ProgressBar(max=1000, size_hint=(8., 1.), pos_hint={ 'x': .1, 'y': .6 }, value=1000 / self.movie.frames) self.layout2.add_widget(self.pb) with self.canvas: self.add_widget(self.layout) self.layout.add_widget(self.seg_message) self.layout.add_widget(self.layout2) def update_bar(self, dt): self.pb.value += 1000 / self.movie.frames def segment_im(self, frame, dt): self.labels[frame, :, :] = segmentimages.segment_image( self.movie, self.params, self.clf, frame) def segment_parallel(self): # Schedule segmentation of images in parallel using pool class cpu_count = multiprocessing.cpu_count() pool = Pool(cpu_count) labels = pool.map( partial(segmentimages.segment_image, self.movie, self.params, self.clf), range(self.movie.frames)) pool.close() pool.join() for i in range(self.movie.frames): self.labels[i, :, :] = labels[i] def get(self): self.seg_message.text = '[b][color=000000]Images Segmented[/b][/color]' return self.labels def update_size(self, window, width, height): self.width = width self.height = height
class MainScreen(Screen): def __init__(self, **kwargs): super(MainScreen, self).__init__(**kwargs) import Tkinter root = Tkinter.Tk() self.WIN_WIDTH, self.WIN_HEIGHT = root.winfo_screenwidth( ), root.winfo_screenheight() self.MIL_WIDTH, self.MIL_HEIGHT = root.winfo_screenmmwidth( ), root.winfo_screenmmheight() self.PPC = 10. * (float(self.WIN_WIDTH) / self.MIL_WIDTH + float(self.WIN_HEIGHT) / self.MIL_HEIGHT) / 2. self.SCREEN_INFO = (self.WIN_WIDTH, self.WIN_HEIGHT, self.MIL_WIDTH, self.MIL_HEIGHT, self.PPC) self.capture = cv2.VideoCapture(0) self.capture.set(3, self.WIN_WIDTH) self.capture.set(4, self.WIN_HEIGHT) self.eyeTracker = None try: self.eyeTracker = pylink.EyeLink('100.1.1.1') except: self.eyeTracker = None print "Could not connect to eye tracker" ''' Layout the layouts ''' self.mainLayout = mainLayout = FloatLayout() with mainLayout.canvas.before: Color(.8, .8, .8, 1) self.background = Rectangle(size=self.size, pos=self.pos) mainLayout.bind(pos=self._updateBackground, size=self._updateBackground) hgap, vgap = 0.01, 0.01 self.topLeftLayout = topLeftLayout = PartialLayout( size_hint=(.5 - hgap / 2, 0.4 * (1 - 2 * vgap)), pos_hint={ 'center_x': 0.25 - hgap / 4, 'center_y': .804 }) self.middleLeftLayout = middleLeftLayout = PartialLayout( size_hint=(.5 - hgap / 2, 0.5 * (1 - 2 * vgap)), pos_hint={ 'center_x': 0.25 - hgap / 4, 'center_y': .353 }) self.bottomLeftLayout = bottomLeftLayout = PartialLayout( size_hint=(.5 - hgap / 2, 0.1 * (1 - 2 * vgap)), pos_hint={ 'center_x': 0.25 - hgap / 4, 'center_y': .049 }) self.rightLayout = rightLayout = PartialLayout(size_hint=(.5 - hgap / 2, 1), pos_hint={ 'center_x': 0.75 + hgap / 4, 'center_y': .5 }) self.add_widget(mainLayout) mainLayout.add_widget(topLeftLayout) mainLayout.add_widget(middleLeftLayout) mainLayout.add_widget(bottomLeftLayout) mainLayout.add_widget(rightLayout) ''' Top left layout ''' saveFolderLabel = Label(text='Save Folder', size_hint=(0.4, 0.25), pos_hint={ 'center_x': 0.2, 'center_y': 0.875 }) folderButton = Button(source='Assets/folder.png', size_hint=(None, None), size=(0.05 * self.WIN_HEIGHT, 0.05 * self.WIN_HEIGHT), pos_hint={ 'center_x': 0.45, 'center_y': 0.875 }) self.folderText = TextInput(size_hint=(0.5, 0.125), pos_hint={ 'center_x': 0.75, 'center_y': 0.875 }) subjectIDLabel = Label(text='Subject ID', size_hint=(0.5, 0.25), pos_hint={ 'center_x': 0.25, 'center_y': 0.625 }) self.subjectIDText = TextInput(size_hint=(0.5, 0.125), pos_hint={ 'center_x': 0.75, 'center_y': 0.625 }) calibButton = Button(text='Calibrate Eye Tracker', size_hint=(1, 0.25), pos_hint={ 'center_x': 0.5, 'center_y': 0.375 }) checkCamButton = Button(text='Check Camera', size_hint=(1, 0.25), pos_hint={ 'center_x': 0.5, 'center_y': 0.125 }) folderButton.background_normal = 'Assets/folder_normal.png' folderButton.background_down = 'Assets/folder_down.png' topLeftLayout.add_widget(saveFolderLabel) topLeftLayout.add_widget(folderButton) topLeftLayout.add_widget(self.folderText) topLeftLayout.add_widget(subjectIDLabel) topLeftLayout.add_widget(self.subjectIDText) topLeftLayout.add_widget(calibButton) topLeftLayout.add_widget(checkCamButton) ''' Middle Left Layout ''' designerLabel = Label(text='Experiment Designer', size_hint=(1, 0.2), pos_hint={ 'center_x': 0.5, 'center_y': 0.9 }) self.asd = asd = AntisaccadeDesigner(size_hint=(1, 0.39), pos_hint={ 'center_x': 0.5, 'center_y': 0.6 }) self.vsd = vsd = VisualSearchDesigner(size_hint=(1, 0.39), pos_hint={ 'center_x': 0.5, 'center_y': 0.2 }) middleLeftLayout.add_widget(designerLabel) middleLeftLayout.add_widget(asd) middleLeftLayout.add_widget(vsd) ''' Bottom Left Layout ''' startButton = Button(text='Start', size_hint=(0.5, 0.99), pos_hint={ 'center_x': 0.5, 'center_y': 0.5 }) bottomLeftLayout.add_widget(startButton) ''' Right Layout ''' self.stimGrid = GridLayout(cols=1, spacing=10, size_hint_y=None) self.stimGrid.bind(minimum_height=self.stimGrid.setter('height')) with self.stimGrid.canvas.before: Color(0, 0, 0, 1) self.gridRect = Rectangle(size=self.stimGrid.size, pos=self.stimGrid.pos) self.stimGrid.bind(pos=self._updateGridRect, size=self._updateGridRect) flowLabel = Label(text='Experiment Flow', size_hint=(1, 0.1), pos_hint={ 'center_x': 0.5, 'center_y': 0.95 }) scroller = ScrollView(size_hint=(1, 0.7), pos_hint={ 'center_x': 0.5, 'center_y': 0.55 }) showButton = Button(text='Hide', size_hint=(0.5, 0.1), pos_hint={ 'center_x': 0.25, 'center_y': 0.15 }) clearButton = Button(text='Clear', size_hint=(0.5, 0.1), pos_hint={ 'center_x': 0.75, 'center_y': 0.15 }) randButton = Button(text='Randomize', size_hint=(0.5, 0.1), pos_hint={ 'center_x': 0.25, 'center_y': 0.05 }) scroller.add_widget(self.stimGrid) rightLayout.add_widget(flowLabel) rightLayout.add_widget(scroller) rightLayout.add_widget(showButton) rightLayout.add_widget(clearButton) rightLayout.add_widget(randButton) ''' Other widgets ''' self.isVisible = True self.coverWidget = FloatLayout(size_hint=(1, 0.7), pos_hint={ 'center_x': 0.5, 'center_y': 0.55 }) with self.coverWidget.canvas.before: Color(0, 0, 0, 1) self.coverRect = Rectangle(size=self.coverWidget.size, pos=self.coverWidget.pos) self.coverWidget.bind(pos=self._updateCoverRect, size=self._updateCoverRect) self.coverWidget.add_widget( Label(text='Experiment flow is\ncurrently hidden.', size_hint=(1, 1), pos_hint={ 'center_x': 0.5, 'center_y': 0.5 })) self.calibrationWidget = FloatLayout(size_hint=(1, 1), pos_hint={ 'center_x': 0.5, 'center_y': 0.5 }) with self.calibrationWidget.canvas.before: Color(0, 0, 0, 1) self.calibRect = Rectangle(size=self.calibrationWidget.size, pos=self.calibrationWidget.pos) self.calibrationWidget.bind(pos=self._updateCalibOverlay, size=self._updateCalibOverlay) self.coverWidget.add_widget( Label(text=CALIB_TEXT, size_hint=(1, 1), pos_hint={ 'center_x': 0.5, 'center_y': 0.5 })) ''' Object Bindings ''' folderButton.bind(on_release=self.chooseRootFolder) checkCamButton.bind(on_release=self.toCheckCam) calibButton.bind(on_release=self.calibrateEyelink) self.asd.addButton.bind(on_release=self.addAntisaccade) self.vsd.addButton.bind(on_release=self.addVisualSearch) startButton.bind(on_release=self.startExperiment) showButton.bind(on_release=self.toggleGUI) clearButton.bind(on_release=self.clearExperiment) randButton.bind(on_release=self.randomizeOrder) def chooseRootFolder(self, _): pass def calibrateEyelink(self, _): if not self.eyeTracker is None: self.eyeTracker.doTrackerSetup() def toCheckCam(self, _): self.parent.transition.direction = 'left' self.parent.current = 'check_cam' def addAntisaccade(self, _): stimLabel = StimLabel(text='Antisaccade', size_hint_y=None, height=self.WIN_HEIGHT / 10) self.stimGrid.add_widget(stimLabel) stimLabel.buttonUp.bind(on_release=self.moveTaskUp) stimLabel.buttonDown.bind(on_release=self.moveTaskDown) stimLabel.buttonRemove.bind(on_release=self.removeTask) def addVisualSearch(self, _): text = 'Visual Search\nContrast(s): {}, Stimuli: {}'.format( self.vsd.mainContrastButton.text.split(' ')[0], self.vsd.mainConditionButton.text.split(' ')[0]) stimLabel = StimLabel(text=text, size_hint_y=None, height=self.WIN_HEIGHT / 10) self.stimGrid.add_widget(stimLabel) stimLabel.buttonUp.bind(on_release=self.moveTaskUp) stimLabel.buttonDown.bind(on_release=self.moveTaskDown) stimLabel.buttonRemove.bind(on_release=self.removeTask) def moveTaskUp(self, obj): index = self.stimGrid.children.index(obj.parent.parent) if index == len(self.stimGrid.children) - 1: return child = self.stimGrid.children[index] self.stimGrid.remove_widget(child) self.stimGrid.add_widget(child, index + 1) def moveTaskDown(self, obj): index = self.stimGrid.children.index(obj.parent.parent) if index == 0: return child = self.stimGrid.children[index] self.stimGrid.remove_widget(child) self.stimGrid.add_widget(child, index - 1) def removeTask(self, obj): self.stimGrid.remove_widget(obj.parent.parent) def startExperiment(self, _): if len(self.stimGrid.children) == 0: return def toggleGUI(self, _): if self.isVisible: self.rightLayout.add_widget(self.coverWidget) else: self.rightLayout.remove_widget(self.coverWidget) self.isVisible = not self.isVisible def clearExperiment(self, _): self.stimGrid.clear_widgets() def randomizeOrder(self, _): random.shuffle(self.stimGrid.children) def _updateBackground(self, instance, _): self.background.pos = instance.pos self.background.size = instance.size def _updateGridRect(self, instance, _): self.gridRect.pos = instance.pos self.gridRect.size = instance.size def _updateCoverRect(self, instance, _): self.coverRect.pos = instance.pos self.coverRect.size = instance.size def _updateCalibOverlay(self, instance, _): self.calibrationWidget.pos = instance.pos self.calibrationWidget.size = instance.size
def post(self, *args): global location_layer layout = FloatLayout() self.mapview = MapView(zoom=18, lat=52.824725, lon=-6.935661) line = LineMapLayer() self.mapview.add_layer(line, mode="scatter") # window scatter drone_layer = DroneMarkerLayer() self.mapview.add_layer(drone_layer, mode="scatter") location_layer = LocationMarkerLayer() self.mapview.add_layer(location_layer, mode="scatter") flights_layer = FlightLayer() self.mapview.add_layer(flights_layer, mode="scatter") layout.add_widget(self.mapview) dronebuttoncolor = [.3,1,0,1] #Green locationbuttoncolor = [.5,1,1,1] #Blue flightbuttoncolor = [1,1,.5,1] #Yellow #Button containers buttonrow1 = BoxLayout(orientation='horizontal',height='30dp',size_hint_y=None) buttonrow2 = BoxLayout(orientation='horizontal',height='30dp',size_hint_y=None) buttonrow3 = BoxLayout(orientation='horizontal',height='30dp',size_hint_y=None) buttonrow1.add_widget(Button(text="RemoveDrone",on_press=lambda a: drone_layer.remove_drone_popup(), background_color = dronebuttoncolor)) buttonrow1.add_widget(Button(text="AddDrone",on_press=lambda a: drone_layer.add_virtual_drone_popup(), background_color = dronebuttoncolor)) buttonrow1.add_widget(Button(text="ViewLocationsList",on_press=lambda a: location_layer.view_locations_popup(), background_color = locationbuttoncolor)) buttonrow1.add_widget(Button(text="ViewLocationMarkers", background_color = locationbuttoncolor, on_press=lambda a: show_locations_button(self.mapview, location_layer, drone_layer))) buttonrow2.add_widget(Button(text="ViewDrones", background_color = dronebuttoncolor,on_press=lambda a: show_drones_button(self.mapview, drone_layer, location_layer))) buttonrow2.add_widget(Button(text="AddVirtualDrone",on_press=lambda a: drone_layer.add_virtual_drone_popup(), background_color = dronebuttoncolor)) buttonrow2.add_widget(Button(text="AddLocation",on_press=lambda a: location_layer.add_point_popup(), background_color = locationbuttoncolor)) buttonrow2.add_widget(Button(text="RemoveLocation",on_press=lambda a: location_layer.remove_location_popup(), background_color = locationbuttoncolor)) buttonrow3.add_widget(Button(text="ViewFlightsList",on_press=lambda a: flights_layer.view_flights_popup(), background_color = flightbuttoncolor)) buttonrow3.add_widget(Button(text="CreateFlight",on_press=lambda a: flights_layer.create_flight_popup(), background_color = flightbuttoncolor)) buttonrow3.add_widget(Button(text="RemoveFlight",on_press=lambda a: flights_layer.remove_flight_popup(), background_color = flightbuttoncolor)) buttonrow3.add_widget(Button(text="StartFlight",on_press=lambda a: flights_layer.start_flight_popup(), background_color = flightbuttoncolor)) buttonrow3.add_widget(Button(text="AbortFlight",on_press=lambda a: flights_layer.abort_flight_popup(), background_color = flightbuttoncolor)) #First button row self.root.add_widget(buttonrow1) #Second button row self.root.add_widget(buttonrow2) #Third button row self.root.add_widget(buttonrow3) self.root.add_widget(layout) #Used to draw locationmarkers on screen def show_locations_button(mapview, locationslayer, droneslayer): global location_hidden global drone_hidden global threads mapv = mapview locationsl = locationslayer dronesl = droneslayer if location_hidden == True: location_hidden = False locationsl.draw_locations() elif location_hidden == False: location_hidden = True for child in mapv.children: if type(child) is MarkerMapLayer: #Remove all marker widgets and add back in Drone markers if not hidden child.clear_widgets() if drone_hidden == False: threads.append(Thread(target = dronesl.draw_drones, args = (dronesl, locationsl), daemon = True)) threads[len(threads)-1].start() break #Used to draw drone markers on screen def show_drones_button(mapview, droneslayer, locationslayer): global drone_hidden global location_hidden global threads mapv = mapview dronesl = droneslayer locationsl = locationslayer if drone_hidden == True: drone_hidden = False threads.append(Thread(target = dronesl.draw_drones, args = (dronesl, locationsl), daemon = True)) threads[len(threads)-1].start() elif drone_hidden == False: drone_hidden = True for child in mapv.children: if type(child) is MarkerMapLayer: #Remove all marker widgets and add back in Location markers if not hidden child.clear_widgets() if location_hidden == False: locationsl.draw_locations() break
def __init__(self, **kwargs): super(First, self).__init__(**kwargs) ## Creating UI Elements ## # Creating Float Layout Fl = FloatLayout() # Creating reload image button reload_btn = Button(text="", background_normal="reload_sprite.png", background_down="reload_sprite_2.png", pos_hint={ 'center_y': .65, 'center_x': .67 }, size_hint=(.06, .18)) # Creating "Enter file name" label l = Label(text='Select file from directory', font_size='15sp', pos_hint={ 'center_y': .85, 'center_x': .5 }, size_hint=(.3, .25)) # Creating Error Label, Set to Hidden self.err = Label(text='Error: Invalid File Selected', font_size='13sp', pos_hint={ 'center_y': .2, 'center_x': .5 }, size_hint=(.3, .25), color=[1, .8, .8, 0]) #################### Generate Spinner Values################ cwd = os.getcwd() # Get Current Working Directory (CWD) self.files = [] for f in listdir(cwd): if isfile(join(cwd, f)): # Check if File Extension is ".csv" (Is it a csv file?) if (f.replace(" ", "")[-4:] == ".csv"): self.files.append(f) # If .csv files are not found in directory, display error if (len(self.files) == 0): self.files = ["No .csv files found in directory"] # Truncate all values that exceed spinner, display new values self.modfiles = self.files[::] # Create new instance of files called "modfiles" for i, item in enumerate(self.modfiles): if (len(item) > 40): self.modfiles[i] = item[:40] + "..." # print(self.files) #Create spinner self.spinner = Spinner(text="Select File", values=set(self.modfiles), size_hint=(.6, .2), pos_hint={ "center_y": .65, "center_x": .4 }) # Create Import Button btn = Button(text="Import", size_hint=(.2, .2), background_color=(.3, .6, .7, 1), pos_hint={ "center_y": .65, "center_x": .8 }) ## ACTIONS/TRIGGERS AND BINDINGS ## # Function: When Button Pressed def on_button(instance): Window.left = 250 Window.top = 40 global questioninfo # print(self.files,self.modfiles) try: ## NOTE: self.spinner.text will give you the value that is selected in the spinner try: file = self.files[self.modfiles.index(self.spinner.text)] except ValueError: file = "Select File" print('File Selected (via Spinner on First Screen): ', file) # Useless Data Validation (If Value Filepath) if not (os.path.isfile(file)): raise Error("Please Select a valid .csv file") # Data Validation (If Default "Select" value) if (file != "Select File" or file != "No .csv files found in directory"): questioninfo = [] # FILE DATA HANDLING global surveyfile try: surveyfile = pd.read_csv(file) except: raise Error("Please Select a valid .csv file") global filename global perresponse filename = file questions = list(surveyfile.columns.values) global notallowed for question in questions: isInvalid = False for restricted in notallowed: # CANNOT USE QUESTION.LOWER() IN NOT ALLOWED if question.lower() == restricted.lower(): isInvalid = True break if not isInvalid: questioninfo.append( Question(question, list(surveyfile[question]), '', '', '', '', '', '', '', '', '', '', '', '', '', '', False)) # REMOVING UNWANTED VALUES for validquestiondata in questioninfo: rowisvalid = False for response in validquestiondata.data: try: #print(response) if str(response).strip().lower( ) == "nil" or str(response).strip().lower( ) == "na" or str(response).strip( ) == "" or response == [] or ( type(response) == float and math.isnan(response) ): #(isinstance(response, float) and math.isnan(float(response)) #print("BAD") validquestiondata.data.remove(response) else: #print("{} is normal valid".format(response)) rowisvalid = True except: # print("{} is valid".format(response)) rowisvalid = True pass if rowisvalid: # print(validquestiondata.name) validquestiondata.isValidRow = True if len(questioninfo) == 0: raise Error("Please Select a valid .csv file") else: selectedButton = questioninfo[0] ## ANALYSING OF DATA ## # TOGGLE STATES MODIFICATION global toggle_states global directstate directstate = [] toggle_states = [] agreearray = [ 'agree', 'strongly agree', 'disagree', 'strongly disagree', 'neutral' ] for item in questioninfo: if item.isValidRow: dataArray = {} for value in item.data: # NOTE: Already Sorted, Remove Whitespace if There # NOTE: FOR DEBUG PURPOSES # print(str(value).lower().strip()) # print(dataArray.keys()) if str(value).lower().strip( ) in dataArray.keys(): dataArray[str(value).lower().strip()] += 1 else: dataArray[str(value).lower()] = 1 # DATA ANALYSIS (Multiple-Choice, Strongly Agree/Disagree, Scale Rating (1 to 10), Open Ended) # print(item.name) hasAppended = False ## CHECK FOR STRONGLY AGREE/DISAGREE if len(dataArray) <= 5 and any( elem in agreearray for elem in dataArray.keys()): hasAppended = True # print("SA/SD") toggle_states.append([ 'normal', 'down', 'normal', 'normal' ]) # Strongly Agree/Disagree Question directstate.append("Strongly Agree/Disagree") ## CHECK FOR SCALE RATING elif len(dataArray) <= 10: isValidQuestion = True for value in dataArray: try: x = 0 for i in range(10): x += 1 if not (int(value) > 0 and int(value) <= 10): isValidQuestion = False raise TypeError() except: if x < 9: break # Data is not valid type else: pass if isValidQuestion: hasAppended = True # print("SCALER") toggle_states.append( ['normal', 'normal', 'down', 'normal']) # Scale Rating Question directstate.append( "Scale Rating (1 to 10)") ## CHECK FOR MULTIPLE CHOICE if hasAppended == False: if len(dataArray) <= 4: # print("MCQ") toggle_states.append( ['down', 'normal', 'normal', 'normal']) # Multiple Choice Question directstate.append("Multiple-Choice") ## CHECK FOR OPEN ENDED else: # print("OE") toggle_states.append( ['normal', 'normal', 'normal', 'down']) # Open Ended Question directstate.append("Open Ended") # CHANGE SCREEN self.manager.current = "second" self.err.color = [1, .8, .8, 0] #Window.size = (1000, 800)#set window size # Error Handling except Error as e: self.err.text = str(e) self.err.color = [1, .8, .8, 1] # Make error text visible Window.left = 420 Window.top = 250 except Exception: print("Something went wrong, this is the error") traceback.print_exc() btn.bind(on_press=on_button) def reload_spinner(instance): self.spinner.text = "Select File" cwd = os.getcwd() # Get Current Working Directory (CWD) self.files = [] for f in listdir(cwd): if isfile(join(cwd, f)): # Check if File Extension is ".csv" (Is it a csv file?) if (f.replace(" ", "")[-4:] == ".csv"): self.files.append(f) # If .csv files are not found in directory, display error if (len(self.files) == 0): self.files = ["No .csv files found in directory"] # Truncate all values that exceed spinner, display new values self.modfiles = self.files[::] # Create new instance of files called "modfiles" for i, item in enumerate(self.modfiles): if (len(item) > 40): self.modfiles[i] = item[:40] + "..." # print(self.modfiles) self.spinner.values = set(self.modfiles) reload_btn.bind(on_press=reload_spinner) ## Add widgets to screen ## Fl.add_widget(btn) Fl.add_widget(self.spinner) Fl.add_widget(l) Fl.add_widget(reload_btn) Fl.add_widget(self.err) self.add_widget(Fl)
class WelcomeScreen(Screen): def __init__(self, **kwargs): super(WelcomeScreen, self).__init__( **kwargs) #initialise the attributes of the parent class self.layout = FloatLayout( on_touch_down=self.nextscreen) #touch screen to go to next screen self.add_widget(self.layout) background = Image(source='icons/background1.jpg') ml = MyLabel(text='Laundry Pool', font_size=70, pos_hint={ 'center_x': 0.33, 'center_y': 0.75 }) self.sl = MyLabel(text='<touch screen to start>', font_size=20, pos_hint={ 'center_x': 0.33, 'center_y': 0.6 }) self.close = MyLabel( text='', font_size=30, pos_hint={ 'center_x': 0.33, 'center_y': 0.5 } ) #tells user to close an open laundry door if any door is left open self.layout.add_widget(background) self.layout.add_widget(ml) self.layout.add_widget(self.sl) self.layout.add_widget(self.close) def on_pre_enter(self): resetVar() Clock.schedule_interval(self.checks, 10) #runes check every 10 seconds Clock.schedule_interval( self.flash, 1) #flashes the label <touch screen to start> every second def on_pre_leave(self): Clock.unschedule(self.checks) Clock.unschedule(self.flash) def nextscreen(self, *args): #function to go to next screen self.manager.current = 'washorcollect' def checks( self, instance ): #checks if all doors are closed (if not, go to the close door screen) and checks if pooling time does not exceed timeOut (start wash once exceeds) if getWash(timeOut) != None: putState(getWash(timeOut), state=-1) if getDoor() != None: return self.door(instance) else: return self.closed(instance) def flash(self, instance): if self.sl.color == [0, 0, 0, 0]: #if transparent, make it opaque self.sl.color = (0, 0, 0, 1) else: self.sl.color = (0, 0, 0, 0) #last digit 0 makes it transparent def door(self, instance): Clock.unschedule( self.flash ) #if door is not closed, stoped flashing <touch screen to start> and hides it self.sl.color = (0, 0, 0, 0) self.close.text = 'Please close the door of\nWashing Machine %d' % ( getDoor()) #displays which washing machine's door to close self.layout.on_touch_down = self.closed def closed(self, instance): Clock.schedule_interval( self.flash, 1) #once door is closed, retarts flashing <touch screen to start> self.close.text = '' self.layout.on_touch_down = self.nextscreen
def finalize(self, *args): """Add my tabs""" if not self.canvas: Clock.schedule_once(self.finalize, 0) return deck_builder_kwargs = { 'pos_hint': { 'x': 0, 'y': 0 }, 'starting_pos_hint': { 'x': 0.05, 'top': 0.95 }, 'card_size_hint': (0.3, 0.4), 'card_hint_step': (0, -0.1), 'deck_x_hint_step': 0.4 } self._tabs = TabbedPanel(size=self.size, pos=self.pos, do_default_tab=False) self.bind(size=self._tabs.setter('size'), pos=self._tabs.setter('pos')) self.add_widget(self._tabs) for functyp in 'trigger', 'prereq', 'action': tab = TabbedPanelItem(text=functyp.capitalize()) setattr(self, '_{}_tab'.format(functyp), tab) self._tabs.add_widget(getattr(self, '_{}_tab'.format(functyp))) builder = DeckBuilderView(**deck_builder_kwargs) setattr(self, '_{}_builder'.format(functyp), builder) builder.bind( decks=getattr(self, '_trigger_push_{}s'.format(functyp))) scroll_left = DeckBuilderScrollBar(size_hint_x=0.01, pos_hint={ 'x': 0, 'y': 0 }, deckbuilder=builder, deckidx=0, scroll_min=0) setattr(self, '_scroll_left_' + functyp, scroll_left) scroll_right = DeckBuilderScrollBar(size_hint_x=0.01, pos_hint={ 'right': 1, 'y': 0 }, deckbuilder=builder, deckidx=1, scroll_min=0) setattr(self, '_scroll_right_' + functyp, scroll_right) layout = FloatLayout() setattr(self, '_{}_layout'.format(functyp), layout) tab.add_widget(layout) layout.add_widget(builder) layout.add_widget(scroll_left) layout.add_widget(scroll_right) layout.add_widget( Label(text='Used', pos_hint={ 'center_x': 0.1, 'center_y': 0.98 }, size_hint=(None, None))) layout.add_widget( Label(text='Unused', pos_hint={ 'center_x': 0.5, 'center_y': 0.98 }, size_hint=(None, None))) self.bind(rule=getattr(self, '_trigger_pull_{}s'.format(functyp)))
def fire_popup(self, name, question_type): ## Set Button Selected ## for item in questioninfo: if str(item.name) == str(name): global selectedButton selectedButton = item if selectedButton.type == "Open Ended": self.array = [ "Sentiment Data", "Pie Chart", "Bar Chart", "Anomalies" ] else: self.array = [ "Statistics", "Pie Chart", "Bar Chart", "Anomalies" ] ## Creates popup widget ## self.current_segement = globals()[self.array[0].replace(" ", "_")]() pops = MyPopup() if (len(name) > 105): # Check if name is more than 2 lines pops.title = name[:105] + "..." # Truncate name else: pops.title = name pops.title_size = 40 ## Create UI Elements ## # Creating Floatlayout Fl = FloatLayout() Bl = BoxLayout(size_hint_y=None, size_hint_x=.95, height="30dp", pos_hint={ 'center_y': .95, 'center_x': .5 }) # Toggle button events def change_type(name, foo): # Unloads previous tab and load new tab plt.close() # Close mathplot figure Fl.remove_widget(self.current_segement) self.current_segement = globals()[name.replace(" ", "_")]() Fl.add_widget(self.current_segement) Fl.remove_widget(btn) Fl.add_widget(btn) # Setup toggle buttons toggle_arra = [] for i in self.array: Tb = ToggleButton(text=i, group="joshua", state="normal", allow_no_selection=False) Tb.bind(on_release=partial(change_type, i)) toggle_arra.append(Tb) Bl.add_widget(Tb) toggle_arra[ 0].state = "down" # Set first toggle button to be default selected # "Dismiss" button btn = Button(text='Dismiss', size_hint=(.2, .1), background_color=(.3, .6, .7, 1), pos_hint={ 'center_y': 0.05, 'center_x': .5 }, on_press=lambda *args: pops.dismiss()) ## Add Widgets to Popup ## Fl.add_widget(self.current_segement) Fl.add_widget(Bl) Fl.add_widget(btn) pops.add_widget(Fl) pops.open()
def build(self): # creates a float layout root = FloatLayout(size=(1920,1080), pos = (0,0)) # Creates a scatter widget scatter = Scatter() # Creates an image widget root_image = Image(source='Bottom_Screen1.jpeg', size_hint_x=None, width=1920, size_hint_y=None, height=1080, allow_stretch = True, keep_ratio = True) root.add_widget(root_image) # Creates a MyKnob object knob1 = MyKnob(size = (300, 300), min = 0, max = 360, step = 1, show_marker = True, knobimg_source = "img/knob_metal.png", marker_img = "img/bline.png", markeroff_color = (0.3, 0.3, .3, 1), pattern_id= 99, #(ids 1 to 8, or 99 for no id) debug = False, obj = scatter) # Passes the object to the knob knob2 = MyKnob(size = (300, 300), min = 0, max = 360, step = 1, show_marker = True, knobimg_source = "img/knob_metal.png", marker_img = "img/bline.png", markeroff_color = (0.3, 0.3, .3, 1), pattern_id= 99, #(ids 1 to 8, or 99 for no id) debug = False, obj = scatter) # Passes the object to the knob knob3 = MyKnob(size = (300, 300), min = 0, max = 360, step = 1, show_marker = True, knobimg_source = "img/knob_metal.png", marker_img = "img/bline.png", markeroff_color = (0.3, 0.3, .3, 1), pattern_id= 99, #(ids 1 to 8, or 99 for no id) debug = False, obj = scatter) # Passes the object to the knob knob4 = MyKnob(size = (300, 300), min = 0, max = 360, step = 1, show_marker = True, knobimg_source = "img/knob_metal.png", marker_img = "img/bline.png", markeroff_color = (0.3, 0.3, .3, 1), pattern_id= 99, #(ids 1 to 8, or 99 for no id) debug = False, obj = scatter) # Passes the object to the knob widget1 = RelativeLayout(size_hint = (None, None), size = (300,300), pos = (100,0)) widget1.add_widget(knob1) widget2 = RelativeLayout(size_hint = (None, None), size = (300,300), pos = (580,0)) widget2.add_widget(knob2) widget3 = RelativeLayout(size_hint = (None, None), size = (300,300), pos = (1050,0)) widget3.add_widget(knob3) widget4 = RelativeLayout(size_hint = (None, None), size = (300,300), pos = (1530,0)) widget4.add_widget(knob4) # Adds knob to the root root.add_widget(widget1) root.add_widget(widget2) root.add_widget(widget3) root.add_widget(widget4) return root
def select_volume(self, obj): choose_volume_layout = FloatLayout() volumes = win32api.GetLogicalDriveStrings() volumes = volumes.split('\000')[:-1] for i, element in enumerate(volumes): volumes[i] = element.replace('/', '') dropdown = DropDown() for i in range(len(volumes)): # When adding widgets, we need to specify the height manually # (disabling the size_hint_y) so the dropdown can calculate # the area it needs. btn = Button(text=volumes[i], size_hint_y=None, height=20) # for each button, attach a callback that will call the select() method # on the dropdown. We'll pass the text of the button as the data of the # selection. btn.bind(on_release=lambda btn: dropdown.select(btn.text)) # then add the button inside the dropdown dropdown.add_widget(btn) # create a big main button main_button = Button(text='Choose the Volume', size_hint=(.7, .3), pos_hint={ 'center_x': .5, 'center_y': .7 }) # show the dropdown menu when the main button is released # note: all the bind() calls pass the instance of the caller (here, the # mainbutton instance) as the first argument of the callback (here, # dropdown.open.). main_button.bind(on_release=dropdown.open) # one last thing, listen for the selection in the dropdown list and # assign the data to the button text. dropdown.bind( on_select=lambda instance, x: setattr(main_button, 'text', x)) connect_btn = Button(text="Confirm selection", size_hint=(.7, .3), pos_hint={ 'center_x': .5, 'center_y': .3 }) choose_volume_layout.add_widget(main_button) choose_volume_layout.add_widget(connect_btn) popup_volume = Popup(title='Volume chooser', content=choose_volume_layout, size_hint=(None, None), size=(300, 200)) popup_volume.open() # Attach close button press with popup.dismiss action connect_btn.bind(on_release=lambda info: self.connect_to_folder( volume=main_button.text))
return animation def __repr__(self): result = super().__repr__() if hasattr(self, "_card"): result += str(self._card) return result if __name__ == "__main__": def toggle_visible(clicked_card_widget: CardWidget): animation = clicked_card_widget.get_flip_animation(0.5, True) animation.start(clicked_card_widget) float_layout = FloatLayout() float_layout.size = 1000, 1000 deck = Card.get_all_cards() random.shuffle(deck) for _card in deck: card_widget = CardWidget(_card) card_widget.size = 240, 370 card_widget.grayed_out = random.random() > 0.5 card_widget.pos = random.randint(100, 900), random.randint(100, 900) card_widget.rotation = random.randint(0, 180) card_widget.bind(on_double_tap=toggle_visible) float_layout.add_widget(card_widget) runTouchApp(float_layout)
class MainWindow(Screen): total = 0 tax_rate = 1.093 current_item = None current_time = None order_list = [] order_count = 1 order_list_details = {} order_list_times = [] order_list_times_past = [] live_orders_timed = [] time = [] order_database = {} order_database_dates = {} vendor = False menu_dict = {'All-Veg Sampler': 9.25, 'Alumutter': 8} menu_dict_vendor = {'All-Veg Sampler': 7, 'Alumutter': 6} def __init__(self, **kwargs): super(MainWindow, self).__init__(**kwargs) self.background = FloatLayout() self.callDatabase() with self.canvas: Color(0.2, 0.2, 0.28) Rectangle(size=(Window.width**2, Window.height**2)) # Color(1, 0, 0, .5, mode='rgba') # Rectangle(pos=self.pos, size=(210,210)) # Color(0.2, 0.2, 0.28) # Rectangle(pos=self.pos, size=(200,200)) # Food labels self.lbl_curry = Label(pos_hint={ "x": 0.11, "y": 0.92 }, size_hint=[0.1, 0.08], font_size=20, color=[1, 0.5, 0, 1], text="[b]Curry[/b]", markup=True) # Menu food item buttons self.btn_allveg = Button(pos_hint={ "x": 0.01, "y": 0.85 }, size_hint=[0.15, 0.08], text="Chicken", background_color=[1.6, 0.7, 0, 3], on_release=self.pressed) self.btn_allveg = Button(pos_hint={ "x": 0.01, "y": 0.85 }, size_hint=[0.15, 0.08], text="All-Veg Sampler", background_color=[1.6, 0.7, 0, 3], on_release=self.pressed) self.btn_allveg = Button(pos_hint={ "x": 0.01, "y": 0.85 }, size_hint=[0.15, 0.08], text="All-Veg Sampler", background_color=[1.6, 0.7, 0, 3], on_release=self.pressed) self.btn_allveg = Button(pos_hint={ "x": 0.01, "y": 0.85 }, size_hint=[0.15, 0.08], text="All-Veg Sampler", background_color=[1.6, 0.7, 0, 3], on_release=self.pressed) self.btn_allveg = Button(pos_hint={ "x": 0.01, "y": 0.85 }, size_hint=[0.15, 0.08], text="All-Veg Sampler", background_color=[1.6, 0.7, 0, 3], on_release=self.pressed) self.btn_allveg = Button(pos_hint={ "x": 0.01, "y": 0.85 }, size_hint=[0.15, 0.08], text="All-Veg Sampler", background_color=[1.6, 0.7, 0, 3], on_release=self.pressed) self.btn_allveg = Button(pos_hint={ "x": 0.01, "y": 0.85 }, size_hint=[0.15, 0.08], text="All-Veg Sampler", background_color=[1.6, 0.7, 0, 3], on_release=self.pressed) self.btn_allveg = Button(pos_hint={ "x": 0.01, "y": 0.85 }, size_hint=[0.15, 0.08], text="All-Veg Sampler", background_color=[1.6, 0.7, 0, 3], on_release=self.pressed) self.btn_alumutter = Button(pos_hint={ "x": 0.16, "y": 0.85 }, size_hint=[0.15, 0.08], text="Alumutter", background_color=[1.6, 0.7, 0, 3], on_release=self.pressed) # Other non-food panels of GUI self.lbl_subtotal = Label(pos_hint={ "x": 0.48, "y": 0.3 }, size_hint=[0.8, 0.2], font_size=15, color=[0.4, 0.4, 0.6], text=f"Subtotal: ${self.total}", markup=True) self.lbl_tax = Label(pos_hint={ "x": 0.48, "y": 0.27 }, size_hint=[0.8, 0.2], font_size=15, color=[0.4, 0.4, 0.6], text=f"Tax: ${self.total}", markup=True) self.lbl_total = Label(pos_hint={ "x": 0.48, "y": 0.23 }, size_hint=[0.8, 0.2], font_size=25, color=[0.6, 0.6, 0.8], text=f"Total: ${self.total}", markup=True) self.btn_complete = Button(pos_hint={ "x": 0.78, "y": 0.2 }, size_hint=[0.2, 0.1], text="Complete Order", background_color=[0.6, 0.5, 0.9, 3], on_release=self.submitOrder) self.btn_cancel = Button(pos_hint={ "x": 0.914, "y": 0.118 }, size_hint=[0.0666, 0.08], text="Cancel\n Order", background_color=[1.3, 0.3, 0.3, 3], font_size=14, on_release=self.cancelOrderPopup) self.btn_vendor = Button(pos_hint={ "x": 0.847, "y": 0.118 }, size_hint=[0.0666, 0.08], text="Vendor", background_color=[0.2, 0.5, 0.9, 3], font_size=14, on_release=self.vendorCheck) self.btn_to_go = Button(pos_hint={ "x": 0.78, "y": 0.118 }, size_hint=[0.0666, 0.08], text="To-Go", background_color=[0.4, 0.8, 0.4, 3], font_size=14, on_release=self.toGo) self.txt_name = TextInput(pos_hint={ "x": 0.7805, "y": 0.062 }, size_hint=[0.2, 0.055], text='', background_color=[0.1, 0.45, 0.45, 3], multiline=False, halign='center', hint_text='Customer Name', hint_text_color=[0.8, 0.8, 0.8, 1]) self.btn_orders = Button(pos_hint={ "right": 1, "top": 1 }, size_hint=[0.03, 1], text="", background_color=[0.8, 0.8, 1, 0.02], on_release=self.changeWindow, markup=True) # Instantiate the GUI self.addWidgets(self.btn_orders, self.lbl_curry, self.btn_allveg, self.btn_alumutter, self.lbl_subtotal, self.lbl_tax, self.btn_to_go, self.txt_name, self.lbl_total, self.btn_cancel, self.btn_complete, self.btn_vendor) self.add_widget(self.background) # Popup for order cancellation confirmation self.popup_cancel_grid = GridLayout(cols=1, spacing=20, size_hint=(1, 0.95), size=(Window.width, Window.height)) self.popup_cancel = Popup(title='Confirmation', title_align='center', content=self.popup_cancel_grid, pos_hint={ 'x': 0.75, 'y': 0.03 }, size_hint=(0.23, 0.33), size=(Window.width, Window.height)) self.popup_cancel_grid.add_widget( Label(text='Are you sure you want \nto cancel this order?')) self.popup_cancel_grid.add_widget( Button(text='No', size=(100, 100), text_size=(Window.width / 5.5, Window.height), halign='center', valign='center', on_release=self.popup_cancel.dismiss, background_color=[0, 1.4, 1.45, 3])) self.popup_cancel_grid.add_widget( Button(text='Yes', size=(100, 100), text_size=(Window.width / 5.5, Window.height), halign='center', valign='center', on_release=self.popup_cancel.dismiss, on_press=self.resetOrder, background_color=[1.3, 0.2, 0.2, 3])) # Scroll window to list the current items self.scroll_grid = GridLayout(cols=1, spacing=0, size_hint_y=None, size_hint_x=self.background.height / self.background.width) self.scroll_grid.bind(minimum_height=self.scroll_grid.setter('height')) self.scroll = ScrollView(size_hint=[0.159, 0.525], pos_hint={ 'x': 0.82, 'y': 0.45 }) self.scroll_btn = None # Popup window shown when an item in the scroll view is indicated self.popup_grid = GridLayout(cols=1, spacing=20, size_hint=(1, 0.95), pos_hint={'bottom': 0.2}, size=(Window.width, Window.height)) self.popup_grid_top = GridLayout(cols=2, spacing=20, size_hint=(1, 1), pos_hint={'top': 0.95}, size=(Window.width, Window.height)) self.popup_btn_delete = Button(text='Text', size=(100, 100), text_size=(Window.width / 5.5, Window.height), halign='center', valign='center', on_release=self.removeItem, background_color=[0.9, 0.2, 0.2, 3]) self.popup_btn_to_go = Button(text='Text', size=(100, 100), text_size=(Window.width / 5.5, Window.height), halign='center', valign='center', on_release=self.toGo, background_color=[0.4, 0.8, 0.4, 3]) self.popup_btn_no_cilantro = Button( text='No Cilantro', size=(100, 100), text_size=(Window.width / 5.5, Window.height), halign='center', valign='center', on_release=self.cilantroMod, background_color=[0.3, 1.4, 1.4, 3]) self.popup_btn_extra_cilantro = Button( text='Extra Cilantro', size=(100, 100), text_size=(Window.width / 5.5, Window.height), halign='center', valign='center', on_release=self.cilantroMod, background_color=[0.3, 1.4, 1.4, 3]) self.popup_txt = TextInput(size_hint=[1, 0.4], text='', background_color=[0.4, 0.3, 0.6, 3], multiline=False, halign='center', font_size=18, padding_y=33, hint_text='Enter Order Details', hint_text_color=[0.8, 0.8, 0.8, 1]) self.popup_grid_top.add_widget(self.popup_btn_delete) self.popup_grid_top.add_widget(self.popup_btn_to_go) self.popup_grid_top.add_widget(self.popup_btn_no_cilantro) self.popup_grid_top.add_widget(self.popup_btn_extra_cilantro) self.popup_grid.add_widget(self.popup_grid_top) self.popup_grid.add_widget(self.popup_txt) self.popup = Popup(title='Title', title_align='center', content=self.popup_grid, on_dismiss=self.addDetails, size_hint=(0.45, 0.7), size=(Window.width, Window.height)) self.button_id = None self.data = None self.data_backups = [] self.client_socket = None try: threading.Thread(target=self.connectSocket).start() except Exception as e: print(f'Error: {e}') def connectSocket(self, instance=None): host = '0.0.0.0' port = 8912 address = (host, port) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(address) server.listen(5) print( f'Listening on {socket.gethostbyname(socket.gethostname())}:{port}' ) while True: conn, addr = server.accept() print(f"Connection from {address} has been established.") self.client_socket = conn while True: time.sleep(0.5) try: conn.send('B=G#J4>m$p'.encode()) except ConnectionResetError: print('Connection with client lost.') break def generateCurOrder(self): self.scroll_btn = Button(text=f"{self.order_list[-1].food}", font_size=11, size_hint_y=None, height=33, background_color=[0.7, 0.7, 1, 1], on_release=self.popupItem) self.scroll_grid.add_widget(self.scroll_btn) if len(self.scroll.children) == 0: self.scroll.add_widget(self.scroll_grid) self.background.add_widget(self.scroll) # def duplicateItem(self, instance): //-- Decided not to use this stuff but I'll keep it here # //-- in case I change my mind later. # for i in range(self.popup_slider.value): # self.scroll_btn = Button(text=f"{self.order_list[self.order_list.index(self.button_id.text)]}", # font_size=12, size_hint_y=None, height=33, # background_color=[0.7, 0.7, 1, 1], on_release=self.popupItem) # self.scroll_grid.add_widget(self.scroll_btn) # self.order_list.append(self.button_id.text) # self.addTotal(self.menu_dict[self.button_id.text]) # # def updateSlider(self, instance, touch): # if self.popup_slider.value == 1: # self.popup_slider_btn.text = f"Duplicate this item {int(self.popup_slider.value)} time" # else: # self.popup_slider_btn.text = f"Duplicate this item {int(self.popup_slider.value)} times" # # self.popup_slider = Slider(min=1, max=10, value=1, step=1, value_track=True, # value_track_color=[0.4, 0.4, 0.6, 1], # on_touch_move=self.updateSlider) # # self.popup_slider_btn = Button(font_size=20, background_color=[0.7, 0.7, 1, 1], on_release=self.duplicateItem, # text=f"Duplicate this item {int(self.popup_slider.value)} time", markup=True) # # self.popup_grid.add_widget(self.popup_slider) # self.popup_grid.add_widget(self.popup_slider_btn) def addTotal(self, x): self.total += x subtotal = format(self.total, '.2f') tax = format((self.total * self.tax_rate) - self.total, '.2f') total = format(float(subtotal) + float(tax), '.2f') self.lbl_subtotal.text = f"Subtotal: ${subtotal}" self.lbl_tax.text = f"Tax: ${tax}" self.lbl_total.text = f"Total: ${total}" def addList(self): self.current_item.time = str(datetime.datetime.now())[:19][11:-3] self.order_list.append(self.current_item) screen_third.generateCurOrders() def addDetails(self, instance=None): if self.popup_txt.text != '': num = 1 rev = [] for child in self.scroll_grid.children: rev.append(child) rev.reverse() for i in range(len(rev)): if rev[i] == self.button_id: break else: num += 1 for i in range(len(self.order_list)): if self.order_list[i].food == self.button_id.text: if self.order_list[i].order_id == num: self.order_list[ i].details = f"({self.popup_txt.text}) " break screen_third.generateCurOrders() def submitOrder(self, instance=None): if len(self.order_list) > 0: self.live_orders_timed = [self.order_list.copy()] self.order_database[len(self.order_database)] = f"{str(datetime.datetime.now())[:19]} - " \ f"{[x.food for x in self.live_orders_timed[-1]]}" with open('database.txt', 'a') as db: db.write( f"{str(datetime.datetime.now())[:19]} - {[x.food for x in self.live_orders_timed[-1]]} - " f"${format((self.total * self.tax_rate), '.2f')}\n") self.data = [x for x in self.order_list] msg = pickle.dumps(self.data) try: if len(self.data_backups) > 0: self.client_socket.send(pickle.dumps(self.data_backups)) self.data_backups.clear() print('<INFO> Backups sent to client.') self.client_socket.send(msg) except Exception as e: if ['BACKUP'] not in self.data_backups: self.data_backups.append(['BACKUP']) self.data_backups.append([x.food for x in self.order_list]) print( f'<ERROR> No connection with client. Backup data created.\n{e}' ) screen_third.generatePastOrders() self.resetOrder() screen_third.scroll_grid.remove_widget(screen_third.div) def cancelOrderPopup(self, instance=None): if len(self.order_list) > 0: self.popup_cancel.open() def resetOrder(self, instance=None): self.total = 0 self.current_item = OrderItem(order_id=0) self.order_list.clear() self.lbl_subtotal.text = f"Subtotal: ${self.total}" self.lbl_tax.text = f"Tax: ${self.total}" self.lbl_total.text = f"Total: ${self.total}" self.scroll_grid.clear_widgets() self.txt_name.text = '' self.order_count = 1 self.background.remove_widget(self.btn_to_go) self.btn_to_go = Button(pos_hint={ "x": 0.78, "y": 0.118 }, size_hint=[0.0666, 0.08], text="To-Go", background_color=[0.4, 0.8, 0.4, 3], font_size=14, on_release=self.toGo) self.addWidgets(self.btn_to_go) screen_third.cancelOrder() @staticmethod def changeWindow(instance): sm.current = 'tertiary' sm.transition.direction = 'left' def callDatabase(self): # This is always called with __init__ count = 0 with open('database.txt', 'r') as db: for line in db: self.time.append(f"{line[:19]}") self.order_database[count] = line[:-1] self.order_database_dates[line[:10]] = None count += 1 self.order_database_dates = [key for key in self.order_database_dates] def popupItem(self, instance): self.button_id = instance num = 1 rev = [] for child in self.scroll_grid.children: rev.append(child) rev.reverse() for i in range(len(rev)): if rev[i] == self.button_id: break else: num += 1 for i in range(len(self.order_list)): if self.order_list[i].food == self.button_id.text: if self.order_list[i].order_id == num: self.popup_txt.text = self.order_list[i].details[1:-2] break self.popup.title = f'Options for selected item - {instance.text}' self.popup_btn_delete.text = f"Remove this '{instance.text}' from the order." if "TO-GO" not in instance.text: self.popup_btn_to_go.text = f"Make this order to-go." else: self.popup_btn_to_go.text = f"Make this '{instance.text[:-6]}' for here." self.popup.open() def vendorCheck(self, instance=None): if self.vendor: self.vendor = False instance.background_normal = 'atlas://data/images/defaulttheme/button' self.vendorGen() else: self.vendor = True instance.background_normal = 'atlas://data/images/defaulttheme/button_pressed' self.vendorGen() def vendorGen(self, instance=None): self.total = 0 if self.vendor: for item in self.order_list: self.addTotal(self.menu_dict_vendor[item.food]) else: for item in self.order_list: self.addTotal(self.menu_dict[item.food]) def cilantroMod(self, instance=None): if instance.text == 'No Cilantro': if self.popup_txt.text != '' and 'Cilantro' not in self.popup_txt.text: self.popup_txt.text = f"{self.popup_txt.text}, No Cilantro" elif 'No Cilantro' in self.popup_txt.text: pass elif ', Extra Cilantro' in self.popup_txt.text: self.popup_txt.text = f"{self.popup_txt.text.split(',')[0]}, No Cilantro" else: self.popup_txt.text = 'No Cilantro' else: if self.popup_txt.text != '' and 'Cilantro' not in self.popup_txt.text: self.popup_txt.text = f"{self.popup_txt.text}, Extra Cilantro" elif 'Extra Cilantro' in self.popup_txt.text: pass elif ', No Cilantro' in self.popup_txt.text: self.popup_txt.text = f"{self.popup_txt.text.split(',')[0]}, Extra Cilantro" else: self.popup_txt.text = 'Extra Cilantro' # def toGo(self, instance=None): # # if "TO-GO" not in self.button_id.text: # i = self.order_list.index(self.button_id.text) # self.button_id.text = f"{self.order_list[i]} TO-GO" # self.order_list[i] = f"{self.order_list[i]} [b]|| [u]TO-GO[/u] ||[/b]" # screen_third.generateCurOrders() # else: # self.button_id.text = self.button_id.text[:-6] # screen_third.generateCurOrders() # for i in range(len(self.order_list)): # if "TO-GO[/u] ||[/b]" in self.order_list[i] and self.button_id.text in self.order_list[i]: # self.order_list[i] = self.order_list[i][:-26] # break # # screen_third.generateCurOrders() # # self.popup.dismiss() def toGo(self, instance=None): if len(self.order_list) > 0: for i in range(len(self.order_list)): self.order_list[i].to_go = ' [b][u]TO-GO[/u][/b]' self.background.remove_widget(self.btn_to_go) self.btn_to_go = Button( pos_hint={ "x": 0.78, "y": 0.118 }, size_hint=[0.0666, 0.08], text="To-Go", background_color=[0.4, 0.8, 0.4, 3], font_size=14, on_release=self.forHere, background_normal= 'atlas://data/images/defaulttheme/button_pressed') self.addWidgets(self.btn_to_go) screen_third.generateCurOrders() def forHere(self, instance=None): if len(self.order_list) > 0: for i in range(len(self.order_list)): self.order_list[i].to_go = '' self.background.remove_widget(self.btn_to_go) self.btn_to_go = Button( pos_hint={ "x": 0.78, "y": 0.118 }, size_hint=[0.0666, 0.08], text="To-Go", background_color=[0.4, 0.8, 0.4, 3], font_size=14, on_release=self.toGo, background_normal='atlas://data/images/defaulttheme/button') self.addWidgets(self.btn_to_go) screen_third.generateCurOrders() def removeItem(self, instance): count = 0 for i in range(len(self.scroll_grid.children)): if self.scroll_grid.children[i] != self.button_id: count += 1 else: break self.order_list.remove(self.order_list[count]) if self.vendor: self.addTotal(-self.menu_dict_vendor[self.button_id.text]) else: self.addTotal(-self.menu_dict[self.button_id.text]) self.scroll_grid.remove_widget(self.button_id) self.popup.dismiss() self.order_count -= 1 screen_third.generateCurOrders() if len(self.order_list) == 0: self.resetOrder() screen_third.scroll_grid.remove_widget(screen_third.div) def addWidgets(self, *args): for i in args: self.background.add_widget(i) def pressed(self, instance): self.current_item = OrderItem(order_id=self.order_count, food=instance.text) self.order_count += 1 self.addList() self.vendorGen() self.generateCurOrder()
def createWidgets(self): list = ScrollView() layoutList = GridLayout(cols=1, size_hint_y=None, spacing=5) layoutList.bind(minimum_height=layoutList.setter('height')) self.nameInput = TextInput( size_hint=[.8, 1], pos_hint={ "center_x": .5, "y": 0 }, width=200, background_normal="images/backLayout.png", background_active="images/backLayout.png", multiline=False, foreground_color=COLOR["LIGHT"]["MAIN_COLOR"], hint_text="Название", hint_text_color=COLOR["LIGHT"]["MAIN_COLOR"]) self.description = TextInput( size_hint=[.8, 1], pos_hint={ "center_x": .5, "y": 0 }, width=200, background_normal="images/backLayout.png", background_active="images/backLayout.png", foreground_color=COLOR["LIGHT"]["MAIN_COLOR"], hint_text="Описание", hint_text_color=COLOR["LIGHT"]["MAIN_COLOR"]) nameLayout = FloatLayout(size_hint=[1, None], height=50, pos_hint={ "center_x": .5, "Y": 0 }) nameLayout.add_widget(self.nameInput) descriptionLayout = FloatLayout(size_hint=[1, None], height=100) descriptionLayout.add_widget(self.description) self.deadLine = check("Срочность", "dead") addImages = FloatLayout(size_hint=[1, None], height=50) addImages.add_widget(addImage()) checkCategoryF = FloatLayout(size_hint=[1, None], height=30) self.checkCategory = Button(text="Выберете категорию", background_normal="images/button.png", size_hint=[.9, 1], pos_hint={ "center_x": .5, "y": 0 }, on_press=self.openChooseType) checkCategoryF.add_widget(self.checkCategory) endButtons = FloatLayout(size_hint=[.7, None], height=75) okButton = Button(size_hint=[.5, None], height=30, background_normal="images/button.png", text="Пртвердиь", pos_hint={ "center_x": .5, "top": 1 }, on_press=self.addPost) noButton = Button(size_hint=[.3, None], height=35, background_normal="images/button.png", text="Отмена", pos_hint={ "center_x": .5, "y": 0 }, on_press=self.clearActivity) self.important = check("Важность", "imp") endButtons.add_widget(okButton) endButtons.add_widget(noButton) layoutList.add_widget(nameLayout) layoutList.add_widget(descriptionLayout) layoutList.add_widget(self.deadLine) layoutList.add_widget(self.important) layoutList.add_widget(addImages) layoutList.add_widget(Widget(size_hint=[1, None], height=5)) layoutList.add_widget(checkCategoryF) layoutList.add_widget(Widget(size_hint=[1, None], height=40)) layoutList.add_widget(endButtons) list.add_widget(layoutList) self.add_widget(list)
def build(self): tb_panel = TabbedPanel() #tb_panel.do_default_tab = False #building_content= FloatLayout() #th_interval_head = TabbedPanelHeader(text="Interval") #th_interval = FloatLayout() #th_interval.add_widget(date1) #date2=datepicker.DatePicker(size_hint = (0.1,0.1)) #th_interval.add_widget(date2) #th_interval_head.content = th_interval #th_building_head = TabbedPanelHeader(text="Building") #th_building_head.content = building_content graph_content = FloatLayout() StartDate = Label(text='Start Date:', font_size=('19dp'), size_hint=(0.1, 0.1), pos_hint={ "x": 0.21, "top": 1 }) graph_content.add_widget(StartDate) startmonth = TextInput(text='', font_size=('15dp'), multiline=False, pos_hint={ "x": 1, "top": 0.5 }, hint_text="MM", input_filter='int') start_month_area = FloatLayout(size_hint=(0.03, 0.04), pos_hint={ "x": 0.27, "top": 0.99 }) start_month_area.add_widget(startmonth) graph_content.add_widget(start_month_area) slashDate1 = Label(text='/', font_size=('19dp'), size_hint=(0.1, 0.1), pos_hint={ "x": 0.29, "top": 1 }) graph_content.add_widget(slashDate1) startday = TextInput(multiline=False, font_size=('15dp'), hint_text="DD", pos_hint={ "x": 1, "top": 0.5 }, input_filter='float') start_day_area = FloatLayout(size_hint=(0.03, 0.04), pos_hint={ "x": 0.32, "top": .99 }) start_day_area.add_widget(startday) graph_content.add_widget(start_day_area) slashDate2 = Label(text='/', font_size=('19dp'), size_hint=(0.1, 0.1), pos_hint={ "x": 0.34, "top": 1 }) graph_content.add_widget(slashDate2) startyear = TextInput(multiline=False, font_size=('15dp'), hint_text="YYYY", pos_hint={ "x": 1, "top": 0.45 }, input_filter='float') start_year_area = FloatLayout(size_hint=(0.04, 0.04), pos_hint={ "x": 0.36, "top": .992 }) start_year_area.add_widget(startyear) graph_content.add_widget(start_year_area) starthour = TextInput(multiline=False, font_size=('15dp'), hint_text="Hr", pos_hint={ "x": 1, "top": 0.5 }, input_filter='float') start_hour_area = FloatLayout(size_hint=(0.03, 0.04), pos_hint={ "x": 0.44, "top": .99 }) start_hour_area.add_widget(starthour) graph_content.add_widget(start_hour_area) colonDate1 = Label(text=':', font_size=('19dp'), size_hint=(0.1, 0.1), pos_hint={ "x": 0.46, "top": 1 }) graph_content.add_widget(colonDate1) startminute = TextInput(multiline=False, font_size=('15dp'), hint_text="Min", pos_hint={ "x": 1, "top": 0.5 }, input_filter='float') start_minute_area = FloatLayout(size_hint=(0.03, 0.04), pos_hint={ "x": 0.49, "top": .99 }) start_minute_area.add_widget(startminute) graph_content.add_widget(start_minute_area) bt3 = ToggleButton(text='AM', group='time1', size_hint=(0.05, 0.025), pos_hint={ "x": 0.57, "top": 0.974 }) graph_content.add_widget(bt3) bt4 = ToggleButton(text='PM', group='time1', size_hint=(0.05, 0.025), pos_hint={ "x": 0.57, "top": 0.95 }) graph_content.add_widget(bt4) EndDate = Label(text='End Date:', font_size=('19dp'), size_hint=(0.1, 0.1), pos_hint={ "x": 0.21, "top": 0.9 }) graph_content.add_widget(EndDate) endmonth = TextInput(text='', font_size=('15dp'), multiline=False, pos_hint={ "x": 1, "top": 0.5 }, hint_text="MM", input_filter='int') end_month_area = FloatLayout(size_hint=(0.03, 0.04), pos_hint={ "x": 0.27, "top": 0.89 }) end_month_area.add_widget(endmonth) graph_content.add_widget(end_month_area) slashDate3 = Label(text='/', font_size=('19dp'), size_hint=(0.1, 0.1), pos_hint={ "x": 0.29, "top": .9 }) graph_content.add_widget(slashDate3) endday = TextInput(multiline=False, font_size=('15dp'), hint_text="DD", pos_hint={ "x": 1, "top": 0.5 }, input_filter='float') end_day_area = FloatLayout(size_hint=(0.03, 0.04), pos_hint={ "x": 0.32, "top": 0.89 }) end_day_area.add_widget(endday) graph_content.add_widget(end_day_area) slashDate4 = Label(text='/', font_size=('19dp'), size_hint=(0.1, 0.1), pos_hint={ "x": 0.34, "top": .9 }) graph_content.add_widget(slashDate4) endyear = TextInput(multiline=False, font_size=('15dp'), hint_text="YYYY", pos_hint={ "x": 1, "top": 0.5 }, input_filter='float') end_year_area = FloatLayout(size_hint=(0.04, 0.04), pos_hint={ "x": 0.36, "top": 0.89 }) end_year_area.add_widget(endyear) graph_content.add_widget(end_year_area) endhour = TextInput(multiline=False, font_size=('15dp'), hint_text="Hr", pos_hint={ "x": 1, "top": 0.5 }, input_filter='float') end_hour_area = FloatLayout(size_hint=(0.03, 0.04), pos_hint={ "x": 0.44, "top": 0.89 }) end_hour_area.add_widget(endhour) graph_content.add_widget(end_hour_area) colonDate2 = Label(text=':', font_size=('19dp'), size_hint=(0.1, 0.1), pos_hint={ "x": 0.46, "top": 0.9 }) graph_content.add_widget(colonDate2) endminute = TextInput(multiline=False, font_size=('15dp'), hint_text="Min", pos_hint={ "x": 1, "top": 0.5 }, input_filter='float') end_minute_area = FloatLayout(size_hint=(0.03, 0.04), pos_hint={ "x": 0.49, "top": 0.89 }) end_minute_area.add_widget(endminute) graph_content.add_widget(end_minute_area) bt5 = ToggleButton(text='AM', group='time2', size_hint=(0.05, 0.025), pos_hint={ "x": 0.57, "top": 0.874 }) graph_content.add_widget(bt5) bt6 = ToggleButton(text='PM', group='time2', size_hint=(0.05, 0.025), pos_hint={ "x": 0.57, "top": 0.85 }) graph_content.add_widget(bt6) #graph settings midnightButton = ToggleButton(text='Midnight Markers', size_hint=(0.25, 0.05), pos_hint={ "right": 1, "top": 1 }) midnightButton.bind( on_press=lambda x: (graphSettings.ToggleMidnight())) graph_content.add_widget(midnightButton) noonButton = ToggleButton(text='Noon Markers', size_hint=(0.25, 0.05), pos_hint={ "right": 1, "top": .951 }) noonButton.bind(on_press=lambda x: (graphSettings.ToggleNoon())) graph_content.add_widget(noonButton) global ampm1 ampm1 = "AM" #default global ampm2 ampm2 = "AM" #default def ampmSET1(self): ampm1 = "AM" def ampmSET2(self): ampm1 = "PM" def ampmSET3(self): ampm2 = "AM" def ampmSET4(self): ampm2 = "PM" bt3.bind(on_press=ampmSET1) bt4.bind(on_press=ampmSET2) bt5.bind(on_press=ampmSET3) bt6.bind(on_press=ampmSET4) def buttonClicked(self): graph_area = FloatLayout(size_hint=(0.75, 0.8), pos_hint={ "left": 0, "top": 0.9 }) plt.gcf().clear() try: sMonth = int(startmonth.text) sDay = int(startday.text) sYear = int(startyear.text) sHour = int(starthour.text) sMin = int(startminute.text) eMonth = int(endmonth.text) eDay = int(endday.text) eYear = int(endyear.text) eHour = int(endhour.text) eMin = int(endminute.text) if sMonth > 12: sMonth = 12 if sMonth < 0: sMonth = 0 if sMonth in [4, 6, 9, 11]: if sDay > 30: sDay = 30 elif sMonth in [1, 3, 5, 7, 8, 10, 12]: if sDay > 31: sDay = 31 elif sMonth == 2: sDay = 28 if sDay < 0: sDay = 0 if sYear > 2020: sYear = 2020 if sYear < 2000: sYear = 2000 if sHour > 12: sHour = 12 if sHour < 0: sHour = 0 if sMin > 59: sMin = 59 if sMin < 0: sMin = 0 if eMonth > 12: eMonth = 12 if eMonth < 0: eMonth = 0 if eMonth in [4, 6, 9, 11]: if eDay > 30: eDay = 30 elif eMonth in [1, 3, 5, 7, 8, 10, 12]: if eDay > 31: eDay = 31 elif eDay == 2: eDay = 28 if eDay < 0: eDay = 0 if eYear > 2020: eYear = 2020 if eYear < 2000: eYear = 2000 if eHour > 12: eHour = 12 if eHour < 0: eHour = 0 if eMin > 59: eMin = 59 if eMin < 0: eMin = 0 if sHour < 10: sHour = "0" + str(sHour) if sMin < 10: sMin = "0" + str(sMin) if eHour < 10: eHour = "0" + str(eHour) if eMin < 10: eMin = "0" + str(eMin) startinterval = (" " + str(sMonth) + "/" + str(sDay) + "/" + str(sYear) + " " + str(sHour) + ":" + str(sMin) + ":" + "00 " + ampm1) endinterval = (" " + str(eMonth) + "/" + str(eDay) + "/" + str(eYear) + " " + str(eHour) + ":" + str(eMin) + ":" + "00 " + ampm2) database.SetInterval(startinterval, endinterval) except: plt.gcf().clear() graph_area.add_widget( Label(text="No data for given parameters", font_size="30dp", pos_hint={ "x": 0, "y": 0.1 }, color=(1, 0, 0, 1))) graph_content.add_widget(graph_area) return 0 if database.ReadData() == False or len( database.selectedBuildings) == 0: plt.gcf().clear() graph_area.add_widget( Label(text="No data for given parameters", font_size="30dp", pos_hint={ "x": 0, "y": 0.1 }, color=(1, 0, 0, 1))) graph_content.add_widget(graph_area) return 0 #if database has no data return a graph error # Initialize graph after prospects # Loop for grabbing buildings and data points ticks = [] labels = [] timestamps = [] kilowatts = [] for buildingNum in range(0, len(database.buildingsData)): timestamps = [] kilowatts = [] for dataPoint in range( 0, len(database.buildingsData[buildingNum].dataPoints)): timestamps.append( database.SetDateToUnix( database.buildingsData[buildingNum]. dataPoints[dataPoint].timestamp)) kilowatts.append( float(database.buildingsData[buildingNum]. dataPoints[dataPoint].kilowatts)) plt.plot(timestamps, kilowatts, label=str(database.buildingsData[buildingNum].name)) plt.xlabel('Timestamp') plt.ylabel('Kilowatts') plt.legend() #midnight and noon lines if graphSettings.midnight == True: for midnight in timestamps: if (midnight % 86400) == 0: plt.axvline(x=(midnight), linestyle=('--'), color=(0, 0, 0, 1)) #for noon in if graphSettings.noon == True: for noon in timestamps: if (noon % 86400) == 43200: plt.axvline(x=(noon), linestyle=('--'), color=(1, 0, 0, 1)) tickNum = 7 for x in range(0, tickNum): ticks.append( (x * ((database.unixInterval[1] - database.unixInterval[0]) / tickNum) + database.unixInterval[0])) # print(self.ticks[x])#verifies the graph ticks label = database.SetUnixToLabel( (x * ((database.unixInterval[1] - database.unixInterval[0]) / tickNum) + database.unixInterval[0])) labels.append(label) # print(self.labels[x])#verifies the graph tick labels ticks.append(database.unixInterval[1]) labels.append(database.SetUnixToLabel(database.unixInterval[1])) plt.xticks(ticks=ticks, labels=labels, rotation=15) plt.title("Dynamic Kilowatt/hr Graph") plt.grid() graphwidget = FigureCanvasKivyAgg((plt.gcf())) graph_area.add_widget(graphwidget) graph_content.add_widget(graph_area) ok = Button(text="Graph", size_hint=(.2, .2), pos_hint={ "x": 0, "top": 1 }) ok.bind(on_press=buttonClicked) graph_content.add_widget(ok) buildingButtons = [] def createButton(name, index): button = ToggleButton(text=name, size_hint=(0.25, 0.05), pos_hint={ "right": 1, "y": 0.05 * index }) button.bind( on_press=lambda x: (database.ChangeBuilding(index + 1))) graph_content.add_widget(button) for i, val in enumerate(database.buildings): createButton(val, i) #_lgraph_head = TabbedPanelHeader(text='Graphs') #th_lgraph_head.content = graph_content tb_panel.default_tab_content = graph_content tb_panel.default_tab_text = "Graphs" #tb_panel.add_widget(th_interval_head) #tb_panel.add_widget(th_building_head) #tb_panel.add_widget(th_lgraph_head) return tb_panel
def buttonClicked(self): graph_area = FloatLayout(size_hint=(0.75, 0.8), pos_hint={ "left": 0, "top": 0.9 }) plt.gcf().clear() try: sMonth = int(startmonth.text) sDay = int(startday.text) sYear = int(startyear.text) sHour = int(starthour.text) sMin = int(startminute.text) eMonth = int(endmonth.text) eDay = int(endday.text) eYear = int(endyear.text) eHour = int(endhour.text) eMin = int(endminute.text) if sMonth > 12: sMonth = 12 if sMonth < 0: sMonth = 0 if sMonth in [4, 6, 9, 11]: if sDay > 30: sDay = 30 elif sMonth in [1, 3, 5, 7, 8, 10, 12]: if sDay > 31: sDay = 31 elif sMonth == 2: sDay = 28 if sDay < 0: sDay = 0 if sYear > 2020: sYear = 2020 if sYear < 2000: sYear = 2000 if sHour > 12: sHour = 12 if sHour < 0: sHour = 0 if sMin > 59: sMin = 59 if sMin < 0: sMin = 0 if eMonth > 12: eMonth = 12 if eMonth < 0: eMonth = 0 if eMonth in [4, 6, 9, 11]: if eDay > 30: eDay = 30 elif eMonth in [1, 3, 5, 7, 8, 10, 12]: if eDay > 31: eDay = 31 elif eDay == 2: eDay = 28 if eDay < 0: eDay = 0 if eYear > 2020: eYear = 2020 if eYear < 2000: eYear = 2000 if eHour > 12: eHour = 12 if eHour < 0: eHour = 0 if eMin > 59: eMin = 59 if eMin < 0: eMin = 0 if sHour < 10: sHour = "0" + str(sHour) if sMin < 10: sMin = "0" + str(sMin) if eHour < 10: eHour = "0" + str(eHour) if eMin < 10: eMin = "0" + str(eMin) startinterval = (" " + str(sMonth) + "/" + str(sDay) + "/" + str(sYear) + " " + str(sHour) + ":" + str(sMin) + ":" + "00 " + ampm1) endinterval = (" " + str(eMonth) + "/" + str(eDay) + "/" + str(eYear) + " " + str(eHour) + ":" + str(eMin) + ":" + "00 " + ampm2) database.SetInterval(startinterval, endinterval) except: plt.gcf().clear() graph_area.add_widget( Label(text="No data for given parameters", font_size="30dp", pos_hint={ "x": 0, "y": 0.1 }, color=(1, 0, 0, 1))) graph_content.add_widget(graph_area) return 0 if database.ReadData() == False or len( database.selectedBuildings) == 0: plt.gcf().clear() graph_area.add_widget( Label(text="No data for given parameters", font_size="30dp", pos_hint={ "x": 0, "y": 0.1 }, color=(1, 0, 0, 1))) graph_content.add_widget(graph_area) return 0 #if database has no data return a graph error # Initialize graph after prospects # Loop for grabbing buildings and data points ticks = [] labels = [] timestamps = [] kilowatts = [] for buildingNum in range(0, len(database.buildingsData)): timestamps = [] kilowatts = [] for dataPoint in range( 0, len(database.buildingsData[buildingNum].dataPoints)): timestamps.append( database.SetDateToUnix( database.buildingsData[buildingNum]. dataPoints[dataPoint].timestamp)) kilowatts.append( float(database.buildingsData[buildingNum]. dataPoints[dataPoint].kilowatts)) plt.plot(timestamps, kilowatts, label=str(database.buildingsData[buildingNum].name)) plt.xlabel('Timestamp') plt.ylabel('Kilowatts') plt.legend() #midnight and noon lines if graphSettings.midnight == True: for midnight in timestamps: if (midnight % 86400) == 0: plt.axvline(x=(midnight), linestyle=('--'), color=(0, 0, 0, 1)) #for noon in if graphSettings.noon == True: for noon in timestamps: if (noon % 86400) == 43200: plt.axvline(x=(noon), linestyle=('--'), color=(1, 0, 0, 1)) tickNum = 7 for x in range(0, tickNum): ticks.append( (x * ((database.unixInterval[1] - database.unixInterval[0]) / tickNum) + database.unixInterval[0])) # print(self.ticks[x])#verifies the graph ticks label = database.SetUnixToLabel( (x * ((database.unixInterval[1] - database.unixInterval[0]) / tickNum) + database.unixInterval[0])) labels.append(label) # print(self.labels[x])#verifies the graph tick labels ticks.append(database.unixInterval[1]) labels.append(database.SetUnixToLabel(database.unixInterval[1])) plt.xticks(ticks=ticks, labels=labels, rotation=15) plt.title("Dynamic Kilowatt/hr Graph") plt.grid() graphwidget = FigureCanvasKivyAgg((plt.gcf())) graph_area.add_widget(graphwidget) graph_content.add_widget(graph_area)
def build(self): layout = FloatLayout() Window.size = (1000, 1000) player = [] for i in range(9): for j in range(9): if ((not (i == 4 and j == 0)) and (not (i == 4 and j == 8)) and (not (i == 0 and j == 4)) and (not (i == 8 and j == 4))): self.b1 = Button(pos=(75 + i * 100, 75 + j * 100), size_hint=(None, None), size=(75, 75), background_color=(74 / 255, 1 / 255, 76 / 255, 1)) layout.add_widget(self.b1) player.append(self.b1) elif (i == 4 and j == 0): self.b2 = Button(pos=(75 + i * 100, 75 + j * 100), size_hint=(None, None), size=(75, 75), background_color=(1, 1 / 255, 76 / 255, 1)) layout.add_widget(self.b2) player.append(self.b2) elif (i == 4 and j == 8): self.b3 = Button(pos=(75 + i * 100, 75 + j * 100), size_hint=(None, None), size=(75, 75), background_color=(6 / 255, 6 / 255, 173 / 255, 1)) layout.add_widget(self.b3) player.append(self.b3) elif (i == 0 and j == 4): self.b4 = Button(pos=(75 + i * 100, 75 + j * 100), size_hint=(None, None), size=(75, 75), background_color=(249 / 255, 241 / 255, 2 / 255, 1)) layout.add_widget(self.b4) player.append(self.b4) elif (i == 8 and j == 4): self.b5 = Button(pos=(75 + i * 100, 75 + j * 100), size_hint=(None, None), size=(75, 75), background_color=(14 / 255, 249 / 255, 1 / 255, 1)) layout.add_widget(self.b5) player.append(self.b5) self.wallv = [] #amodi for i in range(1, 9): for j in range(9): self.w1 = Button(pos=(75 - 25 + i * 100, 75 + j * 100), size_hint=(None, None), size=(25, 75), background_color=(238 / 255, 177 / 255, 239 / 255, 1)) layout.add_widget(self.w1) self.wallv.append(self.w1) self.wallh = [] #ofoghi for i in range(9): for j in range(1, 9): self.w2 = Button(pos=(75 + i * 100, 75 - 25 + j * 100), size_hint=(None, None), size=(75, 25), background_color=(238 / 255, 177 / 255, 239 / 255, 1)) layout.add_widget(self.w2) self.wallh.append(self.w2) for x in range(len(player)): player[x].bind(on_press=self.callback) for i in range(len(self.wallv)): self.wallv[i].bind(on_press=self.callbackwv) for i in range(len(self.wallh)): self.wallh[i].bind(on_press=self.callbackwh) return layout
class ExportDataWindow(Screen): """ export window class Export data from database to a mounted usb memory device. Args: Screen (Screen): kivy.uix.screenmanager """ btn_export_back = ObjectProperty(None) lbl_export_message = ObjectProperty(None) EXPORTDATA = "" EXPORTFILENAME = 'sucsexport001.csv' DEVICENAME = "" # built-in kivy function: before entering the scan window def on_pre_enter(self, *args): s.APP_STATE = "EXPORT" self.exported = False self.media_pi_devs = [] # return to main window def backButton(self): sm.current = "main" self.exported = False self.lbl_export_message.text = "" # button method safely removes all connected USB devices def ejectButton(self): if self.check_sd_mounted(): output = os.popen(CMD_EJECT_A).read() # eject -v /dev/sd?? print(type(self).__name__, "Output:", output) if output == "": self.lbl_export_message.text = "Storage device safely removed" else: self.lbl_export_message.text = "No device to remove" # return the list of media devices mounted in the /media/pi/ directory def get_media_dev_list(self): output = os.popen(CMD_LS + DIR_MEDIA).read() # ls /media/pi/ self.media_pi_devs = output.split('\n') print(type(self).__name__, "Media Devices:", self.media_pi_devs) if "No such file or directory" in output: print( type(self).__name__, "Error:", CMD_LS + DIR_MEDIA, "No such file or directory") #TODO: Check for more tests #Todo: Create popup that say there is a problem with the file system return False # No dir named /media/pi/ elif ''.join(output.split()) == '': print(type(self).__name__, "DEBUG: no files in", CMD_LS, DIR_MEDIA) #Todo: Create popup that say there is no usb device mounted return False # No files in /media/pi/ else: return True # Found device(s) mounted in /media/pi/ # check if usb storage device is mounted def check_sd_mounted(self): output = os.popen(CMD_DF_SD).read() # df | grep /dev/sd if output == None: print(type(self).__name__, ":", "No mounted storage device") return False # Did not find mounted device(s) else: print(type(self).__name__, "Mounted Devices:", output) return True # Found mounted device(s) # button method to export data to a mounted storage device def exportButton(self): if self.exported: return if self.check_sd_mounted(): self.get_media_dev_list() self.popup_pick() else: self.lbl_export_message.text = "No device found" # create a popup that gives user toe option to choose a device def popup_pick(self): self.float_popup = FloatLayout() self.float_popup.add_widget( Label(size_hint=[0.6, 0.2], text="You will export the data to a \nUSB device", font_size=20, pos_hint={ "x": 0.2, "top": 1 })) self.float_popup.add_widget( Button(size_hint=[0.8, 0.2], text="Go Back", font_size=35, pos_hint={ "x": 0.1, "y": 0.1 }, on_press=lambda a: self.popupWindow.dismiss())) count = 0 for i in self.media_pi_devs: if (not i == '') and count < 2: # print(type(self).__name__,"-----i:",i) btn = Button( text=i, size_hint=[0.8, 0.20], pos_hint={ "x": 0.1, "y": 0.32 + 1.2 * count }, font_size=30 #, # on_press= lambda a:self.popup_pick_device(count) ) if count == 0: btn.bind(on_press=self.popup_pick_device0) elif count == 1: btn.bind(on_press=self.popup_pick_device1) self.float_popup.add_widget(btn) count += 1 self.popupWindow = Popup(content=self.float_popup, size_hint=(None, None), size=(400, 400)) self.popupWindow.open() #Popup Button methods def popup_pick_device0(self, *args): self.DEVICENAME = self.media_pi_devs[0] # print(type(self).__name__,"----The Device picked:",self.media_pi_devs[0]) self.popupWindow.dismiss() self.save_to_usb() def popup_pick_device1(self, *args): self.DEVICENAME = self.media_pi_devs[1] # print(type(self).__name__,"----The Device picked:",self.media_pi_devs[1]) self.popupWindow.dismiss() self.save_to_usb() # Save data to usb def save_to_usb(self): loglist = db.get_logs_data(s.ACTIVE_LECTURER) sessionlist = db.get_sessions_data(s.ACTIVE_LECTURER) # print(type(self).__name__,loglist) # Check if there is data in the database if loglist == None or sessionlist == None: print(type(self).__name__, 'Nothing to export') self.lbl_export_message.text = "Nothing to export" else: self.EXPORTFILENAME = 'sucsexport' + s.SUCS_UNIT_NAME + make_datetime_stamp( ) + '.csv' self.lbl_export_message.text = "Export In Progress" export_success = True # write stamp to .csv self.EXPORTDATA = str(s.SUCS_UNIT_NAME) + "," + str( s.SUCS_SOFTWARE_VERSION) + "," + str(s.SUCS_LAST_UPDATE) + "\n" output = os.popen( CMD_ECHO + '"' + self.EXPORTDATA + '" >> "' + DIR_MEDIA + self.DEVICENAME + '/' + self.EXPORTFILENAME + '"') # echo "data" >> "media/pi/DEVICENAME/ECXPORTFILENAME" # Check once if command is successful if "Permission denied" in output: print( type(self).__name__, 'Error: Permission Denied for "' + DIR_MEDIA + self.DEVICENAME + '/' + self.EXPORTFILENAME + '"') #TODO: Check for more tests self.lbl_export_message.text = "Permission Denied" export_success = False return # write session data to .csv line by line for line in sessionlist: self.EXPORTDATA = str( line[0] ) + "," + str(line[1]) + "," + str(line[2]) + "," + str( line[3] ) # data = 20200831100212,20123456,2020-08-31 10:13:28,2020-08-31 10:33:28 output = os.popen( CMD_ECHO + '"' + self.EXPORTDATA + '" >> "' + DIR_MEDIA + self.DEVICENAME + '/' + self.EXPORTFILENAME + '"' ) # echo "data" >> "media/pi/DEVICENAME/ECXPORTFILENAME" # write a line break output = os.popen( CMD_ECHO + '"" >> "' + DIR_MEDIA + self.DEVICENAME + '/' + self.EXPORTFILENAME + '"') # echo "data" >> "media/pi/DEVICENAME/ECXPORTFILENAME" # write logs data to .csv line by line for line in loglist: self.EXPORTDATA = str(line[0]) + "," + str( line[1]) + "," + str( line[2] ) # data = 20200831100212,20123456,2020-08-31 10:13:28 output = os.popen( CMD_ECHO + '"' + self.EXPORTDATA + '" >> "' + DIR_MEDIA + self.DEVICENAME + '/' + self.EXPORTFILENAME + '"' ) # echo "data" >> "media/pi/DEVICENAME/ECXPORTFILENAME" if export_success: self.lbl_export_message.text = "Export Successful"
class LectureLoginWindow(Screen): """ login window class RFID scanner activates on entry unless Settings.RFID_ENABLED = False. Args: Screen (Screen): kivy.uix.screenmanager """ sc = None # SUCS_RFID onject # built-in kivy function: before entering the login window def on_pre_enter(self): s.APP_STATE = "LOGIN" # activate rfid scanner #? if s.RFID_ENABLED: #? if self.sc: #? print(type(self).__name__,"sc:",self.sc) #!Print #? if not self.sc: #? self.sc = SUCS_RFID(key=key.RFID_AUTH_KEY, block_addrs=key.RFID_BLOCK_ADDRS) #? self.sc.start() #? #self.sc.rfid_start_scan(scan_interval=s.RFID_READ_INTERVAL) #? if self.sc: #? print(type(self).__name__,"sc:",self.sc) #!Print #? # shedule event: check if a card has been scanned #? self.checkInfoSchedule = Clock.schedule_interval(self.checkInfo, s.SCAN_CHECK_INTERVAL) #? if not self.checkInfoSchedule.is_triggered: #? self.checkInfoSchedule() # periodic routine: check if check if a card has been scanned def checkInfo(self, *args): info = self.sc.get_lastread_text() #get (usnum, name) from database if not info == None: # test if valid lecturer if db.valid_lecturer(info[0]): # save data and go to main screen Clock.unschedule(self.checkInfo) s.ACTIVE_LECTURER = info self.loginBtn() else: self.popup_new_lecture() # login button is pressed or valid Lecturer card is scanned def loginBtn(self): if s.LOGIN_BYPASS: #? Clock.unschedule(self.checkInfo) s.ACTIVE_LECTURER = s.MANUAL_LECTURER # save data and go to main screen sm.current = "main" #? self.resetLogin() # popup: create new lecturer def popup_new_lecture(self): self.float_popup = FloatLayout() self.float_popup.add_widget( Label( size_hint=[0.6, 0.4], text="Do you want to register as a lecturer using this device?", font_size=20, pos_hint={ "x": 0.2, "top": 1 })) self.float_popup.add_widget( Button(size_hint=[0.8, 0.2], text="Yes", font_size=35, pos_hint={ "x": 0.1, "y": 0.4 }, on_press=lambda a: self.createNewLecrurer())) self.float_popup.add_widget( Button(size_hint=[0.8, 0.2], text="No", font_size=35, pos_hint={ "x": 0.1, "y": 0.1 }, on_press=lambda a: self.popupWindow.dismiss())) self.popupWindow = Popup(content=self.float_popup, size_hint=(None, None), size=(400, 400)) self.popupWindow.open() # popup button method def createNewLecrurer(self, *args): if db.insert_lecturer(s.ACTIVE_LECTURER) < 0: print(type(self).__name__, "Failed to create new lecturer") #!Print else: print( type(self).__name__, "Successfully created lecturer:", s.ACTIVE_LECTURER) #!Print self.popupWindow.dismiss() # log off application def logoffBtn(self): s.APP_STATE = "OFF" #? self.resetLogin() SUCSterminate() # reset class data def resetLogin(self): self.sc.rfid_stop_scan() print(type(self).__name__, "+++++Stop Scan") #!remove self.sc.close() self.sc = None
if __name__ == '__main__': from kivy.uix.floatlayout import FloatLayout from kivy.lang import Builder from kivy.uix.label import Label from kivy.base import runTouchApp class HoverLabel(Label, HoverBehavior): def on_enter(self, *args): print("You are in, through this point", self.border_point) def on_leave(self, *args): print("You left through this point", self.border_point) Builder.load_string(''' <HoverLabel>: text: "inside" if self.hovered else "outside" pos: 200,200 size_hint: None, None size: 100, 30 canvas.before: Color: rgb: 1,0,0 Rectangle: size: self.size pos: self.pos ''') fl = FloatLayout() fl.add_widget(HoverLabel()) runTouchApp(fl)
class Board(RelativeLayout): """A graphical view onto a :class:`LiSE.Character`, resembling a game board. """ character = ObjectProperty() wallpaper_path = StringProperty() spot = DictProperty({}) pawn = DictProperty({}) arrow = DictProperty({}) kvlayoutback = ObjectProperty() arrowlayout = ObjectProperty() spotlayout = ObjectProperty() pawnlayout = ObjectProperty() kvlayoutfront = ObjectProperty() wids = ReferenceListProperty(kvlayoutback, arrowlayout, spotlayout, pawnlayout, kvlayoutfront) spots_unposd = ListProperty([]) layout_tries = NumericProperty(5) tracking_vel = BooleanProperty(False) selection_candidates = ListProperty([]) selection = ObjectProperty(allownone=True) keep_selection = ObjectProperty(False) adding_portal = BooleanProperty(False) reciprocal_portal = BooleanProperty(False) grabbing = BooleanProperty(True) grabbed = ObjectProperty(None, allownone=True) @property def widkwargs(self): return {'size_hint': (None, None), 'size': self.size, 'pos': (0, 0)} def on_touch_down(self, touch): """Check for collisions and select an appropriate entity.""" if hasattr(self, '_lasttouch') and self._lasttouch == touch: return if not self.collide_point(*touch.pos): return if self.selection: self.selection.hit = self.selection.collide_point(*touch.pos) if self.selection.hit: Logger.debug("Board: hit selection") touch.grab(self.selection) pawns = list(self.pawns_at(*touch.pos)) if pawns: Logger.debug("Board: hit {} pawns".format(len(pawns))) self.selection_candidates = pawns if self.selection in self.selection_candidates: self.selection_candidates.remove(self.selection) return True spots = list(self.spots_at(*touch.pos)) if spots: Logger.debug("Board: hit {} spots".format(len(spots))) self.selection_candidates = spots if self.adding_portal: self.origspot = self.selection_candidates.pop(0) self.protodest = Dummy(name='protodest', pos=touch.pos, size=(0, 0)) self.add_widget(self.protodest) self.protodest.on_touch_down(touch) self.protoportal = ArrowWidget(origin=self.origspot, destination=self.protodest) self.add_widget(self.protoportal) if self.reciprocal_portal: self.protoportal2 = ArrowWidget(destination=self.origspot, origin=self.protodest) self.add_widget(self.protoportal2) return True if not self.selection_candidates: arrows = list(self.arrows_at(*touch.pos)) if arrows: Logger.debug("Board: hit {} arrows".format(len(arrows))) self.selection_candidates = arrows return True def on_touch_move(self, touch): """If an entity is selected, drag it.""" if hasattr(self, '_lasttouch') and self._lasttouch == touch: return if self.selection in self.selection_candidates: self.selection_candidates.remove(self.selection) if self.selection: if not self.selection_candidates: self.keep_selection = True return self.selection.dispatch('on_touch_move', touch) elif self.selection_candidates: for cand in self.selection_candidates: if cand.collide_point(*touch.pos): if hasattr(self.selection, 'selected'): self.selection.selected = False if hasattr(self.selection, 'hit'): self.selection.hit = False self.selection = cand cand.hit = cand.selected = True touch.grab(cand) return cand.dispatch('on_touch_move', touch) def portal_touch_up(self, touch): """Try to create a portal between the spots the user chose.""" try: # If the touch ended upon a spot, and there isn't # already a portal between the origin and this # destination, create one. destspot = next(self.spots_at(*touch.pos)) orig = self.origspot.proxy dest = destspot.proxy if not (orig.name in self.character.portal and dest.name in self.character.portal[orig.name]): port = self.character.new_portal(orig.name, dest.name) self.arrowlayout.add_widget(self.make_arrow(port)) # And another in the opposite direction if needed if (hasattr(self, 'protoportal2') and not (orig.name in self.character.preportal and dest.name in self.character.preportal[orig.name])): deport = self.character.new_portal(dest.name, orig.name) self.arrowlayout.add_widget(self.make_arrow(deport)) except StopIteration: pass self.remove_widget(self.protoportal) if hasattr(self, 'protoportal2'): self.remove_widget(self.protoportal2) del self.protoportal2 self.remove_widget(self.protodest) del self.protoportal del self.protodest def on_touch_up(self, touch): """Delegate touch handling if possible, else select something.""" if hasattr(self, '_lasttouch') and self._lasttouch == touch: return self._lasttouch = touch if hasattr(self, 'protodest'): Logger.debug("Board: on_touch_up making a portal") touch.ungrab(self) return self.portal_touch_up(touch) if hasattr(self.selection, 'on_touch_up'): self.selection.dispatch('on_touch_up', touch) while self.selection_candidates: candidate = self.selection_candidates.pop(0) if candidate.collide_point(*touch.pos): Logger.debug("Board: selecting " + repr(candidate)) if hasattr(self.selection, 'selected'): self.selection.selected = False if hasattr(self.selection, 'hit'): self.selection.hit = False if hasattr(self.selection, '_start'): self.selection.pos = self.selection._start del self.selection._start self.selection = candidate if hasattr(self.selection, 'selected'): self.selection.selected = True if hasattr(self.selection, 'hit'): self.selection.hit = True if (hasattr(self.selection, 'thing') and not hasattr(self.selection, '_start')): self.selection._start = tuple(self.selection.pos) self.keep_selection = True if not self.keep_selection: Logger.debug("Board: deselecting " + repr(self.selection)) if hasattr(self.selection, 'selected'): self.selection.selected = False if hasattr(self.selection, 'hit'): self.selection.hit = False self.selection = None self.keep_selection = False touch.ungrab(self) return def on_parent(self, *args): """Create some subwidgets and trigger the first update.""" if not self.parent or hasattr(self, '_parented'): return self._parented = True self.kvlayoutback = KvLayoutBack(wallpaper_path=self.wallpaper_path, pos=(0, 0)) self.bind(wallpaper_path=self.kvlayoutback.setter('wallpaper_path')) self.size = self.kvlayoutback.size self.kvlayoutback.bind(size=self.setter('size')) self.arrowlayout = FloatLayout(**self.widkwargs) self.spotlayout = FloatLayout(**self.widkwargs) self.pawnlayout = FloatLayout(**self.widkwargs) self.kvlayoutfront = KvLayoutFront(**self.widkwargs) for wid in self.wids: if wid != self.kvlayoutback: self.bind(size=wid.setter('size')) self.add_widget(wid) self.trigger_update() def on_character(self, *args): if self.character is None: return if self.parent is None: Clock.schedule_once(self.on_character, 0) return self.engine = self.character.engine self.wallpaper_path = self.character.stat.setdefault( 'wallpaper', 'wallpape.jpg') if '_control' not in self.character.stat or 'wallpaper' not in self.character.stat[ '_control']: control = self.character.stat.setdefault('_control', {}) control['wallpaper'] = 'textinput' self.character.stat['_control'] = control self.character.stat.connect(self._trigger_pull_wallpaper) def pull_wallpaper(self, *args): self.wallpaper_path = self.character.stat.setdefault( 'wallpaper', 'wallpape.jpg') def _trigger_pull_wallpaper(self, *args, **kwargs): if kwargs['key'] != 'wallpaper': return Clock.unschedule(self.pull_wallpaper) Clock.schedule_once(self.pull_wallpaper, 0) @trigger def kv_updated(self, *args): self.unbind(wallpaper_path=self.kvlayoutback.setter('wallpaper_path')) for wid in self.wids: self.remove_widget(wid) self.kvlayoutback = KvLayoutBack(pos=(0, 0), wallpaper_path=self.wallpaper_path) self.bind(wallpaper_path=self.kvlayoutback.setter('wallpaper_path')) self.kvlayoutfront = KvLayoutFront(**self.widkwargs) self.size = self.kvlayoutback.size self.kvlayoutback.bind(size=self.setter('size')) for wid in self.wids: self.add_widget(wid) def make_pawn(self, thing): """Make a :class:`Pawn` to represent a :class:`Thing`, store it, and return it. """ if thing["name"] in self.pawn: raise KeyError("Already have a Pawn for this Thing") r = Pawn(board=self, thing=thing) self.pawn[thing["name"]] = r return r def make_spot(self, place): """Make a :class:`Spot` to represent a :class:`Place`, store it, and return it. """ if place["name"] in self.spot: raise KeyError("Already have a Spot for this Place") r = Spot(board=self, place=place) self.spot[place["name"]] = r if '_x' in place and '_y' in place: r.pos = (self.width * place['_x'], self.height * place['_y']) return r def make_arrow(self, portal): """Make an :class:`Arrow` to represent a :class:`Portal`, store it, and return it. """ if (portal["origin"] not in self.spot or portal["destination"] not in self.spot): raise ValueError("An :class:`Arrow` should only be made after " "the :class:`Spot`s it connects") if (portal["origin"] in self.arrow and portal["destination"] in self.arrow[portal["origin"]]): raise KeyError("Already have an Arrow for this Portal") r = Arrow(board=self, portal=portal) if portal["origin"] not in self.arrow: self.arrow[portal["origin"]] = {} self.arrow[portal["origin"]][portal["destination"]] = r return r def rm_arrows_to_and_from(self, name): origs = list(self.arrow.keys()) if name in origs: origs.remove(name) for dest in list(self.arrow[name].keys()): self.rm_arrow(name, dest) for orig in origs: if name in self.arrow[orig]: self.rm_arrow(orig, name) def rm_pawn(self, name, *args): """Remove the :class:`Pawn` by the given name.""" if name not in self.pawn: raise KeyError("No Pawn named {}".format(name)) # Currently there's no way to connect Pawns with Arrows but I # think there will be, so, insurance self.rm_arrows_to_and_from(name) pwn = self.pawn[name] pwn.parent.remove_widget(pwn) for canvas in (self.pawnlayout.canvas.after, self.pawnlayout.canvas.before, self.pawnlayout.canvas): if pwn.group in canvas.children: canvas.remove(pwn.group) pwn.canvas.clear() del self.pawn[name] def _trigger_rm_pawn(self, name): Clock.schedule_once(partial(self.rm_pawn, name), 0) def rm_spot(self, name, *args): """Remove the :class:`Spot` by the given name.""" if name not in self.spot: raise KeyError("No Spot named {}".format(name)) spot = self.spot[name] pawns_here = list(spot.children) self.rm_arrows_to_and_from(name) self.spotlayout.remove_widget(spot) spot.canvas.clear() del self.spot[name] for pawn in pawns_here: self.rm_pawn(pawn.name) def _trigger_rm_spot(self, name): part = partial(self.rm_spot, name) Clock.unschedule(part) Clock.schedule_once(part, 0) def rm_arrow(self, orig, dest, *args): """Remove the :class:`Arrow` that goes from ``orig`` to ``dest``.""" if (orig not in self.arrow or dest not in self.arrow[orig]): raise KeyError("No Arrow from {} to {}".format(orig, dest)) self.arrowlayout.remove_widget(self.arrow[orig][dest]) del self.arrow[orig][dest] def _trigger_rm_arrow(self, orig, dest): part = partial(self.rm_arrow, orig, dest) Clock.unschedule(part) Clock.schedule_once(part, 0) def graph_layout(self, graph): from networkx.drawing.layout import spring_layout return normalize_layout(spring_layout(graph)) def discard_pawn(self, thingn, *args): if thingn in self.pawn: self.rm_pawn(thingn) def _trigger_discard_pawn(self, thing): part = partial(self.discard_pawn, thing) Clock.unschedule(part) Clock.schedule_once(part, 0) def remove_absent_pawns(self, *args): Logger.debug("Board: removing pawns absent from {}".format( self.character.name)) for pawn_name in list(self.pawn.keys()): if pawn_name not in self.character.thing: self.rm_pawn(pawn_name) def discard_spot(self, placen, *args): if placen in self.spot: self.rm_spot(placen) def _trigger_discard_spot(self, place): Clock.schedule_once(partial(self.discard_spot, place), 0) def remove_absent_spots(self, *args): Logger.debug("Board: removing spots absent from {}".format( self.character.name)) for spot_name in list(self.spot.keys()): if spot_name not in self.character.place: self.rm_spot(spot_name) def discard_arrow(self, orign, destn, *args): if (orign in self.arrow and destn in self.arrow[orign]): self.rm_arrow(orign, destn) def _trigger_discard_arrow(self, orig, dest): Clock.schedule_once(partial(self.discard_arrow, orig, dest), 0) def remove_absent_arrows(self, *args): Logger.debug("Board: removing arrows absent from {}".format( self.character.name)) for arrow_origin in list(self.arrow.keys()): for arrow_destination in list(self.arrow[arrow_origin].keys()): if (arrow_origin not in self.character.portal or arrow_destination not in self.character.portal[arrow_origin]): self.rm_arrow(arrow_origin, arrow_destination) def add_spot(self, placen, *args): if (placen in self.character.place and placen not in self.spot): self.spotlayout.add_widget( self.make_spot(self.character.place[placen])) def _trigger_add_spot(self, placen): Clock.schedule_once(partial(self.add_spot, placen), 0) def add_new_spots(self, *args): Logger.debug("Board: adding new spots to {}".format( self.character.name)) spots_added = [] nodes_patch = {} for place_name in self.character.place: if place_name not in self.spot: place = self.character.place[place_name] spot = self.make_spot(place) patch = {} if '_image_paths' in place: zeroes = [0] * len(place['_image_paths']) else: patch['_image_paths'] = spot.default_image_paths zeroes = [0] if '_offxs' not in place: patch['_offxs'] = zeroes if '_offys' not in place: patch['_offys'] = zeroes if '_stackhs' not in place: patch['_stackhs'] = zeroes if patch: nodes_patch[place_name] = patch self.spotlayout.add_widget(spot) spots_added.append(spot) if nodes_patch: self.engine.handle( 'update_nodes', char=self.character.name, patch=nodes_patch, ) for spot in spots_added: spot.finalize() self.spots_unposd = spots_added def add_arrow(self, orign, destn, *args): if not (orign in self.character.portal and destn in self.character.portal[orign]): raise ValueError("No portal for arrow {}->{}".format(orign, destn)) if not (orign in self.arrow and destn in self.arrow[orign]): self.arrowlayout.add_widget( self.make_arrow(self.character.portal[orign][destn])) assert self.arrow[orign][destn] in self.arrowlayout.children def _trigger_add_arrow(self, orign, destn): part = partial(self.add_arrow, orign, destn) Clock.unschedule(part) Clock.schedule_once(part, 0) def add_new_arrows(self, *args): Logger.debug("Board: adding new arrows to {}".format( self.character.name)) for arrow_orig in self.character.portal: for arrow_dest in self.character.portal[arrow_orig]: if (arrow_orig not in self.arrow or arrow_dest not in self.arrow[arrow_orig]): self.arrowlayout.add_widget( self.make_arrow( self.character.portal[arrow_orig][arrow_dest])) def add_pawn(self, thingn, *args): if (thingn in self.character.thing and thingn not in self.pawn): pwn = self.make_pawn(self.character.thing[thingn]) locn = pwn.thing['location'] nextlocn = pwn.thing['next_location'] if nextlocn is None: self.add_spot(nextlocn) whereat = self.spot[locn] else: self.add_arrow(locn, nextlocn) whereat = self.arrow[locn][nextlocn] whereat.add_widget(pwn) self.pawn[thingn] = pwn def _trigger_add_pawn(self, thingn): part = partial(self.add_pawn, thingn) Clock.unschedule(part) Clock.schedule_once(part, 0) def add_new_pawns(self, *args): Logger.debug("Board: adding new pawns to {}".format( self.character.name)) nodes_patch = {} pawns_added = [] for (thing_name, thing) in self.character.thing.items(): if thing_name not in self.pawn: pwn = self.make_pawn(thing) pawns_added.append(pwn) patch = {} if '_image_paths' in thing: zeroes = [0] * len(thing['_image_paths']) else: patch['_image_paths'] = Pawn.default_image_paths zeroes = [0] * len(Pawn.default_image_paths) if '_offxs' not in thing: patch['_offxs'] = zeroes if '_offys' not in thing: patch['_offys'] = zeroes if '_stackhs' not in thing: patch['_stackhs'] = zeroes if patch: nodes_patch[thing_name] = patch try: whereat = self.arrow[pwn.thing['location']][ pwn.thing['next_location']] except KeyError: whereat = self.spot[pwn.thing['location']] whereat.add_widget(pwn) self.pawn[thing_name] = pwn if nodes_patch: self.engine.handle('update_nodes', char=self.character.name, patch=nodes_patch, silent=True) for pwn in pawns_added: pwn.finalize() @trigger def trigger_update(self, *args): """Force an update to match the current state of my character. This polls every element of the character, and therefore causes me to sync with the LiSE core for a long time. Avoid when possible. """ # remove widgets that don't represent anything anymore Logger.debug("Board: updating") self.remove_absent_pawns() self.remove_absent_spots() self.remove_absent_arrows() # add widgets to represent new stuff self.add_new_spots() self.add_new_arrows() self.add_new_pawns() self.spots_unposd = [ spot for spot in self.spot.values() if not ('_x' in spot.proxy and '_y' in spot.proxy) ] def update_from_delta(self, delta, *args): """Apply the changes described in the dict ``delta``.""" for (place, extant) in delta.get('places', {}).items(): if extant and place not in self.spot: self.add_spot(place) spot = self.spot[place] if '_x' not in spot.place or '_y' not in spot.place: self.spots_unposd.append(spot) elif not extant and place in self.spot: self.rm_spot(place) for (thing, extant) in delta.get('things', {}).items(): if extant and thing not in self.pawn: self.add_pawn(thing) elif not extant and thing in self.pawn: self.rm_pawn(thing) for (node, stats) in delta.get('node_val', {}).items(): if node in self.spot: spot = self.spot[node] x = stats.get('_x') y = stats.get('_y') if x is not None: spot.x = x * self.width if y is not None: spot.y = y * self.height if '_image_paths' in stats: spot.paths = stats[ '_image_paths'] or spot.default_image_paths elif node in self.pawn: pawn = self.pawn[node] if 'location' in stats: pawn.loc_name = stats['location'] if 'next_location' in stats: pawn.next_loc_name = stats['next_location'] if '_image_paths' in stats: pawn.paths = stats[ '_image_paths'] or pawn.default_image_paths else: Logger.warning("Board: diff tried to change stats of node {} " "but I don't have a widget for it".format(node)) for (orig, dests) in delta.get('edges', {}).items(): for (dest, extant) in dests.items(): if extant and (orig not in self.arrow or dest not in self.arrow[orig]): self.add_arrow(orig, dest) elif not extant and orig in self.arrow and dest in self.arrow[ orig]: self.rm_arrow(orig, dest) def trigger_update_from_delta(self, delta, *args): part = partial(self.update_from_delta, delta) Clock.unschedule(part) Clock.schedule_once(part, 0) def on_spots_unposd(self, *args): # TODO: If only some spots are unpositioned, and they remain # that way for several frames, put them somewhere that the # user will be able to find. if not self.spots_unposd: return try: minx, miny, maxx, maxy = detect_2d_grid_layout_bounds( spot.name for spot in self.spots_unposd) assert minx != maxx assert miny != maxy self.grid_layout(minx, miny, maxx, maxy) except ValueError: self.nx_layout() def _apply_node_layout(self, l, *args): if self.width == 1 or self.height == 1: Clock.schedule_once(partial(self._apply_node_layout, l), 0.01) return node_upd = {} for spot in self.spots_unposd: (x, y) = l[spot.name] assert 0 <= x <= 0.98 assert 0 <= y <= 0.98 assert spot in self.spotlayout.children assert self.spotlayout.width == self.width assert self.spotlayout.height == self.height node_upd[spot.name] = {'_x': x, '_y': y} spot.pos = (int(x * self.width), int(y * self.height)) if node_upd: self.character.engine.handle('update_nodes', char=self.character.name, patch=node_upd, silent=True) self.spots_unposd = [] def grid_layout(self, minx, miny, maxx, maxy, *args): l = normalize_layout( {spot.name: spot.name for spot in self.spots_unposd}, minx, miny, maxx, maxy) self._apply_node_layout(l) def nx_layout(self, *args): for spot in self.spots_unposd: if not (spot.name and spot.proxy): Clock.schedule_once(self.nx_layout, 0) return spots_only = self.character.facade() for thing in list(spots_only.thing.keys()): del spots_only.thing[thing] self._apply_node_layout(self.graph_layout(spots_only)) def arrows(self): """Iterate over all my arrows.""" for o in self.arrow.values(): for arro in o.values(): yield arro def pawns_at(self, x, y): """Iterate over pawns that collide the given point.""" for pawn in self.pawn.values(): if pawn.collide_point(x, y): yield pawn def spots_at(self, x, y): """Iterate over spots that collide the given point.""" for spot in self.spot.values(): if spot.collide_point(x, y): yield spot def arrows_at(self, x, y): """Iterate over arrows that collide the given point.""" for arrow in self.arrows(): if arrow.collide_point(x, y): yield arrow