class MessageBox(EnergyGameApp): def __init__(self, parent, titleheader="Title", message="Message", options={"OK": ""}, size=(400, 400)): def popup_callback(instance): "callback for button press" self.retvalue = instance.text self.popup.dismiss() self.parent = parent self.retvalue = None self.titleheader = titleheader self.message = message self.options = options self.size = size box = GridLayout(orientation='vertical', cols=1) box.add_widget(Label(text=self.message, font_size=16)) b_list = [] buttonbox = BoxLayout(orientation='horizontal') for b in self.options: b_list.append(Button(text=b, size_hint=(1,.35), font_size=20)) b_list[-1].bind(on_press=popup_callback) buttonbox.add_widget(b_list[-1]) box.add_widget(buttonbox) self.popup = Popup(title=titleheader, content=box, size_hint=(None, None), size=self.size) self.popup.open() self.popup.bind(on_dismiss=self.OnClose) def OnClose(self, event): self.popup.unbind(on_dismiss=self.OnClose) self.popup.dismiss() if self.retvalue and self.options[self.retvalue] != "": command = "self.parent."+self.options[self.retvalue] exec command
class ProgressBarScreen(Screen): progress_bar = ObjectProperty() def __init__(self, **kwa): super(ProgressBarScreen, self).__init__(**kwa) self.progress_bar = ProgressBar() self.popup = Popup( title='Running, Do Not Exit', content=self.progress_bar ) self.popup.bind(on_open=self.puopen) layout = BoxLayout(orientation='horizontal', size_hint=[.5, .1], pos_hint={'x':.5, 'y':0}) layout.add_widget(Button(text='Run Current Test', on_release=self.pop)) self.add_widget(layout) def pop(self, instance): self.progress_bar.value = 1 self.popup.open() def next(self, dt): self.progress_bar.value += 1 def puopen(self, instance): while self.progress_bar.value<100: Clock.schedule_once(self.next, 5) self.progress_bar.value += 1 if self.progress_bar.value>=100: self.popup.dismiss() ResultsScreen().show()
class InfoCtl(AbstractController): def error(self,titol,msg,trace): e=ErrorLayout() e.lbl.text=msg e.trace.text = trace e.btn.text=_('Aceptar') from utils.format import get_format popup = Popup(title_size=get_format('font14'),title=titol, content=e, size_hint=(None, None), size=(400, 400)) e.btn.bind(on_press=popup.dismiss) popup.open() def createScreens(self): pass def show_message(self,titol,msg,aceptar_function=None,w=400,h=400): e=MessageLayout() self.aceptar_function=aceptar_function e.lbl.text=msg e.btn.text=_('Aceptar') from utils.format import get_format self.popup = Popup(title_size=get_format('font14'),title=titol, content=e, size_hint=(None, None), size=(w, h)) e.btn.bind(on_press=self.on_press_aceptar) self.popup.open() def on_press_aceptar(self,instance): self.popup.dismiss() if self.aceptar_function: self.aceptar_function()
def login(self, mail, passwd, init=False): if self.login_dialog is not None and isinstance(self.login_dialog, Popup): self.login_dialog.dismiss() content = LoginProgressDialog() progress_dialog = Popup(title="ログイン", content=content, size_hint=(0.3, 0.3)) progress_dialog.open() if mail == "": mail = None if passwd == "": passwd = None self.configs.mail = mail self.configs.passwd = passwd try: self.download_video = DownloadVideo(self.configs) self.status_text = "ログインに成功しました" self.mylist_items = MyList.get_mylist_names(self.download_video.session) except LoginFailedException: if init: message = "ユーザー名とパスワードを入力してください" else: message = "ログインに失敗しました" login_dialog = LoginDialog(message, start_login=self.start_login) self.login_dialog = Popup(title="ログイン", content=login_dialog, size_hint=(0.8, 0.9)) self.login_dialog.open() finally: progress_dialog.dismiss()
class AddBlockButton(Button): def __init__(self, *args, **kwargs): super(AddBlockButton, self).__init__(*args, **kwargs) self.bind(on_release=self.openPopup) box=BoxLayout(padding=10) self.Input=TextInput(text="New Block", multiline=False, font_size=18) self.Input.bind(on_text_validate=self.addBlock) b=Button(text="Add it") b.bind(on_release=self.addBlock) box.add_widget(self.Input) box.add_widget(b) self.addPopup = Popup(title="Add A New Block", size_hint=(None,None), size=(400,115), separator_color=[.9,.4,.2,1], background_color=[0,0,0,.6], content=box ) def openPopup(self,*args): self.addPopup.open() def addBlock(self,*args): tree = self.parentLayout.ids["blockstree"] b=TreeViewBlock(text=self.Input.text,is_open=True) b.parentTree=tree tree.add_node(b) blocks= createBlockDicts(tree.iterate_all_nodes()) #Update Blocks updateConfig({"blocks":blocks}) self.addPopup.dismiss()
def update_game(self): pop = Popup(title='Updating', content=Label(text='Questions been updated'), auto_dismiss=False) pop.open() Clock.schedule_once(self.update, 0) pop.dismiss()
class Main(BoxLayout): song_title = ObjectProperty() play_button = ObjectProperty() def __init__(self): super(Main,self).__init__() self.sound = AudioModule() def show_popup(self): content = Loader(load=self.load_sound, cancel=self.dismiss_popup) self.p = Popup(title="Choose a File",content=content) self.p.open() def dismiss_popup(self): self.p.dismiss() def load_sound(self,audio): self.sound.load(audio[0]) self.song_title.text = str(audio[0]) self.p.dismiss() #self._play() def _play(self): self.sound.play() def _pause(self): self.sound.pause()
class FileDropDown(MenuDropDown): path = ObjectProperty(None, allownone=True) file = ObjectProperty(None, allownone=True) def __init__(self, **kwargs): self.file_dialog = None self.popup = None kwargs.setdefault('name', 'File') kwargs.setdefault('items', ['New', 'Open', 'Save']) super(FileDropDown, self).__init__(**kwargs) self.current_mode = None if self.path is None: self.path = os.getcwd() self.register_event_type('on_new_file') self.register_event_type('on_open_file') self.register_event_type('on_save_file') def build_file_dialog(self): dlg = self.file_dialog = FileDialog(mode=self.current_mode, path=self.path, file=self.file) dlg.bind(on_cancel=self.on_file_dialog_cancel, on_submit=self.on_file_dialog_submit) self.popup = Popup(title=self.current_mode.title(), content=dlg, size_hint=(.9, .9)) self.popup.open() def clear_file_dialog(self): self.file_dialog.unbind(on_cancel=self.on_file_dialog_cancel, on_submit=self.on_file_dialog_submit) self.popup.dismiss() self.file_dialog = None self.popup = None def on_file_dialog_cancel(self, *args): self.clear_file_dialog() self.current_mode = None def on_file_dialog_submit(self, *args): dlg = self.file_dialog self.path = dlg.path self.file = dlg.file self.clear_file_dialog() sig_name = '_'.join(['on', self.current_mode.lower(), 'file']) self.dispatch(sig_name, self.path, self.file) self.current_mode = None def on_select(self, value): self.current_mode = value if value == 'New': self.current_mode = None self.file = None self.dispatch('on_new_file') elif value == 'Open': self.build_file_dialog() elif value == 'Save': if self.file is not None: self.dispatch('on_save_file', self.path, self.file) self.current_mode = None else: self.build_file_dialog() def on_new_file(self, *args): pass def on_open_file(self, *args): pass def on_save_file(self, *args): pass
class vertexColorButton(Button): graph = ObjectProperty( GraphPanel()) popupp = ObjectProperty( Popup()) clrpkr = ObjectProperty(ColorPicker()) box = ObjectProperty(BoxLayout()) button = ObjectProperty(Button()) def on_touch_down(self, touch): if self.collide_point(touch.x, touch.y): self.popupp.open() def initialize(self, graph): self.text = "Vertex color" self.graph = graph self.box = BoxLayout(orientation='vertical', size_hint=(1,1)) self.clrpkr = ColorPicker(size_hint=(1,0.9)) self.button = Button(text='Done', size_hint=(1,0.1)) self.button.bind(on_press=self.close) self.box.add_widget(self.clrpkr) self.box.add_widget(self.button) self.popupp = Popup(title='Choose your color', content=self.box,size_hint=(None, None), size=(400, 450)) def on_color(self): listColor = self.clrpkr.color r = listColor[0] g = listColor[1] b = listColor[2] self.graph.setAllVertexRGB(r,g,b) def close(self, touch): self.on_color() self.popupp.dismiss()
def send_bof(self): # self.connection.write(a_command + '?\r\n') # response = self.connection.read_until(b"\n") if not self.program: return send_bof_label = Label(text='Sending bof,\nplease be patient.') popup = Popup(title='ROACH Busnise', content=send_bof_label, size_hint=(None,None), size=(1,30)) popup.open() connection = telnetlib.Telnet(self.ip, self.port) connection.read_until('0', timeout=1) connection.write('?listbof\r\n') return_lit = connection.expect(['.*!listbof ok .*', ]) aList = return_lit[2] lol = aList.split('\n') pattern = r'#listbof (?P<bof_name>.*.bof)' regex_c = re.compile(pattern) bof_files = [] for data in lol: outP = regex_c.search(data) if outP: bof_files.append(outP.group('bof_name')) # is given the alternative to delete one bof # if the fpga is full if not(self.bitstream in bof_files): content = BofSelector("", bof_files) a_popup = Popup(title='Choose Bof', auto_dismiss=False, content=content, size_hint=(None, None), size=(400,400)) content.set_popup(a_popup) a_popup.open() while content.continues: pass chossen = content.choosen_name if len(chossen) > 0: connection.write('?delbof %s\r\n' % (chossen)) #print connection.read_until('!delbof ok', timeout=3) #thread.start_new(self.send_it, (connection,)) #connection command = '?uploadbof 3000 %s\r\n'%(self.bitstream) connection.write(command) time.sleep(1) command = 'nc %s 3000 < %s' %(self.ip, self.bof_path) os.system(command) popup.dismiss() connection.close()
class GUI(BoxLayout): def __init__(self, app): super(GUI, self).__init__(orientation='vertical') self.app = app self.label = Label(text='Connecting To Server...', color=(0, 0, 0, 1), halign='center', valign='middle') bl = BoxLayout(orientation='vertical') self.ti = TextInput(multiline=False, size_hint_y=0.3) bn = Button(text="Start", size_hint_y=0.3) bn.bind(on_press=self.connect) bl.add_widget(self.ti) bl.add_widget(bn) self.pp = Popup(title='Enter IP Address of Server:', content=bl) self.pp.open() def readactivity(self, activity): activity = activity.split("*****") activity = activity[0] msg = str("You are " + activity) try: tts.speak(msg) except NotImplementedError: print "Error!" def connect(self, btn): ip = self.ti.text self.app.connect_to_server(ip) self.pp.dismiss() self.add_widget(self.label)
class PopupApp(GridLayout): def __init__(self, **kwargs): super(PopupApp, self).__init__(**kwargs) self.cols = 1 buton1 = Button(text = "deschide un popup") buton1.size = (0.8,0.8) buton1.bind(on_press=self.un_popup) self.add_widget(buton1) def un_popup(self,buton): """Creaza un popup""" inchide=Button(text='Inchide!') inchide.size_hint = (1,0.1) eticheta=Label(text ="Acesta este un popup informativ!") layout2=BoxLayout() layout2.orientation = "vertical" layout2.add_widget(eticheta) layout2.add_widget(inchide) layout2.padding = 40 self.popup = Popup() self.popup.size_hint = (None,None) self.popup.size = (400, 400) self.popup.title='Testam un popup' self.popup.content=layout2 self.popup.open() inchide.bind(on_press=self.inchide_popup) def inchide_popup(self, Buton): """inchide""" self.popup.dismiss()
class JobLoading(Job): def on_feedback_init(self,*largs): from utils.format import get_format self.e=CargandoLayout() self.e.lbl=_('Cargando') self.popup = Popup(title_size=get_format('font14'),title=_('Cargando'), content=self.e, size_hint=(None, None), size=(400, 150),auto_dismiss=False) self.popup.open() def on_feedback_loop(self,*largs): self.e.pb.value=(self.e.pb.value+5)%self.e.pb.max def on_job_init(self,*largs): import gc print "job_collecting",str(gc.collect()) self.controller.screen_manager.all_widgets_disabled=True def on_job_finally(self,*largs): self.controller.screen_manager.all_widgets_disabled=False def on_job_error(self,*largs): info_ctl.error(_('Error'),self.str_error,self.str_traceback) def on_feedback_finished(self,*largs): self.popup.dismiss()
def login_but(self): # gets the data from the text inputs on the login page uname = self.ids['uname_input'] pword = self.ids['pass_input'] # make sure that the values are not null if len(uname.text) > 0: if len(pword.text) > 0: popup = Popup(title='', content=Label(text='Loading . . .'), size_hint=(.9, .3), size=(800, 800)) popup.open() query = retrieve("SELECT * FROM users WHERE username = \"%s\" AND password = \"%s\"" % (uname.text, pword.text)) popup.dismiss() if query == 0: popup = Popup(title='Connection', content=Label(text='Could not connect to the database'), size_hint=(.9, .3), size=(800, 800)) popup.open() elif len(query) < 1: popup = Popup(title='Invalid Credentials', content=Label(text='Username or Password is Incorrect'), size_hint=(.9, .3), size=(800, 800)) popup.open() else: user.uid, user.firstname, user.lastname, user.username, user.password, user.game_id, user.bt_ID, user.status, user.target = query[0] bt_ID = myBTA.getAddress() results = create("UPDATE users SET bt_ID = '%s' WHERE uid = '%s'" % (bt_ID, user.uid)) uname.text = "" pword.text = "" sm.current = "Home" else: popup = Popup(title='Invalid Credentials', content=Label(text='Please Enter a Password'), size_hint=(.9, .3), size=(800, 800)) popup.open() else: popup = Popup(title='Invalid Credentials', content=Label(text='Please Enter a Username'), size_hint=(.9, .3), size=(800, 800)) popup.open()
class DBWidget(TabbedPanel): def __init__(self, ctrl, **kwargs): super(DBWidget, self).__init__(size_hint=(1, 1), do_default_tab=False, **kwargs) self.ctrl = ctrl self.ctrl.add_call_listener(self) @mainthread def draw_db(self, db): for table in db.values(): th = TabbedPanelHeader(text=table['name']) th.content = TableWidget(self.ctrl, table) self.add_widget(th) def update(self): def get_db(): print 'updating...' if self.ctrl.is_opened(): db = self.ctrl.get_db() self.draw_db(db) self.clear_tabs() self.clear_widgets() self.popup = Popup(title='Loading', content=Label(text='Please wait'), auto_dismiss=False, size_hint=(0.3, 0.3)) self.popup.open() try: thread = threading.Thread(target=get_db) thread.start() finally: self.popup.dismiss() self.popup = None
class ChooseOptionPopup: m_dictOptionCallback = None def __init__(self, title, listOptionCallback): self.m_dictOptionCallback = {} layout = BoxLayout(orientation="vertical") for option,callback in listOptionCallback: if callback != None: self.m_dictOptionCallback[option] = callback btn = Button(text=option, size_hint=(1, 0.1)) btn.bind(on_release = self.choice) layout.add_widget(btn) else: layout.add_widget(Label(text=option, size_hint=(1, 0.1))) self.popup = Popup(title=title,content=layout,size_hint=(0.5, min(0.1 + len(listOptionCallback) * 0.1, 1.0))) self.popup.open() def choice(self, instance): self.dismiss_popup() (self.m_dictOptionCallback[instance.text])() def dismiss_popup(self): self.popup.dismiss()
class ScreenControls(FloatLayout, MakesmithInitFuncs): def setButtonAppearance(self): ''' Called on creation to set up links to button background textures ''' self.actionsBtn.btnBackground = self.data.iconPath + 'Generic.png' self.actionsBtn.textColor = self.data.fontColor self.settingsBtn.btnBackground = self.data.iconPath + 'Generic.png' self.settingsBtn.textColor = self.data.fontColor self.backgroundBtn.btnBackground = self.data.iconPath + 'Generic.png' self.backgroundBtn.textColor = self.data.fontColor def openSettings(self): ''' Open the settings panel to manually change settings ''' #force the settings panel to update App.get_running_app().destroy_settings() #open the settings panel App.get_running_app().open_settings() def show_actions(self): ''' Open A Pop-up To Allow User Actions Creates a new pop-up allows the user to do things like open a file. ''' content = OtherFeatures() content.setUpData(self.data) content.close = self.close_actions self._popup = Popup(title="Actions", content=content, size_hint=(0.9, 0.9)) self._popup.open() def close_actions(self): ''' Close pop-up ''' self._popup.dismiss() def open_background(self): ''' Open A Pop-up To Manage the Canvas Background ''' content = BackgroundMenu(self.data) content.setUpData(self.data) content.close = self.close_actions self._popup = Popup(title="Background Picture", content=content, size_hint=(0.5, 0.5)) self._popup.open()
class NewImage(): def __init__(self, callback): self.title = "New Image: " self.callback = callback self.content = NewDialog(ok=self._ok, cancel=self._dismiss) self._popup = Popup(title=self.title, content=self.content, pos_hint={'center': 1, 'top': 1}, size_hint=(0.3, 0.3)) def open(self): self._popup.open() def _ok(self, wtext, htext): Window.release_all_keyboards() try: w = int(wtext) h = int(htext) except: PopupMessage("Notification", "Width and height should be greater than zero") return if w == 0 or h == 0: PopupMessage("Notification", "Width and height should be greater than zero") return self.callback((w, h)) self._popup.dismiss() def _dismiss(self): Window.release_all_keyboards() self._popup.dismiss()
class SettingsApp(App): settings_cls = SettingsWithSidebar display_type = 'popup' popup = None def build(self): bt = Button(text='Open settings') bt.bind(on_press=self.open_settings) return bt def on_settings_cls(self, *args): self.destroy_settings() def display_settings(self, settings): if self.display_type == 'popup': if self.popup is None: self.popup = Popup(content=settings, title='Settings', size_hint=(0.8, 0.8)) self.popup.open() else: super(SettingsApp, self).display_settings(settings) def close_settings(self, *args): if self.display_type == 'popup': if self.popup is not None: self.popup.dismiss() else: super(SettingsApp, self).close_settings()
def load_particle(self,name='templates/thelight.pex'): progress_dialog = Popup(title="Loading...", content=Label(text="Please wait while the particle file is being loaded."), size_hint=(.5,.5)) progress_dialog.open() pbuilder = self.parent.parent pl = pbuilder.params_layout pw = pbuilder.particle_window if not pl.tabs_loaded: # if the default panel is loaded, we need to create tabs pl.create_tabs() else: # if not, then the tabs are already there, but we do need to stop and remove the particle pbuilder.demo_particle.stop(clear = True) pw.remove_widget(pbuilder.demo_particle) new_particle = kivyparticle.ParticleSystem(name) new_particle.pos = pw.center_x, pw.center_y pbuilder.demo_particle = new_particle pw.add_widget(pbuilder.demo_particle) pbuilder.demo_particle.start() pbuilder.active_filename = os.path.basename(name) pl.particle_tabs.tab_list[0].content.get_values_from_particle() pl.particle_tabs.tab_list[1].content.get_values_from_particle() pl.particle_tabs.tab_list[2].content.get_values_from_particle() pl.open_first_tab() progress_dialog.dismiss()
class MessageBox(DownloadScreen): def __init__(self, titleheader="Title", message="Message", options={"OK": "self.ok()", "NO": "self.no()"}): def popup_callback(instance): "callback for button press" # print('Popup returns:', instance.text) self.retvalue = instance.text self.popup.dismiss() self.retvalue = None self.options = options box = BoxLayout(orientation='vertical') box.add_widget(Label(text=message, font_size=20)) b_list = [] buttonbox = BoxLayout(orientation='horizontal') for b in options: b_list.append(Button(text=b, size_hint=(1,.35), font_size=20)) b_list[-1].bind(on_press=popup_callback) buttonbox.add_widget(b_list[-1]) box.add_widget(buttonbox) self.popup = Popup(title=titleheader, content=box, size_hint=(None, None), size=(400, 400)) self.popup.open() self.popup.bind(on_dismiss=self.OnClose) def OnClose(self, event): self.popup.unbind(on_dismiss=self.OnClose) self.popup.dismiss() if self.retvalue != None: command = "super(MessageBox, self)."+self.options[self.retvalue] # print "command", command exec command
class CatchPhraseApp(App): def build(self): self.event_manager = ClientEventManager() self.uplink = Uplink(self.event_manager) self.popup = None self.lobby = None self.game = None return MyScreenManager() def loading_popup(self, message = "Loading..."): if self.popup: self.close_popup() self.popup = Popup(content=Label(text=message), auto_dismiss=False, size_hint = (1,.5), title="") self.popup.open() def close_popup(self, result=None): if self.popup: self.popup.dismiss() self.popup = None return result def generic_popup(self, message): if self.popup: self.close_popup() box_layout = BoxLayout(orientation="vertical") box_layout.add_widget(Label(text=message, size_hint = (1,.8))) close_button = Button(text='close', size_hint = (1, .2)) box_layout.add_widget(close_button) self.popup = Popup(content=box_layout, auto_dismiss=False, size_hint = (1, .5), title="") close_button.bind(on_release=self.popup.dismiss) self.popup.open()
class FilePopup: m_fctOpenCallback = None def __init__(self, open_callback, popuptitle): self.m_fctOpenCallback = open_callback layout = BoxLayout(orientation="vertical") self.selection = TextInput(multiline=False,text=os.getcwd() + os.sep, readonly=False,size_hint=(1,0.1),focus=True) layout.add_widget(self.selection) filechooser = FileChooserListView(filters=["*.py","*.txt"],path=os.getcwd()) layout.add_widget(filechooser) filechooser.bind(selection = self.on_selection) buttonslayout = BoxLayout(size_hint=(1, 0.1),orientation="horizontal") btn1 = Button(text='OK', size_hint=(0.5, 1)) btn1.bind(on_release = self.on_ok_button) buttonslayout.add_widget(btn1) btn2 = Button(text='Cancel', size_hint=(0.5, 1)) btn2.bind(on_release = self.on_cancel_button) buttonslayout.add_widget(btn2) layout.add_widget(buttonslayout) self.popup = Popup(title=popuptitle,content=layout,size_hint=(1,1)) self.popup.open() def on_selection(self, instance, value): self.selection.text = value and value[0] or "" def on_ok_button(self, instance): self.m_fctOpenCallback(self.selection.text) self.dismiss_popup() def on_cancel_button(self, instance): self.dismiss_popup() def dismiss_popup(self): self.popup.dismiss()
def login_but(self): # gets the data from the text inputs on the login page uname = self.ids['uname_input'] pword = self.ids['pass_input'] # make sure that the values are not null if len(uname.text) > 0: if len(pword.text) > 0: popup = Popup(title='', content=Label(text='Loading . . .'), size_hint=(None, None), size=(400, 100)) popup.open() query = root.retrieve("SELECT * FROM users WHERE username = \"%s\" AND password = \"%s\"" % (uname.text, pword.text)) popup.dismiss() if query == 0: popup = Popup(title='Connection', content=Label(text='Could not connect to the database'), size_hint=(None, None), size=(400, 100)) popup.open() elif len(query) < 1: popup = Popup(title='Invalid Credentials', content=Label(text='Username or Password is Incorrect'), size_hint=(None, None), size=(400, 100)) popup.open() else: uid, firstname, lastname, username, password, game = query[0] loggedinuser = username root.getBluetoothName() root.remove_widget(login) home.ids['uname_label'].text = "Welcome back %s" % (firstname) root.add_widget(home) else: popup = Popup(title='Invalid Credentials', content=Label(text='Please Enter a Password'), size_hint=(None, None), size=(400, 100)) popup.open() else: popup = Popup(title='Invalid Credentials', content=Label(text='Please Enter a Username'), size_hint=(None, None), size=(400, 100)) popup.open()
class QuestionYesNoPopup: m_fctAnswerCallback = None m_bAnswer = None def __init__(self, popuptitle, popupquestion, answercallback): self.m_fctAnswerCallback = answercallback layout = BoxLayout(orientation="vertical") layout.add_widget(Label(text=popupquestion)) buttonslayout = BoxLayout(size_hint=(1, 0.2),orientation="horizontal") btn1 = Button(text='Yes', size_hint=(0.5, 1)) btn1.bind(on_release = self.on_yes_button) buttonslayout.add_widget(btn1) btn2 = Button(text='No', size_hint=(0.5, 1)) btn2.bind(on_release = self.on_no_button) buttonslayout.add_widget(btn2) layout.add_widget(buttonslayout) self.popup = Popup(title=popuptitle,content=layout,size_hint=(0.75, 0.5)) self.popup.open() def on_yes_button(self, instance): self.m_bAnswer = True self.dismiss_popup() def on_no_button(self, instance): self.m_bAnswer = False self.dismiss_popup() def dismiss_popup(self): if self.m_fctAnswerCallback: self.m_fctAnswerCallback(self.m_bAnswer) self.popup.dismiss()
class SaveBase(): def __init__(self, callback): self.callback = callback self.app = App.get_running_app() self.def_path = self.app.config.getdefault('filechooser', 'save_path', DEF_PATH) if self.def_path == '': self.def_path = DEF_PATH self.content = SaveDialog(save=self._save, cancel=self._dismiss, filters=self.filters, formats=self.formats, set_format=self._set_format, get_texture=self._get_texture) self.content.chooser.path = self.def_path self.content.spinner.bind(text=self._set_format) self.content.chooser.bind(path=self._set_title) self._popup = Popup(title=self.title, content=self.content, size_hint=(1, 1)) self._set_title(self.content.chooser, self.def_path) def open(self): self._popup.open() def _set_format(self, spinner, format): self.format = format def _set_title(self, chooser, path): self._popup.title = self.title + os.path.normpath(path) def _dismiss(self): self._popup.dismiss() def _save(self, path, filename): fullpath = os.path.join(path, filename) + '.' + self.format.lower() def save(answer): if answer == 'yes': pass else: self.open() filename = os.path.split(filename)[1] if len(filename) == 0: PopupMessage(title='Information', text='Filename can\'t be is empty.', callback=save) return if set(filename).intersection('\\/:*?"<>|'): PopupMessage(title='Information', text='Filename can\'t contain any of \\/:*?"<>| characters.', callback=save) return if isfile(fullpath): ConfirmDialog(title='Confirmation', text='File already exist. Overwrite?', callback=save) return self.callback(path, filename, self.format) self._popup.dismiss() def _get_texture(self, filename): ext = '*' + splitext(filename)[1] if ext in self.filters: if ext == '*.pixelmate': return improc.merged_texture_from_zip(filename) else: return Image(source=filename).texture
class MessageBox(App): def __init__(self, parent, titleheader="Message", message="", options={"OK": ""}, size_hint=(.8,.3), font_size=None, size=None, modal=0, edit_add = False, edit_default_text=""): #def build(self, parent, titleheader="Message", message="", options={"OK": ""}, size_hint=(.8,.2), size=(None, None)): def popup_callback(instance): self.retvalue = instance.text self.popup.dismiss() self.parent = parent self.retvalue = None self.titleheader = titleheader self.message = message self.options = options self.font_size=font_size self.edit_add=edit_add self.edit_default_text=edit_default_text if size: self.size = size else: self.size=(0,0) if size_hint: self.size_hint=size_hint #box = GridLayout(orientation='vertical', cols=1) box = GridLayout(cols=1) box.orientation='vertical' #self.add_widget(box) #box.add_widget(Label(text=self.message, font_size=self.font_size)) box.add_widget(Label(text=self.message)) if self.edit_add: self.edit=TextInput(text=self.edit_default_text) box.add_widget(self.edit) b_list = [] buttonbox = BoxLayout(orientation='horizontal',size_hint=(1, None),height=32) box.add_widget(buttonbox) for b in self.options: b_list.append(Button(text=b, on_press=popup_callback)) #b_list[-1].bind(on_press=self.popup_callback) buttonbox.add_widget(b_list[-1]) if modal: #Допилить self.popup = ModalView() self.popup.title=titleheader self.popup.size_hint=self.size_hint self.popup.size=self.size self.popup.add_widget(box) else: self.popup = Popup(title=titleheader, content=box, size_hint=self.size_hint, size=self.size) #self.popup = Popup(title=titleheader, content=box, size_hint=self.size_hint) self.popup.open() self.popup.bind(on_dismiss=self.OnClose) def OnClose(self, event): self.popup.unbind(on_dismiss=self.OnClose) self.popup.dismiss() if self.retvalue != None and self.retvalue in self.options and self.options[self.retvalue] != "": command = "self.parent."+ (self.options[self.retvalue]%self.edit.text if self.edit_add else self.options[self.retvalue]) exec(command) def dismiss(self): self.retvalue = 'dismiss' self.popup.dismiss()
def dismiss( self, forced=False ) : Popup.dismiss( self ) if forced : return return {"axisColor" : self.axisColor.rgb(), \ "plotColor" : self.plotColor.rgb(), \ "xRange" : (self.xRangeMin.value, self.xRangeMax.value), \ "yRange" : (self.yRangeMin.value, self.yRangeMax.value) }, eval( self.expLabel.text )
class StructureElement(BaseElement): structure = ObjectProperty() userStructure = ObjectProperty() def __init__(self, structures, **kwargs): if not isinstance(structures[0], Structure) or not isinstance(structures[1], Structure): raise Exception("Un objet model de structure est requis") self.structure = structures[0] self.userStructure = structures[1] super(StructureElement, self).__init__(**kwargs) if self.structure.type == 3: widget = RHWidget elif self.structure.type == 2: widget = ShopWidget else: widget = BaseWidget widget = widget(sup=self.sup, structure=self.structure, userStructure=self.userStructure, size_hint=(1, 1), pos_hint={"left": 0, "top": 0}) self.changeWidget(widget) def changeWidget(self, widget): if not isinstance(widget, BaseWidget): raise Exception("Une objet héritant de BaseWidget est requis") self.ids.container.clear_widgets() self.ids.container.add_widget(widget) def leave(self, *args): self.sup.changeElement(self.sup.defaultElement()) def levelUpPopup(self, *args): self.popup = Popup(title="Vérification", size=("400dp", "200dp"), size_hint=(None, None), auto_dismiss=False) layout = BoxLayout(orientation='vertical', size_hint=(1, 1)) layout.add_widget( Label(text="Voulez-vous améliorer ce batiment ?\n Cela vous coutera " + str(self.priceCalc()) + " crédits", size_hint=(1, 0.7))) layout2 = BoxLayout(orientation='horizontal', size_hint=(1, 0.3)) button1 = Button(text="Oui") button2 = Button(text="Non") button1.bind(on_release=self.levelUp) button2.bind(on_release=self.popup.dismiss) layout2.add_widget(button1) layout2.add_widget(button2) layout.add_widget(layout2) self.popup.content = layout self.popup.open() def levelUp(self, *args): structureCtrl = StructureController(app=self.sup.app) if self.sup.app.gameManager.user.credits >= self.priceCalc(): structureCtrl.levelUp(self.structure.id) self.popup.dismiss() def priceCalc(self): return 50 * self.userStructure.level
class CurrentGameScreen(Screen, FloatLayout): def __init__ (self, *args, **kwargs): super(CurrentGameScreen, self).__init__(*args, **kwargs) self.eliminate = self.ids['eliminate'] self.status = self.ids['status'] self.eliminate.disabled = True self.BluetoothAdapter = autoclass('android.bluetooth.BluetoothAdapter') self.BluetoothDevice = autoclass('android.bluetooth.BluetoothDevice') self.BluetoothSocket = autoclass('android.bluetooth.BluetoothSocket') self.UUID = autoclass('java.util.UUID') self.Bundle = autoclass('android.os.Bundle') self.Intent = autoclass('android.content.Intent') self.IntentFilter = autoclass('android.content.IntentFilter') self.Context = autoclass('android.content.Context') self.Toast = autoclass('android.widget.Toast') self.PythonActivity = autoclass('org.renpy.android.PythonActivity') self.myBTA = self.BluetoothAdapter.getDefaultAdapter() self.popup = Popup(title='Notification', content=Label(text='Searching For Target. . .'), size_hint=(.9, .3), size=(800, 800)) self.popup1 = Popup(title='Notification', content=Label(text='Target Found!'), size_hint=(.9, .3), size=(800, 800)) def goback(self): sm.current = "Home" def findTarget(self): self.popup.open() self.br = BroadcastReceiver(self.onReceive, actions=['main'], myFilter = self.BluetoothDevice.ACTION_FOUND) self.br.start() self.myBTA.startDiscovery() def onReceive(self, context, intent): action = intent.getAction(); if (self.BluetoothDevice.ACTION_FOUND == action): extras = intent.getParcelableExtra(self.BluetoothDevice.EXTRA_DEVICE) device = cast('android.bluetooth.BluetoothDevice', extras) deviceName = device.getAddress() if deviceName == user.target: self.eliminate.disabled = False self.eliminate.color = (1,0,0,1) self.popup.dismiss() self.popup1.open() self.br.stop() def eliminateUser(self): query = retrieve("SELECT target FROM users WHERE bt_ID = '%s'" % (user.target)) update("UPDATE users SET target = '',status = '0' WHERE bt_ID = '%s'" % (user.target)) user.target = query[0] print user.target, '**************************************' create("UPDATE users SET target = '%s' WHERE uid = '%s'" % (user.target, user.uid)) updateUser() query1 = retrieve("SELECT firstname,lastname FROM users WHERE bt_ID = '%s'" % (user.target)) tfirstname, tlastname = query1[0] self.status.text = str("Your Current Target is %s %s" % (tfirstname, tlastname))
class MWindow(BoxLayout): def show_generate(self): content = SaveDialog(save=self.generate_design, cancel=self.dismiss_popup) self._popup = Popup(title="Save caDNAno design", content=content, size_hint=(0.9, 0.9)) self._popup.open() def generate_design(self, fpath, filename): print("_" * 80) print("trying to generate_design") design = [] hex_grid = self.ids.hex_grid scaffold_path = hex_grid.scaffold_path print("!" * 80) from pprint import pprint pprint(scaffold_path) helix = scaffold_path[0] path = scaffold_path[1::] path.append(None) for next_helix in path: node = helix.node_to id_1 = node.helix_to_slot(helix) + 1 id_2 = node.helix_to_slot(helix) - 1 c_helix_1 = node.number_to_helix(id_1) c_helix_2 = node.number_to_helix(id_2) if c_helix_1 and c_helix_1 != next_helix: if c_helix_1.node_from == node: print(helix.vvhelix_id, "->", c_helix_1.vvhelix_id) design.append([c_helix_1.vvhelix_id, helix.vvhelix_id]) if c_helix_2 and c_helix_2 != next_helix: if c_helix_2.node_from == node: print(helix.vvhelix_id, "->", c_helix_2.vvhelix_id) design.append([c_helix_2.vvhelix_id, helix.vvhelix_id]) helix = next_helix print("-" * 80) print("final design is:") # TODO: CHECK THIS... from pprint import pprint print("*" * 80) pprint(design) print("*" * 80) # create caDNAno file # construct generator to produce meaningful helix positions helix_position = generate_even_helix_position_sq() helices = [] hex_grid = self.ids.hex_grid n_helix = int(hex_grid.vvhelix_id / 2) # reduce(max, map(max, design)) / 2 + 1 # change to be reasonable for i in range(n_helix): c, r = next(helix_position) helices.append( vhelix(num=2 * i, column=c, row=r, segment_length=37, overhang=3)) # interconnect the freshly generated helices interconnect_helices(helices) # break all staples in the middle for h in helices: break_staple(h, 27) # provide the linkage for the staples interconnect_staples(helices, design) # dump the json to a file cadnano_file = {"vstrands": helices, "name": "Created by M.Matthies"} import json with open(os.path.join(fpath, filename), "w+") as out_file: print(filename) out_file.write(json.dumps(cadnano_file)) # self.dismiss_popup() def dismiss_popup(self): self._popup.dismiss() def show_load(self): content = LoadDialog(load=self.load_design, cancel=self.dismiss_popup) self._popup = Popup(title="Load file", content=content, size_hint=(0.9, 0.9)) self._popup.open() def load_design(self, path, filename): hex_canvas = self.ids.hex_grid # with open(os.path.join(path, filename[0])) as in_file: with open(filename[0]) as in_file: in_des = eval(in_file.read()) for helix_pair in in_des: node_from_id, node_to_id = helix_pair node_from = hex_canvas.grid[node_from_id[0]][node_from_id[1]] node_to = hex_canvas.grid[node_to_id[0]][node_to_id[1]] with node_from.canvas: Color(1, 1, 1, 1) Ellipse(pos=(node_from.center[0] - 6, node_from.center[1] - 6), size=(12, 12)) with node_to.canvas: Color(1, 1, 1, 1) Ellipse(pos=(node_to.center[0] - 6, node_to.center[1] - 6), size=(12, 12)) vvh = VVHelix(from_node=node_from, to_node=node_to, vvhelix_id=hex_canvas.vvhelix_id) hex_canvas.scaffold_path.append(vvh) hex_canvas.vvhelix_id += 2 hex_canvas.add_widget(vvh) from pprint import pprint pprint(hex_canvas.scaffold_path) self.dismiss_popup() def show_save(self): content = SaveDialog(save=self.save_design, cancel=self.dismiss_popup) self._popup = Popup(title="Save file", content=content, size_hint=(0.9, 0.9)) self._popup.open() def save_design(self, path, filename): design_to_save = [] for helix in self.ids.hex_grid.scaffold_path: entry = [helix.node_from.grid_id, helix.node_to.grid_id] design_to_save.append(entry) with open(os.path.join(path, filename), "w+") as out_file: out_file.write(str(design_to_save)) self.dismiss_popup() def clear_canvas(self): hg = self.ids.hex_grid hg.clean()
class ConfigView(Screen): Builder.load_file(CONFIG_VIEW_KV) # file save/load loaded = BooleanProperty(False) loadfile = ObjectProperty(None) savefile = ObjectProperty(None) text_input = ObjectProperty(None) writeStale = BooleanProperty(False) track_manager = ObjectProperty(None) # List of config views configViews = [] menu = None rc_config = None script_view = None _settings = None base_dir = None _databus = None def __init__(self, **kwargs): super(ConfigView, self).__init__(**kwargs) self._status_pump = kwargs.get('status_pump') self._databus = kwargs.get('databus') self.rc_config = kwargs.get('rcpConfig', None) self.rc_api = kwargs.get('rc_api', None) self._settings = kwargs.get('settings') self.base_dir = kwargs.get('base_dir') self.register_event_type('on_config_updated') self.register_event_type('on_channels_updated') self.register_event_type('on_config_written') self.register_event_type('on_tracks_updated') self.register_event_type('on_config_modified') self.register_event_type('on_read_config') self.register_event_type('on_write_config') self._sn = '' if self.rc_config: self._sn = self.rc_config.versionConfig.serial self.ids.menu.bind(selected_node=self.on_select_node) def on_config_written(self, *args): self.writeStale = False def on_config_modified(self, *args): self.writeStale = True def update_runtime_channels(self, system_channels): for view in self.configViews: channelWidgets = list(kvquery(view, __class__=ChannelNameSpinner)) for channelWidget in channelWidgets: channelWidget.dispatch('on_channels_updated', system_channels) def on_channels_updated(self, runtime_channels): self.update_runtime_channels(runtime_channels) def on_config_updated(self, config, force_reload=False): if config.versionConfig.serial != self._sn or force_reload: # New device or we need to redraw, reload everything # Our config object is the same object with new values, so we need to copy our value self._sn = copy(config.versionConfig.serial) self._clear() self.init_screen() else: self.rc_config = config self.update_config_views() def _clear(self): nodes = [] # Building an array because if we remove while iterating we end up skipping things for node in self.ids.menu.iterate_all_nodes(): nodes.append(node) for node in nodes: self.ids.menu.remove_node(node) self.ids.menu.clear_widgets() del (self.configViews[:]) self.ids.content.clear_widgets() def on_track_manager(self, instance, value): self.update_tracks() def on_loaded(self, instance, value): self.update_config_views() self.update_tracks() def on_writeStale(self, instance, value): self.updateControls() def _reset_stale(self): self.writeStale = False def update_config_views(self): config = self.rc_config if config and self.loaded: for view in self.configViews: view.dispatch('on_config_updated', config) self._reset_stale() def init_screen(self): self.createConfigViews() def on_enter(self): if not self.loaded: Clock.schedule_once(lambda dt: self.init_screen()) def createConfigViews(self): def attach_node(text, n, view_builder): tree = self.ids.menu label = LinkedTreeViewLabel(text=text) label.view_builder = view_builder label.color_selected = ColorScheme.get_dark_primary() return tree.add_node(label, n) def create_scripting_view(capabilities): script_view = LuaScriptingView(capabilities, rc_api=self.rc_api) self.script_view = script_view return script_view runtime_channels = self._settings.runtimeChannels default_node = attach_node( 'Race Tracks', None, lambda: TrackConfigView(status_pump=self._status_pump, databus=self._databus, rc_api=self.rc_api, settings=self._settings, track_manager=self.track_manager)) attach_node('GPS', None, lambda: GPSChannelsView()) attach_node('Race Timing', None, lambda: LapStatsView()) if self.rc_config.capabilities.has_analog: attach_node('Analog Sensors', None, lambda: AnalogChannelsView(channels=runtime_channels)) if self.rc_config.capabilities.has_timer: attach_node('Pulse/RPM Sensors', None, lambda: PulseChannelsView(channels=runtime_channels)) if self.rc_config.capabilities.has_gpio: attach_node('Digital In/Out', None, lambda: GPIOChannelsView(channels=runtime_channels)) attach_node('Accel/Gyro', None, lambda: ImuChannelsView(rc_api=self.rc_api)) if self.rc_config.capabilities.has_pwm: attach_node( 'Pulse/Analog Out', None, lambda: AnalogPulseOutputChannelsView(channels=runtime_channels)) attach_node('CAN Bus', None, lambda: CANConfigView()) if self.rc_config.capabilities.has_can_channel: attach_node( 'CAN Mapping', None, lambda: CANChannelsView(settings=self._settings, channels=runtime_channels, base_dir=self.base_dir)) attach_node( 'OBDII', None, lambda: OBD2ChannelsView(channels=runtime_channels, base_dir=self.base_dir)) attach_node( 'Wireless', None, lambda: WirelessConfigView( self.base_dir, self.rc_config, self.rc_config.capabilities)) attach_node('Telemetry', None, lambda: TelemetryConfigView(self.rc_config.capabilities)) if self.rc_config.capabilities.has_script: node_name = 'Scripting' else: node_name = 'Logs' attach_node(node_name, None, lambda: create_scripting_view(self.rc_config.capabilities)) if self.rc_api.is_firmware_update_supported(): from autosportlabs.racecapture.views.configuration.rcp.firmwareupdateview import FirmwareUpdateView attach_node( 'Firmware', None, lambda: FirmwareUpdateView(rc_api=self.rc_api, settings=self._settings)) self.ids.menu.select_node(default_node) self.update_runtime_channels(runtime_channels) self.update_tracks() self.loaded = True def show_node(self, node): view = node.view if not view: view = node.view_builder() self.configViews.append(view) view.bind(on_config_modified=self.on_config_modified) node.view = view if self.loaded: if self.rc_config: view.dispatch('on_config_updated', self.rc_config) if self.track_manager: view.dispatch('on_tracks_updated', self.track_manager) if view.get_parent_window() is None: Clock.schedule_once(lambda dt: self.ids.content.add_widget(view)) def on_select_node(self, instance, value): if not value: return # ensure that any keyboard is released try: self.ids.content.get_parent_window().release_keyboard() except: pass self.ids.content.clear_widgets() Clock.schedule_once(lambda dt: self.show_node(value)) def updateControls(self): Logger.debug("ConfigView: data is stale: " + str(self.writeStale)) write_button = self.ids.write write_button.disabled = not self.writeStale write_button.pulsing = self.writeStale Clock.schedule_once( lambda dt: HelpInfo.help_popup( 'rc_write_config', self, arrow_pos='left_mid'), 1.0) def update_tracks(self): track_manager = self.track_manager if track_manager and self.loaded: for view in self.configViews: view.dispatch('on_tracks_updated', track_manager) def on_tracks_updated(self, track_manager): self.track_manager = track_manager def on_read_config(self, instance, *args): pass def on_write_config(self, instance, *args): pass def readConfig(self): if self.writeStale == True: popup = None def _on_answer(instance, answer): if answer: self.dispatch('on_read_config', None) popup.dismiss() popup = confirmPopup( 'Confirm', 'Configuration Modified - Continue Loading?', _on_answer) else: self.dispatch('on_read_config', None) def writeConfig(self): if self.rc_config.loaded: self.dispatch('on_write_config', None) else: alertPopup('Warning', 'Please load or read a configuration before writing') def openConfig(self): if self.writeStale: popup = None def _on_answer(instance, answer): if answer: self.doOpenConfig() popup.dismiss() popup = confirmPopup( 'Confirm', 'Configuration Modified - Open Configuration?', _on_answer) else: self.doOpenConfig() def set_config_file_path(self, path): self._settings.userPrefs.set_pref('preferences', 'config_file_dir', path) def get_config_file_path(self): return self._settings.userPrefs.get_pref('preferences', 'config_file_dir') def doOpenConfig(self): content = LoadDialog(ok=self.load, cancel=self.dismiss_popup, filters=['*' + RCP_CONFIG_FILE_EXTENSION], user_path=self.get_config_file_path()) self._popup = Popup(title="Load file", content=content, size_hint=(0.9, 0.9)) self._popup.open() def saveConfig(self): if self.rc_config.loaded: content = SaveDialog(ok=self.save, cancel=self.dismiss_popup, filters=['*' + RCP_CONFIG_FILE_EXTENSION], user_path=self.get_config_file_path()) self._popup = Popup(title="Save file", content=content, size_hint=(0.9, 0.9)) self._popup.open() else: alertPopup('Warning', 'Please load or read a configuration before saving') def load(self, instance): self.set_config_file_path(instance.path) self.dismiss_popup() try: selection = instance.selection filename = selection[0] if len(selection) else None if filename: with open(filename) as stream: rcpConfigJsonString = stream.read() self.rc_config.fromJsonString(rcpConfigJsonString) self.rc_config.stale = True self.on_config_updated(self.rc_config, force_reload=True) self.on_config_modified() else: alertPopup('Error Loading', 'No config file selected') except Exception as detail: alertPopup('Error Loading', 'Failed to Load Configuration:\n\n' + str(detail)) Logger.exception('ConfigView: Error loading config: ' + str(detail)) def save(self, instance): def _do_save_config(filename): if not filename.endswith(RCP_CONFIG_FILE_EXTENSION): filename += RCP_CONFIG_FILE_EXTENSION with open(filename, 'w') as stream: configJson = self.rc_config.toJsonString() stream.write(configJson) self.set_config_file_path(instance.path) self.dismiss_popup() config_filename = instance.filename if len(config_filename): try: config_filename = os.path.join(instance.path, config_filename) if os.path.isfile(config_filename): def _on_answer(instance, answer): if answer: _do_save_config(config_filename) popup.dismiss() popup = confirmPopup('Confirm', 'File Exists - overwrite?', _on_answer) else: _do_save_config(config_filename) except Exception as detail: alertPopup('Error Saving', 'Failed to save:\n\n' + str(detail)) Logger.exception('ConfigView: Error Saving config: ' + str(detail)) def dismiss_popup(self, *args): self._popup.dismiss()
class AssetsEditorPopupAdd(): # 0.5.0 TEST EVENTS def on_mouse_pos(self, window, pos): for item in self.leftBox.children: print("MOUSE EVENTS >>>>>>>>" + item.__class__.__name__) if item.__class__.__name__ == "Button": if item.collide_point(*pos): print('POINT :::>>:' + item.text) item.background_color =(self.engineConfig.getThemeTextColor()) item.color = (self.engineConfig.getThemeCustomColor('engineBtnsBackground')) else: item.color = (self.engineConfig.getThemeTextColor()) item.background_color = (self.engineConfig.getThemeCustomColor('engineBtnsBackground')) # do something here def __init__(self, **kwargs): self.engineConfig = kwargs.get("engineConfig") self.engineRoot = kwargs.get("engineRoot") self.currentAsset = kwargs.get("currentAsset") Window.bind(mouse_pos=self.on_mouse_pos) self.operationStatus = True self.isFreeRigthBox = True self.box = BoxLayout(orientation="horizontal") self.leftBox = BoxLayout(orientation="vertical") self.imageResourceGUIBox = BoxLayout(orientation="vertical") print("DEBUG", platform) if platform == 'linux': drives = psutil.disk_partitions() if platform == 'win': drives = ['%s:' % d for d in string.ascii_uppercase if os.path.exists('%s:' % d)] for item in drives: print(item) self.drivesChooseBox = BoxLayout(size_hint=(1, None), height=40,) for item in drives: if platform == 'win': self.drivesChooseBox.add_widget(Button( text=item + '/', on_press=partial(self.setFileBrowserPath), color=(self.engineConfig.getThemeTextColor()), size_hint=(1, None), height=65, background_normal= '', background_color=(self.engineConfig.getThemeCustomColor('engineBtnsBackground')) )) print(" drive: ", item) elif platform == 'linux' or True: self.drivesChooseBox.add_widget(Button( text=item.mountpoint , on_press=partial(self.setFileBrowserPath), color=(self.engineConfig.getThemeTextColor()), size_hint=(1, None), height=65, background_normal= '', background_color=(self.engineConfig.getThemeCustomColor('engineBtnsBackground')) )) print(" drive: ", item) self.imageResourceGUIBox.add_widget(self.drivesChooseBox) if platform == 'win': self.fileBrowser = FileChooserListView(# select_string='Select', dirselect: True # path='projects/' + self.engineConfig.currentProjectName + '/data/', filters=['*.png', '*.jpg'], path= drives[0] + '/', size_hint=(1,3), dirselect= True, on_submit=self.load_from_filechooser ) elif platform == 'linux' or True: self.fileBrowser = FileChooserListView(# select_string='Select', dirselect: True # path='projects/' + self.engineConfig.currentProjectName + '/data/', filters=['*.png', '*.jpg'], path= drives[0].mountpoint + '/', size_hint=(1,3), dirselect= True, on_submit=self.load_from_filechooser ) self.imageResourceGUIBox.add_widget(self.fileBrowser) self.fileBrowser.bind(selection=partial(self.load_from_filechooser)) self.imageResourceGUIBox.add_widget(Label(text='Application assets pack path' , size_hint=(1, None), height=40 ), ) self.selectedPathLabel = Label(text='...') self.imageResourceGUIBox.add_widget(self.selectedPathLabel) self.assetName = TextInput( text='MyAssets1', foreground_color=(0,1,1, 1), size_hint=(1, None), height=40) with self.assetName.canvas.before: Color(self.engineConfig.getThemeCustomColor('background')[0], self.engineConfig.getThemeCustomColor('background')[1], self.engineConfig.getThemeCustomColor('background')[2], self.engineConfig.getThemeCustomColor('background')[3]) self.assetName.rect = Rectangle(size=self.assetName.size, pos=self.assetName.pos) def update_rect(instance, value): instance.rect.pos = instance.pos instance.rect.size = instance.size self.imageResourceGUIBox.add_widget(self.assetName) # self.assetName.bind(pos=update_rect, size=update_rect) self.assetName.foreground_color = (1,1,1,1) self.commandBtn = Button(text='Add selected image', color=(self.engineConfig.getThemeTextColor()), size_hint=(1, None), height=60, background_normal= '', background_color=(self.engineConfig.getThemeCustomColor('engineBtnsBackground')) ) #on_press=partial(self.createImageAssets)) self.commandBtn.bind(on_press=partial(self.createImageAssets)) self.imageResourceGUIBox.add_widget(self.commandBtn) self.leftBox.add_widget(Label(text='Application assets package operation.')) self.cancelBtn = Button(text='Cancel', color=(self.engineConfig.getThemeTextColor()), size_hint=(1, None), height=70, background_normal= '', background_color=(self.engineConfig.getThemeCustomColor('engineBtnsBackground'))) self.previewBox = BoxLayout(size_hint=(1,None), height=250) self.previewPicture = AsyncImage(source="", size_hint=(1, 1)) self.previewBox.add_widget(Label(text='Preview Box')) self.previewBox.add_widget(self.previewPicture) self.imageResourceGUIBox.add_widget(self.previewBox) self.box.add_widget(self.leftBox) # Add button - ImageResource self.addImageRes = Button(markup=True, text='[b]Add Image Resource[b]', color=(self.engineConfig.getThemeTextColor()), size_hint=(1, None), height=60, background_normal= '', background_color=(self.engineConfig.getThemeCustomColor('engineBtnsBackground'))) self.leftBox.add_widget(self.addImageRes) # Others - Fonts self.addFontRes = Button(markup=True, text='[b]Add Font Resource[b]', color=(self.engineConfig.getThemeTextColor()), size_hint=(1, None), height=60, background_normal= '', background_color=(self.engineConfig.getThemeCustomColor('engineBtnsBackground'))) # Add JSON Data - JSONResource self.addJSONResBtn = Button(markup=True, text='[b]Add JSON DATA Resource[b]', color=(self.engineConfig.getThemeTextColor()), size_hint=(1, None), height=60, background_normal= '', background_color=(self.engineConfig.getThemeCustomColor('engineBtnsBackground'))) self.leftBox.add_widget(self.addJSONResBtn) self.leftBox.add_widget(self.addFontRes) self.leftBox.add_widget(self.cancelBtn) self.previewFont = Label( size_hint=(1, 1), markup=True, font_size=50, text="Font [b]Bold[/b]!") _local = 'CrossK ' + self.engineConfig.getVersion() + ' Assets Editor' self.popup = Popup(title=_local , content=self.box, auto_dismiss=False) self.cancelBtn.bind(on_press=self.popup.dismiss) self.addImageRes.bind(on_press=lambda a:self.showImageAssetGUI()) self.addFontRes.bind(on_press=lambda a:self.showFontAssetGUI()) self.addJSONResBtn.bind(on_press=lambda a:self.showJSONAssetGUI()) self.popup.open() def showImageAssetGUI(self): # no prepare it si initial if self.isFreeRigthBox == True: self.box.add_widget(self.imageResourceGUIBox) self.isFreeRigthBox = False self.previewPicture.size_hint = (1,1) self.previewFont.size_hint = (0,0) def showFontAssetGUI(self): if self.isFreeRigthBox == True: # prepare self.fileBrowser.filters = ['*.ttf'] self.commandBtn.text = 'Add Font Family' self.commandBtn.unbind(on_press=partial(self.createImageAssets)), self.commandBtn.bind(on_press=partial(self.createFontAssets)) self.previewPicture.size_hint = (0,0) self.previewFont.size_hint = (1,1) self.box.add_widget(self.imageResourceGUIBox) self.isFreeRigthBox = False def showJSONAssetGUI(self): if self.isFreeRigthBox == True: # prepare self.fileBrowser.filters = ['*.json'] self.commandBtn.text = 'Add JSON Object Data' self.commandBtn.unbind(on_press=partial(self.createImageAssets)), self.commandBtn.bind(on_press=partial(self.createJSONAssets)) self.previewPicture.size_hint = (0,0) # self.previewFont.size_hint = (0,0) self.box.add_widget(self.imageResourceGUIBox) self.isFreeRigthBox = False def resolvePathFolder(self): ASSETPACK_PATH = os.path.abspath( os.path.join(os.path.dirname(__file__), '../../projects/' + self.engineConfig.currentProjectName + "/data/") ) if not os.path.exists(ASSETPACK_PATH): print("MAKE_ASSETPACK_PATH") os.mkdir(ASSETPACK_PATH) else: print('ASSETPACK_EXIST') def resolveAssetPathFolder(self, typeOfAsset): CURRENT_ASSETPACK_PATH = os.path.abspath( os.path.join(os.path.dirname(__file__), '../../projects/' + self.engineConfig.currentProjectName + "/data/" + self.assetName.text) ) collectExt = '' local = self.fileBrowser.selection[0][::-1] for item in local: if item == '.': print("Create Image Resource -> Break EXT = ", collectExt) break else: collectExt += item; collectExt = collectExt[::-1] # print(collectExt) if not os.path.exists(CURRENT_ASSETPACK_PATH): print("MAKE_ASSETS_PACK_DIR") os.mkdir(CURRENT_ASSETPACK_PATH) else: if self.currentAsset == None: print("SOMETHIND WRONG - ASSETS ALREADY EXIST") getMessageBoxYesNo( message="Asset reference path with this name already exist. Please use some different name.", msgType="OK") #callback=wtf) return None self.operationStatus = False print("Assets pack write meta data...") copyfile(self.fileBrowser.selection[0], CURRENT_ASSETPACK_PATH + '/' + str(self.assetName.text) + '.' + collectExt) self.assetsStore = JsonStore(self.engineConfig.currentProjectAssetPath+ '/assets.json') localElements = self.assetsStore.get('assetsComponentArray')['elements'] asset = { 'name': self.assetName.text, 'type': typeOfAsset, 'ext': collectExt, 'source': CURRENT_ASSETPACK_PATH + '/' + str(self.assetName.text) + '.' + collectExt, 'path': 'projects/' + self.engineConfig.currentProjectName + "/data/"+ str(self.assetName.text) + "/" + str(self.assetName.text) + "." + collectExt, 'version': self.engineConfig.getVersion() } # Check it if exist localCheckDouble = False for checkItem in localElements: if checkItem['name'] == asset['name']: localCheckDouble = True getMessageBoxYesNo( message="Asset reference with this name already exist. Please use some different name.", msgType="OK") #callback=wtf) if localCheckDouble == False: localElements.append(asset) self.assetsStore.put('assetsComponentArray', elements=localElements) self.engineRoot.resourceGUIContainer.selfUpdate() def createImageAssets(self, instance): if self.operationStatus == True: self.resolvePathFolder() self.resolveAssetPathFolder('ImageResource') self.popup.dismiss() def createFontAssets(self, instance): if self.operationStatus == True: self.resolvePathFolder() self.resolveAssetPathFolder('FontResource') self.popup.dismiss() def createJSONAssets(self, instance): if self.operationStatus == True: self.resolvePathFolder() self.resolveAssetPathFolder('JSONResource') self.popup.dismiss() def load_from_filechooser(self, instance , selectedData): print("Selected data: ", selectedData) #self.load(self.fileBrowser.path, self.fileBrowser.selection) localHandler = self.fileBrowser.selection[0].replace(self.fileBrowser.path, '') self.selectedPathLabel.text = localHandler # check type assets print(">>", self.fileBrowser.filters) if self.fileBrowser.filters[0] == '*.png' or self.fileBrowser.filters[0] == '*.jpg': self.previewPicture.source=self.fileBrowser.selection[0] # JSON Nidza if '.json' in localHandler: self.imageResourceGUIBox.remove_widget(self.previewBox) testJSONNidzaLOader = JsonN( assetsPath=self.fileBrowser.selection[0], currentContainer=self.imageResourceGUIBox, engineRoot=self.engineRoot ) def setFileBrowserPath(self, instance): self.fileBrowser.path = instance.text print( 'setFileBrowserPath: ' , instance.text)
class ReverbApp(App): _hue = NumericProperty(1.0) _saturation = NumericProperty(1.0) _brightness = NumericProperty(1.0) lamp_is_on = BooleanProperty(True) def _get_hue(self): return self._hue def _set_hue(self, value): if fabs(self.hue - value) > TOLERANCE: self._hue = value def _get_saturation(self): return self._saturation def _set_saturation(self, value): if fabs(self.saturation - value) > TOLERANCE: self._saturation = value def _get_brightness(self): return self._brightness def _set_brightness(self, value): if fabs(self.brightness - value) > TOLERANCE: self._brightness = value hue = AliasProperty(_get_hue, _set_hue, bind=['_hue']) saturation = AliasProperty(_get_saturation, _set_saturation, bind=['_saturation']) brightness = AliasProperty(_get_brightness, _set_brightness, bind=['_brightness']) gpio17_pressed = BooleanProperty(False) #right button gpio22_pressed = BooleanProperty(False) #2nd right button gpio23_pressed = BooleanProperty(False) #2nd left button gpio27_pressed = BooleanProperty(False) #left button def on_start(self): self.lamp_driver = LampDriver() Clock.schedule_once(lambda dt: self._update_leds(), 0.01) self.set_up_GPIO_and_IP_popup() def on_hue(self, instance, value): Clock.schedule_once(lambda dt: self._update_leds(), 0.01) def on_saturation(self, instance, value): Clock.schedule_once(lambda dt: self._update_leds(), 0.01) def on_brightness(self, instance, value): Clock.schedule_once(lambda dt: self._update_leds(), 0.01) def on_lamp_is_on(self, instance, value): Clock.schedule_once(lambda dt: self._update_leds(), 0.01) def _update_leds(self): self.lamp_driver.set_lamp_state(self._hue, self._saturation, self._brightness, self.lamp_is_on) def set_up_GPIO_and_IP_popup(self): self.pi = pigpio.pi() self.pi.set_mode(17, pigpio.INPUT) self.pi.set_mode(22, pigpio.INPUT) self.pi.set_mode(23, pigpio.INPUT) self.pi.set_mode(27, pigpio.INPUT) self.pi.set_pull_up_down(17, pigpio.PUD_UP) self.pi.set_pull_up_down(22, pigpio.PUD_UP) self.pi.set_pull_up_down(23, pigpio.PUD_UP) self.pi.set_pull_up_down(27, pigpio.PUD_UP) Clock.schedule_interval(self._poll_GPIO, 0.05) self.popup = Popup(title='IP Addresses', content=Label(text='IP ADDRESS WILL GO HERE'), size_hint=(1, 1), auto_dismiss=False) self.popup.bind(on_open=self.update_popup_ip_address) def update_popup_ip_address(self, instance): interface = "wlan0" ipaddr = lampi_util.get_ip_address(interface) instance.content.text = "{}: {}".format(interface, ipaddr) def on_gpio17_pressed(self, instance, value): if value: self.popup.open() else: self.popup.dismiss() def on_gpio22_pressed(self, instance, value): if value: self.popup.open() else: self.popup.dismiss() def on_gpio23_pressed(self, instance, value): if value: self.popup.open() else: self.popup.dismiss() def on_gpio27_pressed(self, instance, value): if value: self.popup.open() else: self.popup.dismiss() def _poll_GPIO(self, dt): self.gpio17_pressed = not self.pi.read(17) self.gpio22_pressed = not self.pi.read(22) self.gpio23_pressed = not self.pi.read(23) self.gpio27_pressed = not self.pi.read(27)
class ApvMainScreen(Screen): def __init__(self, **kwargs): super(ApvMainScreen, self).__init__(**kwargs) self.__master_dict = {'Listing': None, 'Website': None, 'Email': None, 'Username': None, 'Password': None} self.__win = 'C:\\APV\\Private.xlsx' self.__linux = '/home/' + str(os.getlogin()) + './APV/Private.xlsx' self.__mac = '/home/' + str(os.getlogin()) + './APV/Private.xlsx' # wrong self.__encryption_key = None self._popup = None def open_load_file_dialog(self): content = LoadDialog(load = self.load, cancel = self.dismiss_popup) self._popup = Popup(title = "Load file", content = content, size_hint = (0.9, 0.9)) self._popup.open() def open_save_file_dialog(self): content = SaveDialog(save = self.save, cancel = self.dismiss_popup) self._popup = Popup(title = "Save file", content = content, size_hint=(0.9, 0.9)) self._popup.open() def load(self, path, filename): try: if sys.platform == 'win32': with open(os.path.join(path, filename[0])) as stream: self.ids.viewport_output.text = stream.read() elif sys.platform == 'linux2': with open(os.path.join(path, filename[0])) as stream: self.ids.viewport_output.text = stream.read() elif sys.platform == 'darwin': with open(os.path.join(path, filename[0])) as stream: self.ids.viewport_output.text = stream.read() self.dismiss_popup() except OSError as exception: raise OSError("%s: %s" % (exception.strerror)) def save(self, path, filename): with open(os.path.join(path, filename), 'w') as stream: stream.write(self.ids.viewport_output.text) self.dismiss_popup() def dismiss_popup(self): self._popup.dismiss() def set_listing_text(self): if sys.platform == 'linux2': __listing = self.ids.listing_input.text self.__master_dict['Listing'] = __listing self.ids.listing_input.hint_text = 'Listing: ' elif sys.platform == 'win32': __listing = self.ids.listing_input.text self.__master_dict['Listing'] = __listing self.ids.listing_input.hint_text = 'Listing: ' elif sys.platform == 'darwin': __listing = self.ids.listing_input.text self.__master_dict['Listing'] = __listing self.ids.listing_input.hint_text = 'Listing: ' def set_website_text(self): if sys.platform == 'linux2': __website = self.ids.website_input.text self.__master_dict['Website'] = __website self.ids.website_input.hint_text = 'Website: ' elif sys.platform == 'win32': __website = self.ids.website_input.text self.__master_dict['Website'] = __website self.ids.website_input.hint_text = 'Website: ' elif sys.platform == 'darwin': __website = self.ids.website_input.text self.__master_dict['Website'] = __website self.ids.website_input.hint_text = 'Website: ' def set_email_text(self): if sys.platform == 'linux2': __email = self.ids.email_input.text self.__master_dict['Email'] = __email self.ids.email_input.hint_text = 'Email Address: ' elif sys.platform == 'win32': __email = self.ids.email_input.text self.__master_dict['Email'] = __email self.ids.email_input.hint_text = 'Email Address: ' elif sys.platform == 'darwin': __email = self.ids.email_input.text self.__master_dict['Email'] = __email self.ids.email_input.hint_text = 'Email Address: ' def set_user_text(self): if sys.platform == 'linux2': __usr = self.ids.username_input.text self.__master_dict['Username'] = __usr self.ids.username_input.hint_text = 'Username: '******'win32': __usr = self.ids.username_input.text self.__master_dict['Username'] = __usr self.ids.username_input.hint_text = 'Username: '******'darwin': __usr = self.ids.username_input.text self.__master_dict['Username'] = __usr self.ids.username_input.hint_text = 'Username: '******'linux2': __password = self.ids.password_input.text self.__master_dict['Password'] = __password self.append_and_write_dataframes(self.__linux) self.ids.password_input.hint_text = 'Password: '******'win32': __password = self.ids.password_input.text self.__master_dict['Password'] = __password self.append_and_write_dataframes(self.__win) self.ids.password_input.hint_text = 'Password: '******'darwin': __password = self.ids.password_input.text self.__master_dict['Password'] = __password self.append_and_write_dataframes(self.__mac) self.ids.password_input.hint_text = 'Password: '******'Accounts') df1 = pd.DataFrame({'Listing': [self.__master_dict['Listing']], 'Website': [self.__master_dict['Website']], 'Email': [self.__master_dict['Email']], 'Username': [self.__master_dict['Username']], 'Password': [self.__master_dict['Password']]}) df3 = df.append(df1) df3 = df3[['Listing', 'Website', 'Email', 'Username', 'Password']] writer = pd.ExcelWriter(path, engine='xlsxwriter') df3.to_excel(writer, sheet_name='Accounts') workbook = writer.book worksheet1 = writer.sheets['Accounts'] worksheet1.set_column(1, 5, 35) writer.save() self.__master_dict.clear()
class builder(App): theme_cls = ThemeManager() sm=ScreenManager() loc='0' def build(self): self.r=first_screen() if ((int(time.strftime('%Y'))<2020) & (int(time.strftime('%m'))<12)): return self.sm return term_over() def set_popup_screen(self): self.k.open() def resize_content_layout(self, *largs): self.k.gl_content.height = self.k1.height def on_pause(self): return True def callback_for_menu_items(self, *args): print(args[0]) self.k1.ids.h.text=args[0] def pop_load(self): self.p=Popup(title='Loading',title_color=[0,0,0,1],background='',size_hint=[0.75,0.2],auto_dismiss=False) b=MDLabel(text='please wait loading',halign='center') self.p.add_widget(b) self.p.open() return def ref(self): network.refresh_papers() self.papers=network.get_papers() self.paperIds=list(self.papers.keys()) self.paperIds.remove('eenadu') self.paperIds.remove('sakshi') self.paperIds.remove('Jyothi') self.paper_items=[{ "viewclass": "MDMenuItem", "text": 'reload', "callback": self.showPaper, }] for i in self.paperIds: item={ "viewclass": "MDMenuItem", "text": i, "callback": self.showPaper, } self.paper_items.append(item) self.p.dismiss() def showPaper(self,*args): paper=args[0] if (paper=='reload'): threading.Thread(target=self.ref,args=()).start() self.pop_load() return webbrowser.open(self.papers[paper]) def on_location(self, **kwargs): self.gps_location = '='.join(['{}={}'.format(k, v) for k, v in kwargs.items()]) self.count+=1 st=self.gps_location.split('=') self.loc=st[1]+','+st[3] if (self.count==3): plyer.gps.stop() k=threading.Thread(target=network.do_all,args=(plyer.uniqueid.id,time.strftime('%d-%m-%y-%T'),self.loc,'0','0','0','0')) k.start() def on_status(self, stype, status): pass def on_start(self): self.count=0 try: plyer.gps.configure(on_location=self.on_location,on_status=self.on_status) except Exception: pass plyer.gps.start(100,0) self.k=MDBottomSheet() self.k1=ContentForAnimCard() value=['guntur','visakhapatnam','hyderabad','vijayawada','delhi','mumbai'] self.menu_items=[{ "viewclass": "MDMenuItem", "text": 'guntur', "callback": self.callback_for_menu_items, },{ "viewclass": "MDMenuItem", "text": 'visakhapatnam', "callback": self.callback_for_menu_items, },{ "viewclass": "MDMenuItem", "text": 'hyderabad', "callback": self.callback_for_menu_items, },{ "viewclass": "MDMenuItem", "text": 'vijayawada', "callback": self.callback_for_menu_items, },{ "viewclass": "MDMenuItem", "text": 'delhi', "callback": self.callback_for_menu_items, },{ "viewclass": "MDMenuItem", "text": 'mumbai', "callback": self.callback_for_menu_items, } ] self.papers=network.get_papers() self.paperIds=list(self.papers.keys()) self.paperIds.remove('eenadu') self.paperIds.remove('sakshi') self.paperIds.remove('Jyothi') self.paper_items=[{ "viewclass": "MDMenuItem", "text": 'reload', "callback": self.showPaper, }] for i in self.paperIds: item={ "viewclass": "MDMenuItem", "text": i, "callback": self.showPaper, } self.paper_items.append(item) self.sm.add_widget(self.r) self.k.gl_content.add_widget(self.k1) Clock.schedule_once(self.resize_content_layout, 0)
class Layout_candidat(GridLayout): def build(self,nom,prenom,nuance,sortant,personalite,dico_envoi,dico_score,dico_scrutin_nuance_proba,liste_oui,liste_petit_effectif): global compteur #Pour pouvoir faire les explications on a besoin de stoquer dans la classe les données self.nom = nom self.liste_oui = liste_oui self.liste_petit_effectif = liste_petit_effectif self.prenom = prenom self.nuance = nuance self.sortant = sortant self.dico_envoi = dico_envoi if self.sortant: """ sql_command = "SELECT uid FROM Elu WHERE nom = '{}' AND prenom = '{}'".format(self.nom,self.prenom) cursor.execute(sql_command) for item in cursor: uid_elu = item[0] self.score_affinité,self.dico_vote_elu = make_score_sortant(uid_elu,self.dico_envoi) """ pass else: pass self.score_affinite = dico_score[self.nuance] self.score_affinite = dico_score[self.nuance] #print(self.liste_oui) self.dico_candidat = 0 self.dico_scrutin_nuance_proba = dico_scrutin_nuance_proba self.personalite = personalite self.cols = 1 #print(self.score_affinite) self.dico_texte_reponse = {} self.dico_texte_question = {} self.dico_nuance_nom = {"EXG" : "d'Extrême Gauche","PG":"du Parti de Gauche","COM":"Communistes", "SOC":"Socialistes","RDG":"Radicaux de Gauche","DVG":"Divers Gauche", "ECO":"Ecologistes","REG":"Regionalistes","DIV":"Divers","MDM":"Modem", "REM":"Républiques en Marche","UDI":"Union des démocrates et indépendants", "LR":"Républicains","DVD":"Divers Droite","DLF":"Debout la France", "FN":"Front National","EXD":"Extrême droite","FI":"France Insoumise"} self.resultat_IA = "Oui" * (self.nuance in self.liste_oui) + "Non" * (self.nuance not in self.liste_oui) if self.nuance in self.liste_oui: self.resultat_IA = "Oui" elif self.nuance in self.liste_petit_effectif or self.score_affinite == -10: self.resultat_IA = "???" else: self.resultat_IA = "Non" for reponse in os.listdir("Texte_bouton"): with open(os.path.join("Texte_bouton",reponse)) as file: self.dico_texte_reponse[reponse] = file.read() #(file.read()) for question in os.listdir("Questions"): # question est l'uid du scrutin path_question = os.path.join("Texte_résumé",question) with open(path_question,"r") as file: texte_question = file.read() self.dico_texte_question[question] = texte_question """ for reponse in os.listdir("Texte_bouton"): with codecs.open(os.path.join("Texte_bouton",reponse), "r", encoding='utf-8') as file: self.dico_texte_reponse[reponse] = file.read() for question in os.listdir("Questions"): # question est l'uid du scrutin path_question = os.path.join("Questions",question) with codecs.open(path_question, "r", encoding='utf-8') as file: texte_question = file.read() self.dico_texte_question[question] = texte_question """ #Layout de la bande du haut layout_haut = BoxLayout(orientation = "horizontal") #de gauche à droite photo Nom Nuance avec logo ou de couleur (a priori label coloré) photo_candidat = Image() photo_candidat.source = "images_candidat/{}.jpg".format(compteur) compteur+=1 layout_haut.add_widget(photo_candidat) #label_nom = Label(text = (prenom + " " + nom)) label_nom = WrappedLabel(text = (prenom + " " + nom)) label_nom.halign = "left" label_nom.font_size = 30 layout_haut.add_widget(label_nom) image_nuance = Image(source = "image_nuance/"+self.nuance+".png") layout_haut.add_widget(image_nuance) layout_haut.size_hint_y = 0.2 #Layout de la bande centrale avec les résultats layout_score = BoxLayout(orientation = "horizontal") layout_score.size_hint_y = 0.6 #sous-Layout pour le score d'affinité layout_score_affinité = BoxLayout(orientation = "vertical") label_affinite = Label(text = "Score d'Affinité") label_affinite.size_hint_y = 0.3 label_affinite.font_size = 40 layout_score_affinité.add_widget(label_affinite) string_label_score = (dico_score[self.nuance] != -10)*(str(dico_score[self.nuance])+"/100") + "???"*(dico_score[self.nuance] == -10) label_score_affinite = Label(text = string_label_score) label_score_affinite.font_size = 100 label_score_affinite.size_hint_y = 0.7 layout_score_affinité.add_widget(label_score_affinite) #sous-Layout pour le resultat IA layout_resultat_IA = BoxLayout(orientation = "vertical") label_IA = Label(text = "Conseil IA") label_IA.font_size = 40 label_IA.size_hint_y = 0.3 layout_resultat_IA.add_widget(label_IA) label_resultat_IA = Label(text = str(self.resultat_IA)) label_resultat_IA.font_size = 100 label_resultat_IA.size_hint_y = 0.7 layout_resultat_IA.add_widget(label_resultat_IA) #Ajout des layout score et IA au layout central score layout_score.add_widget(layout_score_affinité) layout_score.add_widget(layout_resultat_IA) self.layout_bouton_explication = GridLayout(cols = 5) self.layout_bouton_explication.size_hint_y = 0.2 self.bouton_explication = Button(text = "Explications") self.bouton_explication.bind(on_press = self.explication) self.bouton_explication.id = self.nuance + "," + self.sortant self.layout_bouton_explication.add_widget(self.bouton_explication) self.add_widget(layout_haut) self.add_widget(layout_score) self.add_widget(self.layout_bouton_explication) def explication(self,instance): print(self.score_affinite) if self.score_affinite == -10: content_explication = GridLayout(cols=1) label_explication = WrappedLabel() texte_explication = "Il n'y a pas d'élu {} à l'assemblée nationale, donc l'algorithme ne peut pas comparer avec vos choix avec les votes d'un élu {}".format(self.nuance,self.nuance) label_explication.text = texte_explication label_explication.markup = True content_explication.add_widget(label_explication) bouton_close = Button(text="Close") bouton_close.bind(on_press=self.close) bouton_close.size_hint_y = 0.2 content_explication.add_widget(bouton_close) self.popup_explication = Popup( title="Explication pour les élus {}".format(self.dico_nuance_nom[self.nuance]), content=content_explication, title_align="center", title_size=35) self.popup_explication.open() print("Pas d'élu de cette nuance") elif self.sortant != "Oui": content_explication = GridLayout(cols = 1) label_explication = WrappedLabel() texte_explication = "" for item in self.dico_envoi.items(): if item[1][1] != 0: proba = int(100*self.dico_scrutin_nuance_proba[item[0]][self.nuance][item[1][0]]) texte_explication += "[b]Question[/b] : " + self.dico_texte_question[item[0]].capitalize() + ". \n Vous avez choisi [b]{}[/b]".format(item[1][0]) + ", les élu.e.s ont voté [b]{}[/b] à [b]{}%[/b] ".format(item[1][0],proba) + "\n\n" label_explication.text = texte_explication label_explication.markup = True content_explication.add_widget(label_explication) bouton_close = Button(text = "Close") bouton_close.bind(on_press = self.close) bouton_close.size_hint_y = 0.2 content_explication.add_widget(bouton_close) self.popup_explication = Popup(title="Explication pour les élus {}".format(self.dico_nuance_nom[self.nuance]),content = content_explication,title_align = "center",title_size = 35) self.popup_explication.open() else: sql_sequence = "SELECT uid FROM Elu WHERE nom = '{}' and prenom = '{}'".format(self.nom.capitalize(),self.prenom.capitalize()) #Il va y avoir un problème avec les majuscules des noms composés cursor.execute(sql_sequence) content_explication = GridLayout(cols=1) label_explication = WrappedLabel() texte_explication = "" for item in cursor: uid = (item[0]) for item in self.dico_envoi.items(): if item[1][1] != 0: uid_scrutin = item[0].split(".")[0] sql_sequence = "SELECT listeUidNonVotants,listeUidPours,listeUidContres,listeUidAbstentions FROM Scrutin WHERE uid = '{}'".format(uid_scrutin) cursor.execute(sql_sequence) for scrutin in cursor: listeUidNonVotants, listeUidPours, listeUidContres, listeUidAbstentions = scrutin if uid in listeUidNonVotants: vote_elu = "non votant" elif uid in listeUidAbstentions: vote_elu = "abstention" elif uid in listeUidContres: vote_elu = "contre" else: vote_elu = "pour" texte_explication += "[b]Question[/b] : " + self.dico_texte_question[item[0]].capitalize() + ". \n Vous avez choisi [b]{}[/b]".format(item[1][0]) + ", {} {} a voté [b]{}[/b] ".format(self.prenom,self.nom,vote_elu) + "\n\n" label_explication.text = texte_explication label_explication.markup = True content_explication.add_widget(label_explication) bouton_close = Button(text="Close") bouton_close.bind(on_press=self.close) bouton_close.size_hint_y = 0.2 content_explication.add_widget(bouton_close) self.popup_explication = Popup( title="Explication pour {} {}".format(self.prenom,self.nom), content=content_explication, title_align="center", title_size=35) self.popup_explication.open() def close(self,instance): self.popup_explication.dismiss()
class Application(ScreenManager): def __init__(self, **kwargs): super(Application, self).__init__(**kwargs) """Main Screen image""" self.screen_image = kivy.resources.resource_find("padariacentral.png") """Main screen""" self.main_screen = Screen(name='Padaria Central') self.layout = BoxLayout(orientation='vertical') self.logo = Image(source=self.screen_image, allow_stretch=True, size_hint_y=1) self.layout_down = GridLayout(cols=2, rows=1, size_hint_y=0.2) self.layout.add_widget(self.logo) self.layout.add_widget(self.layout_down) self.main_screen.add_widget(self.layout) """Define os and default path""" self.os = platform self.path = "" if self.os == 'win': self.path = dirname(expanduser("~")) else: self.path = expanduser("~") """ Main screen buttons""" self.generate_payments = Button(text='Tirar contas do mês', size_hint_y=0.1) self.generate_payments.bind( on_press=lambda x: self.file_chooser("pay")) self.send_warnings = Button(text='Enviar aviso para Clientes', size_hint_y=0.1) self.send_warnings.bind(on_press=lambda x: self.file_chooser("info")) self.layout_down.add_widget(self.generate_payments) self.layout_down.add_widget(self.send_warnings) # init default popup self.popup = Popup() """Screen Manager""" self.s_open_file = Screen(name='Selecionar Ficheiro') self.add_widget(self.main_screen) self.add_widget(self.s_open_file) self.s_save_file = Screen(name='Gravar Ficheiro') self.add_widget(self.s_save_file) # self.s_select_clients = Screen(name='Selecionar Clientes') # self.add_widget(self.s_select_clients) """Init""" self.text_input = TextInput() self.text = "" def file_chooser(self, op): mp_layout = GridLayout(cols=1) info = Label(text="Selecionar ficheiro excel!") confirm = Button(text="Ok") mp_layout.add_widget(info) mp_layout.add_widget(confirm) confirm.bind(on_press=lambda x: self.browser(op)) self.popup = Popup(title="Gerar ficheiro", separator_height=0, content=mp_layout, size_hint=(None, None), size=(300, 150)) self.popup.open() def browser(self, op): """ This function creates the file chooser to select image""" # Create Layout for popup try: self.popup.dismiss() except PopupException: pass self.current = 'Selecionar Ficheiro' b_main_lay = GridLayout(rows=2) action_layout = BoxLayout(orientation='horizontal', size_hint_y=0.1) file = FileChooserIconView(path=self.path, size_hint_y=0.9, multiselect=False) # this popup buttons and actions select = Button(text='Selecionar') select.bind(on_press=lambda x: self.open(file.selection, op)) cancel = Button(text='Cancelar') cancel.bind(on_press=self.cancel_callback) action_layout.add_widget(select) action_layout.add_widget(cancel) b_main_lay.add_widget(file) b_main_lay.add_widget(action_layout) self.s_open_file.add_widget(b_main_lay) # def select_clients(self, clients): # # Create Layout for popup # # try: # # self.popup.dismiss() # # except PopupException: # # pass # # self.current = 'Selecionar Clientes' # # self.s_open_file.clear_widgets() # # # # clients_layout = GridLayout(cols=2) # # action_layout = BoxLayout(orientation='horizontal', size_hint_y=0.1) # # # # select = Button(text='Selecionar') # # select.bind(on_press=lambda x: self.cancel_callback()) # # cancel = Button(text='Cancelar') # # cancel.bind(on_press=self.cancel_callback) # # # # action_layout.add_widget(select) # # action_layout.add_widget(cancel) # # # # for client in clients: # # clients_layout.add_widget(Label(text=client.nome)) # # clients_layout.active = CheckBox(active=True) # # clients_layout.add_widget(clients_layout.active) # # # # clients_layout.add_widget(action_layout) # # self.s_select_clients.add_widget(clients_layout) # # """Try like a popup""" # self.current = 'Padaria Central' # grid = GridLayout(cols=2, padding=10, spacing=20, size_hint=(None, None), size=(500, 500)) # grid.bind(minimum_height=grid.setter('height')) # dismiss = Button(text='Sair', size_hint=(None, None), size=(50, 30)) # create = Button(text='Ok', size_hint=(None, None), size=(50, 30)) # for client in clients: # grid.add_widget(Label(text=client.nome)) # grid.active = CheckBox(active=True) # grid.add_widget(grid.active) # grid.add_widget(dismiss) # grid.add_widget(create) # root = ScrollView(size_hint=(None, None), size=(500, 500), # pos_hint={'center_x': .5, 'center_y': .5}, do_scroll_x=False) # root.add_widget(grid) # self.popup = Popup(title="Padaria Central", separator_height=0, content=root) # self.popup.open() # dismiss.bind(on_press=self.popup.dismiss) def cancel_callback(self, instance): self.current = 'Padaria Central' self.s_open_file.clear_widgets() def open(self, filename, op): self.current = 'Padaria Central' self.s_open_file.clear_widgets() if op == "pay": try: grid_s = GridLayout(rows=2) confirm = Button(text="Selecionar") spinner = Spinner( # default value shown text='Selecione o mês', text_autoupdate=True, # available values values=('Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'), # just for positioning in our example size_hint=(None, None), size=(275, 40), pos_hint={ 'center_x': .5, 'center_y': .5 }) confirm.bind(on_press=lambda x: self.generate( spinner.text, filename, op, None)) grid_s.add_widget(spinner) grid_s.add_widget(confirm) self.popup = Popup(title="Escolher Mês", separator_height=0, content=grid_s, size_hint=(None, None), size=(300, 150)) self.popup.open() except FileExistsError as e: self.end_action( "Oops! Algo correu mal!\nVerifique se selecionou o ficheiro correto" ) elif op == "info": try: grid_s = GridLayout(cols=1, rows=4) label = Label(text="Mensagem a enviar para clientes:", size_hint=(.5, .3)) self.text_input = TextInput(text="", multiline=True, size_hint=(.5, .8)) self.text_input.bind(text=self.set_text) confirm = Button(text="Seguinte", size_hint=(.5, .2)) cancel = Button(text="Cancelar", size_hint=(.5, .2)) cancel.bind(on_press=lambda x: self.popup.dismiss()) confirm.bind(on_press=lambda x: self.generate( None, filename, op, self.text_input.text)) grid_s.add_widget(label) grid_s.add_widget(self.text_input) grid_s.add_widget(confirm) grid_s.add_widget(cancel) self.popup = Popup(title="Mensagem", separator_height=0, content=grid_s, size_hint=(None, None), size=(400, 350)) self.popup.open() except Exception as e: self.end_action("Erro, tente novamente!") print(e) else: self.end_action( "Oops! Algo correu mal!\nVerifique se selecionou o ficheiro correto" ) def end_action(self, text): self.current = 'Padaria Central' grid = GridLayout(rows=2) label = Label(text=text) dismiss = Button(text='OK', size_hint_y=None, size=(50, 30)) grid.add_widget(label) grid.add_widget(dismiss) self.popup = Popup(title="Padaria Central", separator_height=0, content=grid, size_hint=(None, None), size=(300, 200)) self.popup.open() dismiss.bind(on_press=self.popup.dismiss) def show_selected_value(self, instance, text): """ Get current value from spinner """ if text is not "Tipo de ficheiro" and not '': return text else: print("Invalid file extension") def generate(self, month, filename, op, infotext): try: self.popup.dismiss() mp_layout = GridLayout(cols=1) info = Label(text="Selecionar pasta e nome do ficheiro Word") confirm = Button(text="Ok") mp_layout.add_widget(info) mp_layout.add_widget(confirm) confirm.bind(on_press=lambda x: self.popup.dismiss()) self.popup = Popup(title="Guardar Ficheiro", separator_height=0, content=mp_layout, size_hint=(None, None), size=(400, 150)) self.popup.open() except PopupException: pass try: self.current = 'Gravar Ficheiro' grid_s = GridLayout(rows=3) action_layout = BoxLayout(orientation='horizontal', size_hint_y=0.1) file_name_type_layout = BoxLayout(orientation='horizontal', size_hint_y=0.1) self.text_input = TextInput(text="", multiline=False) file_name_type_layout.add_widget(self.text_input) self.text_input.bind(text=self.set_text) save = Button(text="Guardar") cancel = Button(text="Cancelar") action_layout.add_widget(save) action_layout.add_widget(cancel) file = FileChooserIconView(path=self.path, ) grid_s.add_widget(file) grid_s.add_widget(file_name_type_layout) grid_s.add_widget(action_layout) self.s_save_file.add_widget(grid_s) cancel.bind(on_press=self.cancel_callback) save.bind(on_press=lambda x: self.proc( month, filename, file.path, self.text_input, op, infotext)) except: self.end_action("Algo correu mal, tente novamente!") def proc(self, month, input_file_path, output_file_path, output_file_name, op, infotext): filename = output_file_name.text if not filename and op == "pay": filename = "Contas" + month if not filename and op == "info": filename = "InfoClientes" if self.os == 'win': output_path = output_file_path + "\\" + filename + ".docx" else: output_path = output_file_path + "/" + filename + ".docx" try: if op == 'pay': try: clients = ExcelInfo(input_file_path[0]).get() for x in clients: print(x) # """try""" # self.select_clients(clients) # Word3Cols(clients, INVERSE_MONTH[month], output_path, "pay", None).create() except Exception as e: print(e) self.end_action( "Erro, guarde o ficheiro no formato \n Excel97-2003 (.xls)" ) else: self.end_action("Ficheiro guardado com sucesso!") else: clients = ExcelInfo(input_file_path[0]).get() Word3Cols(clients, None, output_path, op, infotext).create() self.end_action("Ficheiro guardado com sucesso!") except Exception as e: self.end_action("ERRO, tente novamente!") print(e) def set_text(self, instance, input): """ Workaround to save input from textInput """ self.text = input
class ViewMenu(GridLayout, MakesmithInitFuncs): page = 1 def openFile(self): ''' Open The Pop-up To Load A File Creates a new pop-up which can be used to open a file. ''' content = LoadDialog(load=self.load, cancel=self.dismiss_popup) content.path = path.dirname(self.data.gcodeFile) if content.path is "": content.path = path.expanduser('~') self._popup = Popup(title="Load file", content=content, size_hint=(0.9, 0.9)) self._popup.open() def reloadGcode(self): ''' Trigger a reloading of the gcode file ''' filePath = self.data.gcodeFile self.data.gcodeFile = "" self.data.gcodeFile = filePath #close the parent popup self.parentWidget.close() def load(self, filePath, filename): ''' Load A File (Any Type) Takes in a file path (from pop-up) and handles the file appropriately for the given file-type. ''' #close the open file popup self.dismiss_popup() #locate the file filename = filename[0] fileExtension = path.splitext(filename)[1] validExtensions = self.data.config.get('Ground Control Settings', 'validExtensions').replace(" ", "").split(',') if fileExtension in validExtensions: self.data.gcodeFile = filename self.data.config.set('Maslow Settings', 'openFile', str(self.data.gcodeFile)) self.data.config.write() else: self.data.message_queue.put("Message: Ground control can only open gcode files with extensions: " + self.data.config.get('Ground Control Settings', 'validExtensions')) #close the parent popup self.parentWidget.close() def resetView(self): ''' Reset the gcode canvas view. Most of the work is done in the .kv file. ''' #close the parent popup self.parentWidget.close() def show_gcode(self): ''' Display the currently loaded gcode in a popup It would be cool if you could run the program stepping through using this popup ''' popupText = "" if len(self.data.gcode) is 0: popupText = "No gcode to display" else: if self.page<=1: line = 0 else: line = (self.page-1)*447 popupText = "...\n...\n...\n" if line>len(self.data.gcode): line = len(self.data.gcode)-447 for lineNum, gcodeLine in enumerate(self.data.gcode): if lineNum>=line and lineNum<line+447: popupText = popupText + str(lineNum+1) + ': ' + gcodeLine + "\n" elif lineNum>=line+447: popupText = popupText + "...\n...\n...\n" break content = ScrollableTextPopup(cancel = self.dismiss_popup, prev = self.show_gcode_prev, next = self.show_gcode_next, text = popupText) titleString = 'Gcode File: ' + self.data.gcodeFile +'\nLines: '+str(line+1)+' - '+str(lineNum)+' of '+str(len(self.data.gcode)) self._popup = Popup(title=titleString, content=content, size_hint=(0.9, 0.9)) self._popup.open() def show_gcode_next(self,*args): if (self.page)*447<len(self.data.gcode): self.page += 1 self._popup.dismiss() self.show_gcode() def show_gcode_prev(self,*args): if self.page > 1: self.page -= 1 self._popup.dismiss() self.show_gcode() def dismiss_popup(self): ''' Close The Pop-up ''' self.page = 1 self._popup.dismiss()
class KivyPanelABM(GridLayout): def __init__(self, lista, nombreABM, **kwargs): # make sure we aren't overriding any important functionality super(KivyPanelABM, self).__init__(**kwargs) self.cols = 2 self.nombreABM = nombreABM self.lista = TreeView(hide_root=True, size_hint_x=0.9) self.add_widget(self.lista) self.panelbotoneraAcciones = GridLayout(cols=1, size_hint_x=0.1, size_hint_y=None, size=(0, 32)) # self.panelbotoneraAcciones.padding=[100,10,10,10] self.btnAdd = Button(background_normal="Add.png", size_hint=(None, None), size=(32, 32)) self.btnAdd.bind(on_press=self.btnEventAdd) self.btnEdit = Button(background_normal="Edit.png", size_hint=(None, None), size=(32, 32)) self.btnEdit.bind(on_press=self.btnEventEdit) self.btnDel = Button(background_normal="Delete.png", size_hint=(None, None), size=(32, 32)) self.btnDel.bind(on_press=self.btnEventDel) self.panelbotoneraAcciones.add_widget(self.btnAdd) self.panelbotoneraAcciones.add_widget(self.btnEdit) self.panelbotoneraAcciones.add_widget(self.btnDel) self.add_widget(self.panelbotoneraAcciones) for elemento in lista: self.lista.add_node(TreeViewLabel(text=elemento)) def getLista(self): list = [] print("arbol: " + str(self.lista)) for nodo in self.lista.iterate_all_nodes(node=None): list.append(nodo.text) return list[1:] def btnEventAdd(self, value): panel = GridLayout(cols=1) self.text = TextInput() panel.add_widget(self.text) # botonGuardar = Button(text="guardar")uardar) panel.add_widget(Button(text="guardar", on_press=self.guardar)) self.popup = Popup(title='Agregar ' + self.nombreABM, content=panel, size_hint=(1, 0.6)) self.popup.open() def guardar(self, value): self.lista.add_node(TreeViewLabel(text=self.text.text)) self.popup.dismiss() def __deleteItem__(self): if self.lista.selected_node: self.lista.remove_node(self.lista.selected_node) def btnEventDel(self, value): self.__deleteItem__() def btnEventEdit(self, value): panel = GridLayout(cols=1) self.text = TextInput(text=self.lista.get_selected_node().text) panel.add_widget(self.text) panel.add_widget(Button(text="guardar", on_press=self.modificar)) self.popup = Popup(title='Editar ' + self.nombreABM, content=panel, size_hint=(1, 0.6)) self.popup.open() def modificar(self, value): self.lista.get_selected_node().text = self.text.text # self.lista.add_node(TreeViewLabel(text=self.text.text)) self.popup.dismiss()
class AdjustZCalibrationDepth(GridLayout): ''' Provides a standard interface for setting up the Z axis ''' data = ObjectProperty(None) #linked externally def on_Enter(self): ''' This function runs when the step is entered ''' self.data = App.get_running_app().data if int(self.data.config.get('Maslow Settings', 'zAxis')) == 1: self.zAxisActiveSwitch.active = True self.openZPopupBtn.disabled = False else: self.zAxisActiveSwitch.active = False self.openZPopupBtn.disabled = True def enableZaxis(self, *args): ''' Triggered when the switch to enable the z-axis is touched ''' self.data.config.set('Maslow Settings', 'zAxis', int(self.zAxisActiveSwitch.active)) #enable and disable the button to open the z-axis popup if self.zAxisActiveSwitch.active == True: self.openZPopupBtn.disabled = False else: self.openZPopupBtn.disabled = True def zAxisPopup(self): self.popupContent = ZAxisPopupContent(done=self.dismissZAxisPopup) self.popupContent.data = self.data self.popupContent.initialize() self._zpopup = Popup(title="Z-Axis", content=self.popupContent, size_hint=(0.5, 0.5)) self._zpopup.open() def dismissZAxisPopup(self): ''' Close The Z-Axis Pop-up ''' self._zpopup.dismiss() def zeroZ(self): ''' Define the z-axis to be currently at height 0 and move to the next step. ''' self.data.gcode_queue.put("G10 Z0 ") #Set z-zero if self.data.units == "INCHES": #Go to traverse self.data.gcode_queue.put("G00 Z.25 ") else: self.data.gcode_queue.put( "G00 Z5.0 ") #these should use safe retract settings self.readyToMoveOn() def on_Exit(self): ''' This function runs when the step is completed ''' pass
class SecondWindow(Screen): #l=[] def __init__(self, **kwargs): super(SecondWindow, self).__init__(**kwargs) Clock.schedule_once( lambda dt: self.scrollVehiculos() ) #hago este proceso, porque si trato de usar los self.ids desde el constructor, #Me dara error, ya que no se han creado todavia, por eso con clock lo que trato es #retardar el proceso, de esta manera funciona, con la func lambda no tengo que obtener dt. def oprimidoBtnAgregarVehiculo(self): self.content = AgregarVehiculo( ) #Este texto que paso lo captura el stringProperty self.content.bind( on_guardar=self._on_guardar ) #segun mi analisis, es para dar el mando de on_answer a _on_answer self.popup = Popup(title="Agregue el vehiculo que desee", content=self.content, size_hint=(0.9, 0.9)) self.popup.open() def pantallas(self, app): app.root.screens[3].actualizarMarcadores( ) #Es para que el mapa siempre aparesca centrado en la ubicacion actual def _on_guardar(self, instance): resultadoVentanaAgregarVehiculo = self.content.on_guardar( ) #La pos 0 me determina si los datos de agregarVeh son correctos o no. if resultadoVentanaAgregarVehiculo[0]: #pos que contiene True o False box = BoxLayout(orientation="horizontal") box.add_widget( BotonVehiculo(text=resultadoVentanaAgregarVehiculo[1]) ) #pos que tiene nombre del vehiculo. box.add_widget( BotonUbicacion(text="ubicacion") ) #Los ids son iguales y corresponden al nombre del vehiculo box.add_widget(BotonEliminar(text="Eliminar")) self.ids.contenedorFilas.add_widget(box) self.popup.dismiss() else: pass def scrollVehiculos(self): # CONSULTA BASE DE DATOS PARA LISTAR TODOS LOS VEHICULOS for i in range(5): #self.l.append(BoxLayout(orientation="horizontal")) #self.ids.contenedorFilas.add_widget(self.l[-1]) #al gridlayout le agrego lo boxlayout necesarios, en cada boxlayout puedo posicionar #mis tres botones. self.ids.contenedorFilas.add_widget( BoxLayout(orientation="horizontal")) for i, n in enumerate(self.ids.contenedorFilas.children): n.add_widget(BotonVehiculo(text="vehiculo" + str(i))) n.add_widget( BotonUbicacion(text="ubicacion" + str(i)) ) #Los ids son iguales y corresponden al nombre del vehiculo n.add_widget(BotonEliminar(text="Eliminar" + str(i))) #l.append(n) #l.append(self.ids.contenedorFilas) #print(l) #No entiendo porque se imprimen dos listas """
class GenerateBarCodeWindow(Screen): barCodePath = StringProperty(barcode_path) now = datetime.datetime.now() filename = None skulist = None popup = None def build(self): pass def generateBarCode(self): if self.sku.text is None or self.sku.text is "" and self.skulist is None: self.errorLabel = "Please enter suvs or browse a file" else: skuarr = None inputStr = self.sku.text inputlist = inputStr.split(',') if self.barCodePath is None or self.barCodePath is "": self.errorLabel = "Go to settings and specify folder location to save the codes" return try: if self.skulist is not None: skuarr = self.skulist else: inputStr = self.sku.text skuarr = inputStr.split(',') for s in skuarr: str = self.now.strftime("%Y-%m-%d") fullPath = self.barCodePath + '/' + str if not os.path.exists(fullPath): os.makedirs(fullPath) code128.image(s).save(fullPath + "/" + s + ".png") if self.skulist is not None: self.skulist = None self.errorLabel = "Done" except Exception as e: print(e) self.errorLabel = "Error in generating SKU's" def chooseFile(self): if sys.platform == 'win': user_path = dirname(expanduser('~')) + sep + 'Documents' else: user_path = expanduser('~') + sep + 'Documents' browser = FileBrowser(select_string='Select', favorites=[(user_path, 'Documents')]) self.popup = Popup(size_hint=(None, None), content=browser, auto_dismiss=False, size=(700, 500)) browser.bind(on_success=self.selectFile, on_canceled=self.popup.dismiss) self.popup.open() def selectFile(self, instance): self.filename = instance.selection self.skulist = self.readFile(self.filename) self.popup.dismiss() return def readFile(self, filename): with open(filename[0], 'rt') as f: reader = csv.DictReader(f, delimiter='\t') data = {} for row in reader: for header, value in row.items(): try: data[header].append(value) except KeyError: data[header] = [value] return data['sku']
class Cards(FloatLayout): def __init__(self, **kwargs): super(Cards, self).__init__(**kwargs) self.cards_name = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] self.card_number = [x for x in range(2, 15)] self.all_cards = [] self.mixed_cards = [] self.p1 = [] self.p2 = [] self.temp1 = [] self.temp2 = [] self.num1 = 0 self.num2 = 0 self.bat_1 = 0 self.bat_2 = 0 self.default_back = 'boc/BackOfCards4.png' self.boc = ('boc/BackOfCards.png', 'boc/BackOfCards1.png', 'boc/BackOfCards2.png', 'boc/BackOfCards3.png', 'boc/BackOfCards4.png', 'boc/BackOfCards5.png') def new_back(self): # Popup for changing backgrounds val = '180dp' self.popup = Popup(title='Choose background', auto_dismiss=True, size_hint=(0.95, 0.62), separator_color=(0, 0, 1, 1), title_align='center', title_color=(1, 1, 1, 1), title_size='16sp', title_font='fonts/Fcarbim.ttf') scroll = ScrollView() scroll.size_hint = (1, 1) scroll.do_scroll_x = False scroll.do_scroll_y = True grd = GridLayout(cols=3, spacing='3dp') grd.size_hint = (1, None) grd.bind(minimum_height=grd.setter('height')) but1 = ImageButton( source='boc/BackOfCards.png', on_release=lambda x: self.receive('boc/BackOfCards.png'), size_hint=(1, None), height=val) but2 = ImageButton( source='boc/BackOfCards1.png', on_release=lambda x: self.receive('boc/BackOfCards1.png'), size_hint=(1, None), height=val) but3 = ImageButton( source='boc/BackOfCards2.png', on_release=lambda x: self.receive('boc/BackOfCards2.png'), size_hint=(1, None), height=val) but4 = ImageButton( source='boc/BackOfCards3.png', on_release=lambda x: self.receive('boc/BackOfCards3.png'), size_hint=(1, None), height=val) but5 = ImageButton( source='boc/BackOfCards4.png', on_release=lambda x: self.receive('boc/BackOfCards4.png'), size_hint=(1, None), height=val) but6 = ImageButton( source='boc/BackOfCards5.png', on_release=lambda x: self.receive('boc/BackOfCards5.png'), size_hint=(1, None), height=val) grd.add_widget(but1) grd.add_widget(but2) grd.add_widget(but3) grd.add_widget(but4) grd.add_widget(but5) grd.add_widget(but6) scroll.add_widget(grd) self.popup.add_widget(scroll) self.popup.open() def receive(self, dan): # callback for change background cards self.default_back = dan self.rem_wid() self.dc() if self.ids.but_card1.source not in self.boc: pass elif self.ids.but_card1.source in self.boc: self.ids.but_card1.source = self.default_back if self.ids.but_card2.source not in self.boc: pass elif self.ids.but_card2.source in self.boc: self.ids.but_card2.source = self.default_back self.popup.dismiss() def new_cards(self): # Popup for changing the length of the game self.popup1 = Popup(title='Choose number of cards to play', auto_dismiss=True, size_hint=(0.8, 0.5), separator_color=(0, 0, 1, 1), title_align='center', title_color=(1, 1, 1, 1), title_size='18sp', title_font='fonts/Fcarbim.ttf') self.layout = GridLayout(cols=1, spacing=5) self.check1 = Button( text='When boss is not around\n (12 cards)', halign='left', on_release=lambda x: self.new_no_of_cards(5), font_name='fonts/Fcarbim.ttf', background_color=utils.get_color_from_hex('#ed86f8')) self.check2 = Button( text='Coffee time\n (20 cards)', halign='left', on_release=lambda x: self.new_no_of_cards(7), font_name='fonts/Fcarbim.ttf', background_color=utils.get_color_from_hex('#bf4dcc')) self.check3 = Button( text='I cant sleep\n (28 cards)', halign='left', on_release=lambda x: self.new_no_of_cards(9), font_name='fonts/Fcarbim.ttf', background_color=utils.get_color_from_hex('#9737a2')) self.check4 = Button( text='Netflix is down\n (36 cards)', halign='left', on_release=lambda x: self.new_no_of_cards(11), font_name='fonts/Fcarbim.ttf', background_color=utils.get_color_from_hex('#782c81')) self.check5 = Button( text='Nothing to do after work\n (44 cards)', halign='left', on_release=lambda x: self.new_no_of_cards(13), font_name='fonts/Fcarbim.ttf', background_color=utils.get_color_from_hex('#5c1864')) self.check6 = Button( text='Free all day\n (52 cards)', halign='left', on_release=lambda x: self.new_no_of_cards(15), font_name='fonts/Fcarbim.ttf', background_color=utils.get_color_from_hex('#3d1242')) self.check7 = Button( text=' Jobless\n(104 cards)', halign='left', on_release=lambda x: self.new_no_of_cards(28), font_name='fonts/Fcarbim.ttf', background_color=utils.get_color_from_hex('#3d1242')) self.check8 = Button( text='Jobless and immortal\n (208 cards)', halign='left', on_release=lambda x: self.new_no_of_cards(54), font_name='fonts/Fcarbim.ttf', background_color=utils.get_color_from_hex('#000000')) self.layout.add_widget(self.check1) self.layout.add_widget(self.check2) self.layout.add_widget(self.check3) self.layout.add_widget(self.check4) self.layout.add_widget(self.check5) self.layout.add_widget(self.check6) self.layout.add_widget(self.check7) self.layout.add_widget(self.check8) self.popup1.add_widget(self.layout) self.popup1.open() def new_no_of_cards(self, no): # Callback for length of the cards self.bat_1 = 0 self.bat_2 = 0 a = range(2, 15) self.no = int(no) if self.no == 28: self.card_number = [val for val in a for _ in (0, 1)] elif self.no == 54: self.card_number = [val for val in a for _ in (0, 1, 2, 3)] else: self.card_number = [x for x in range(2, no)] self.add_cards() self.popup1.dismiss() def add_cards(self): self.bat_1 = 0 self.bat_2 = 0 self.ids.newgame1.text = '' self.ids.newgame2.text = '' self.p1.clear() self.p2.clear() self.all_cards.clear() self.mixed_cards.clear() self.temp1.clear() self.temp2.clear() for i in self.card_number: for j in self.cards_name: a = f'{i} of {j}' self.all_cards.append(a) for i in range(len(self.all_cards)): alin = random.choice(self.all_cards) self.mixed_cards.append(alin) moc = self.all_cards.index(alin) self.all_cards.remove(self.all_cards[moc]) self.p1 = self.mixed_cards[0:int(len(self.mixed_cards) / 2)] self.p2 = self.mixed_cards[int(len(self.mixed_cards) / 2):] self.ids.but_card1.disabled = False self.ids.but_card2.disabled = False self.ids.but_card1.source = self.default_back self.ids.but_card2.source = self.default_back self.ids.score_p1.text = '{}'.format(len(self.p1)) self.ids.score_p2.text = '{}'.format(len(self.p2)) self.ids.score_p2.color = 1, 1, 1, 1 self.ids.score_p1.color = 1, 1, 1, 1 self.ids.numbers_1.text = 'Win\n{}'.format(self.num1) self.ids.numbers_2.text = 'Win\n{}'.format(self.num2) self.ids.battle1.text = 'Battles\n{}'.format(self.bat_1) self.ids.battle2.text = 'Battles\n{}'.format(self.bat_2) self.dc() def cards_p1(self): # Card for player ONE global a a = self.p1[0] self.ids.but_card1.source = 'cards/{}.png'.format(a) self.ids.but_card1.disabled = True if self.ids.but_card1.source != self.default_back and self.ids.but_card2.source != self.default_back: self.ids.move_on.disabled = False return a def cards_p2(self): # Card for player two global b b = self.p2[0] self.ids.but_card2.source = 'cards/{}.png'.format(b) self.ids.but_card2.disabled = True if self.ids.but_card1.source != self.default_back and self.ids.but_card2.source != self.default_back: self.ids.move_on.disabled = False return b def move2next(self): self.ids.move_on.disabled = True self.ids.but_card1.source = self.default_back self.ids.but_card2.source = self.default_back self.take_cards(a, b) def take_cards(self, v1, v2): self.ids.move_on.disabled = True self.enabled_p1p2() self.v1 = v1 self.v2 = v2 ap1 = v1.split(' ', 1) ap1 = int(ap1[0]) ap2 = v2.split(' ', 1) ap2 = int(ap2[0]) if ap1 > ap2 and len(self.p2) > 1: self.ids.score_p2.color = 1, 1, 1, 1 self.ids.score_p1.color = 1, 1, 1, 1 if self.temp1 != [] and self.temp2 != []: [self.p1.append(x) for x in self.temp1] [self.p1.append(x) for x in self.temp2] self.p1.append(v1) self.p1.append(v2) self.p1.remove(v1) self.p2.remove(v2) self.temp1.clear() self.temp2.clear() self.dc() if self.p2 == []: self.num1 += 1 self.end_game() else: self.p1.append(v1) self.p1.append(v2) self.p1.remove(v1) self.p2.remove(v2) self.dc() self.bat_1 += 1 self.show_score() elif ap1 > ap2 and len(self.p2) == 1: self.ids.score_p2.color = 1, 1, 1, 1 self.ids.score_p1.color = 1, 1, 1, 1 self.num1 += 1 self.end_game() elif ap2 > ap1 and len(self.p1) > 1: self.ids.score_p2.color = 1, 1, 1, 1 self.ids.score_p1.color = 1, 1, 1, 1 if self.temp1 != [] and self.temp2 != []: [self.p2.append(x) for x in self.temp1] [self.p2.append(x) for x in self.temp2] self.p2.append(v1) self.p2.append(v2) self.p1.remove(v1) self.p2.remove(v2) self.temp1.clear() self.temp2.clear() self.dc() if self.p1 == []: self.num2 += 1 self.end_game() else: self.p2.append(v2) self.p2.append(v1) self.p1.remove(v1) self.p2.remove(v2) self.dc() self.bat_2 += 1 self.show_score() elif ap2 > ap1 and len(self.p1) == 1: self.ids.score_p2.color = 1, 1, 1, 1 self.ids.score_p1.color = 1, 1, 1, 1 self.num2 += 1 self.end_game() elif ap1 == ap2 and (len(self.p1) == 1 or len(self.p2) == 1): self.num1 += 1 self.num2 += 1 self.end_game() elif ap1 == ap2: self.ids.score_p2.color = 1, 0, 0, 1 self.ids.score_p1.color = 1, 0, 0, 1 ab1 = v1.split(' ', 1) ab2 = v2.split(' ', 1) ac1 = int(ab1[0]) ac2 = int(ab2[0]) if len(self.p1) <= ac1 + 1: ac1 = len(self.p1) - 1 ac2 = ac1 if len(self.p2) <= ac2 + 1: ac2 = len(self.p2) - 1 ac1 = ac2 ad1 = self.p1[:ac1] ad2 = self.p2[:ac2] [self.temp1.append(x) for x in ad1] [self.temp2.append(x) for x in ad2] [self.p1.remove(x) for x in self.p1[:ac1]] [self.p2.remove(x) for x in self.p2[:ac2]] self.dc() def keep_score(self, n1, n2): self.num1 = n1 self.num2 = n2 self.ids.numbers_1.text = 'Win\n{}'.format(n1) self.ids.numbers_2.text = 'Win\n{}'.format(n2) def show_score(self): self.ids.score_p1.text = '{}'.format(len(self.p1)) self.ids.score_p2.text = '{}'.format(len(self.p2)) self.ids.battle1.text = '[b]Battles[/b]\n{}'.format(self.bat_1) self.ids.battle2.text = '[b]Battles[/b]\n{}'.format(self.bat_2) def enabled_p1p2(self): self.ids.but_card1.disabled = False self.ids.but_card2.disabled = False def rem_wid(self): self.ids.float_p1.clear_widgets() self.ids.float_p2.clear_widgets() def dc(self): # small cards for both players self.rem_wid() a = len(self.p1) b = len(self.p2) if a > 33: a = 33 if b > 33: b = 33 pop1 = 1 for i in range(a): self.img = Image(source=self.default_back, size_hint=(1, 0.1), pos_hint={ 'x': 0, 'top': pop1 }) self.ids.float_p1.add_widget(self.img) impartit1 = 0.03 pop1 -= impartit1 pop2 = 1 for i in range(b): self.img = Image(source=self.default_back, size_hint=(1, 0.1), pos_hint={ 'x': 0, 'top': pop2 }) self.ids.float_p2.add_widget(self.img) impartit2 = 0.03 pop2 -= impartit2 def end_game(self): self.rem_wid() self.bat_1 = 0 self.bat_2 = 0 self.ids.but_add_cards.disabled = False self.ids.score_p1.text = '' self.ids.score_p2.text = '' self.ids.but_card1.disabled = True self.ids.but_card2.disabled = True self.ids.but_number_cards.disabled = False self.ids.move_on.disabled = True self.ids.newgame1.text = 'GAME OVER' self.ids.newgame2.text = 'GAME OVER' self.keep_score(self.num1, self.num2) def show_startup(self): startPop = Popup(title='Help', auto_dismiss=True, size_hint=(0.9, 0.4), separator_color=(0, 0, 1, 1), title_align='center', title_color=(1, 1, 1, 1), title_size='16sp', title_font='fonts/Fcarbim.ttf') layStart = GridLayout(cols=2, spacing=10) but_playNextCards = Image(source='icons/PlayDown.png') but_playNextCards.size_hint = (None, 1) but_playNextCards.width = '40dp' lbl_playNextCards = Label(text=' Play current cards') lbl_playNextCards.halign = 'left' lbl_playNextCards.valign = 'middle' lbl_playNextCards.bind(size=lbl_playNextCards.setter('text_size')) but_startGame = Image(source='icons/ShuffleCardsDown.png') but_startGame.size_hint = (None, 1) but_startGame.width = '40dp' lbl_startGame = Label(text=' Start new game') lbl_startGame.halign = 'left' lbl_startGame.valign = 'middle' lbl_startGame.bind(size=lbl_startGame.setter('text_size')) but_duration = Image(source='icons/noofcards.png') but_duration.size_hint = (None, 1) but_duration.width = '40dp' lbl_duration = Label(text=' How many cards to play') lbl_duration.halign = 'left' lbl_duration.valign = 'middle' lbl_duration.bind(size=lbl_duration.setter('text_size')) but_background = Image(source='icons/but_backofcards.png') but_background.size_hint = (None, 1) but_background.width = '40dp' lbl_background = Label(text=' Change the background') lbl_background.halign = 'left' lbl_background.valign = 'middle' lbl_background.bind(size=lbl_background.setter('text_size')) but_exit = Image(source='icons/Exit.png') but_exit.size_hint = (None, 1) but_exit.width = '40dp' lbl_exit = Label(text=' Exit game') lbl_exit.halign = 'left' lbl_exit.valign = 'middle' lbl_exit.bind(size=lbl_exit.setter('text_size')) layStart.add_widget(but_playNextCards) layStart.add_widget(lbl_playNextCards) layStart.add_widget(but_startGame) layStart.add_widget(lbl_startGame) layStart.add_widget(but_duration) layStart.add_widget(lbl_duration) layStart.add_widget(but_background) layStart.add_widget(lbl_background) layStart.add_widget(but_exit) layStart.add_widget(lbl_exit) startPop.add_widget(layStart) startPop.open()
class AddLocationForm(FloatLayout): icon = 'logo.png' hidden_text = ObjectProperty(None) text_input = ObjectProperty(None) progress_bar = ObjectProperty() savefile = ObjectProperty(None) text_input = ObjectProperty(None) minutes = StringProperty() seconds = StringProperty() running = BooleanProperty(False) _operand = None # current executing option _op_args = None # arguments for the executing option def start(self, *latgs): self.clear_widgets() page = BoxLayout(orientation='vertical') self.add_widget(page) pict = Image(source='./logo.png', size_hint=(1, .3), pos_hint={ 'center_x': .5, 'center_y': .8 }) button1 = Button(text='Test sample', bold=True, background_normal='bottone3.png', font_size='18sp', size_hint=(0.22, 0.12), pos_hint={ 'center_x': .5, 'center_y': .40 }) button1.bind(on_press=self.camerabutton) button2 = Button(text='Select image', bold=True, background_normal='bottone3.png', font_size='18sp', size_hint=(0.22, 0.12), pos_hint={ 'center_x': .5, 'center_y': .25 }) button2.bind(on_press=self.choosebutton) button3 = Button(text='Procedure', bold=True, background_normal='bottone3.png', font_size='18sp', size_hint=(0.22, 0.12), pos_hint={ 'center_x': .5, 'center_y': .55 }) button3.bind(on_press=self.howitworksbutton) button4 = Button(text='info', bold=True, background_normal='trasp.png', font_size='18sp', size_hint=(0.22, 0.12), pos_hint={ 'center_x': .5, 'center_y': .08 }) button4.bind(on_press=self.infobutton) self.add_widget(pict) self.add_widget(button2) self.add_widget(button3) self.add_widget(button4) self.add_widget(button1) def done(self, e): #receive e as the image location self.lblCam.text = e #update the label to the image location img = Image(source=(e), pos_hint={'center_x': .5, 'center_y': .5}) self.add_widget(img) def camerabutton(self, e): camera.take_picture('/storage/sdcard/screenshot%(counter)04d.jpg', self.done) def show_save(self, *largs): content = SaveDialog(save=self.save, cancel=self._dismiss_popup) self._popup = Popup(title="Save file", content=content, size_hint=(0.9, 0.9)) self._popup.open() def save(self, path, filename): with open(os.path.join(path, filename), 'w') as stream: stream.write(self.text_input.text) self._dismiss_popup() def howitworksbutton(self, *latgs): page = Widget() self.clear_widgets() self.add_widget(page) button1 = Button(text='Home', background_normal='bottone3.png', size_hint=(0.11, 0.10), pos_hint={ 'center_x': .1, 'center_y': .1 }) button1.bind(on_press=self.start) self.add_widget(button1) label1 = Label( text= '1) Assemble the smartphone adaptor \n\n2) Add sample to T1-T2 wells \n\n3) Incubate 30 min \n\n4) Add BL substrate \n\n5) Insert cartridge into the adaptor \n\n6) Acquire BL image & Read result', color=(1, 1, 1, .9), font_size='15sp', pos_hint={ 'center_x': .24, 'center_y': .56 }) self.add_widget(label1) button2 = Image(source='./app1-2.png', size_hint=(0.15, 0.21), pos_hint={ 'center_x': .7, 'center_y': .75 }) self.add_widget(button2) button3 = Image(source='./app2-1.png', size_hint=(0.20, 0.26), pos_hint={ 'center_x': .85, 'center_y': .77 }) self.add_widget(button3) button4 = Image(source='./app3-2.png', size_hint=(0.15, 0.21), pos_hint={ 'center_x': .7, 'center_y': .52 }) self.add_widget(button4) button5 = Image(source='./app4-2.png', size_hint=(0.20, 0.26), pos_hint={ 'center_x': .85, 'center_y': .50 }) self.add_widget(button5) button6 = Image(source='./app8-2.png', size_hint=(0.25, 0.31), pos_hint={ 'center_x': .78, 'center_y': .2 }) self.add_widget(button6) button4 = Button(text='Begin', background_normal='bottone3.png', size_hint=(0.21, 0.11), bold=True, font_size='20sp', pos_hint={ 'center_x': .5, 'center_y': .1 }) button4.bind(on_press=self.analysis) self.add_widget(button4) label = Button(text='Procedure', background_normal='bottone3.png', size_hint=(0.31, 0.12), bold=True, font_size='20sp', color=(1, 1, 1, .9), valign='top', pos_hint={ 'center_x': .5, 'center_y': .92 }) pict = Image(source='./logo.png', size_hint=(1, .16), pos_hint={ 'center_x': .68, 'center_y': .92 }) self.add_widget(label) self.add_widget(pict) def analysis(self, *latgs): self.clear_widgets() label = Button(text=' Checklist ', background_normal='bottone3.png', size_hint=(0.31, 0.14), bold=True, font_size='20sp', color=(1, 1, 1, .9), valign='top', pos_hint={ 'center_x': .5, 'center_y': .92 }) pict = Image(source='./logo.png', size_hint=(1, .16), pos_hint={ 'center_x': .68, 'center_y': .92 }) self.add_widget(label) self.add_widget(pict) label1 = Label( text= 'Assembled Device \n\nSample Added \n\nBL Substrate Added \n\nCartridge inserted', color=(1, 1, 1, .9), font_size='15sp', pos_hint={ 'center_x': .24, 'center_y': .56 }) checkbox = CheckBox(pos_hint={'center_x': .10, 'center_y': .61}) checkbox1 = CheckBox(pos_hint={'center_x': .10, 'center_y': .51}) checkbox.bind(active=self.on_checkbox_active) button4 = Button(text='Acquire', background_normal='bottone3.png', size_hint=(0.21, 0.11), bold=True, font_size='20sp', pos_hint={ 'center_x': .5, 'center_y': .1 }) self.add_widget(button4) button4.bind(on_press=self.camerabutton) self.add_widget(label1) self.add_widget(checkbox1) self.add_widget(checkbox) button1 = Button(text='Home', background_normal='bottone3.png', size_hint=(0.11, 0.10), pos_hint={ 'center_x': .1, 'center_y': .1 }) button1.bind(on_press=self.start) self.add_widget(button1) def on_checkbox_active(self, checkbox, value): #delta = datetime.datetime.now()+datetime.timedelta(1, 60*30) delta = "30:00" hour_string = str(delta) self.minutes = hour_string.split(':')[0] self.seconds = hour_string.split(':')[1] if value: label3 = Label(text="TIMER", font_size=20, color=(0, 0, 0, .9), bold=True, pos_hint={ 'center_x': .703, 'center_y': .62 }) #verdecolor=(0, 1, 0, .9) label2 = Label(text="%s:%s" % (self.minutes, self.seconds), font_size=32, pos_hint={ 'center_x': .7, 'center_y': .545 }) label4 = Label(text="Minutes Seconds", font_size=12, color=(0, 0, 0, .9), pos_hint={ 'center_x': .7, 'center_y': .59 }) rec = Button(size_hint=(0.28, 0.20), pos_hint={ 'center_x': .66, 'center_y': .57 }, background_normal='bottone3.png') pict = Image(source='./hourglass_blue_T.png', size_hint=(1, .16), pos_hint={ 'center_x': .58, 'center_y': .575 }) self.add_widget(rec) self.add_widget(label2) self.add_widget(label3) self.add_widget(label4) self.add_widget(pict) self.seconds = str(60) while int(self.minutes) <= 30: os.system print self.minutes, " minutes", self.seconds, " seconds" time.sleep(1) if (int(self.minutes) != 0 or int(self.seconds) != 0): self.seconds = str(int(self.seconds) - 1) if int(self.seconds) == 00: if int(self.minutes) > 0: self.minutes = str(int(self.minutes) - 1) self.seconds = str(60) if int(self.minutes) == 0: self.minutes = str(0) else: break else: self.clear_widgets() label = Button(text=' Checklist ', background_normal='bottone3.png', size_hint=(0.31, 0.14), bold=True, font_size='20sp', color=(1, 1, 1, .9), valign='top', pos_hint={ 'center_x': .5, 'center_y': .92 }) pict = Image(source='./logo.png', size_hint=(1, .16), pos_hint={ 'center_x': .68, 'center_y': .92 }) self.add_widget(label) self.add_widget(pict) label1 = Label( text= 'Assembled Device \n\nSample Added \n\nBL Substrate Added \n\nCartridge inserted', color=(1, 1, 1, .9), font_size='15sp', pos_hint={ 'center_x': .24, 'center_y': .56 }) checkbox = CheckBox(pos_hint={'center_x': .10, 'center_y': .61}) checkbox.bind(active=self.on_checkbox_active) self.add_widget(label1) self.add_widget(checkbox) checkbox1 = CheckBox(pos_hint={'center_x': .10, 'center_y': .51}) checkbox1.bind(active=self.on_checkbox_active1) self.add_widget(checkbox1) button4 = Button(text='Acquire', background_normal='bottone3.png', size_hint=(0.21, 0.11), bold=True, font_size='20sp', pos_hint={ 'center_x': .5, 'center_y': .1 }) self.add_widget(button4) button4.bind(on_press=self.camerabutton) button1 = Button(text='Home', background_normal='bottone3.png', size_hint=(0.11, 0.10), pos_hint={ 'center_x': .1, 'center_y': .1 }) button1.bind(on_press=self.start) self.add_widget(button1) def on_checkbox_active1(self, checkbox1, value): delta = "00:30" hour_string = str(delta) self.minutes = hour_string.split(':')[0] self.seconds = hour_string.split(':')[1] if value: label5 = Label(text="TIMER", font_size=20, color=(0, 0, 0, .9), bold=True, pos_hint={ 'center_x': .703, 'center_y': .42 }) label6 = Label(text="%s:%s" % (self.minutes, self.seconds), font_size=32, pos_hint={ 'center_x': .7, 'center_y': .345 }) label7 = Label(text="Minutes Seconds", font_size=12, color=(0, 0, 0, .9), pos_hint={ 'center_x': .7, 'center_y': .39 }) rec1 = Button(size_hint=(0.28, 0.20), pos_hint={ 'center_x': .66, 'center_y': .37 }, background_normal='bottone3.png') pict1 = Image(source='./hourglass_blue_T.png', size_hint=(1, .16), pos_hint={ 'center_x': .58, 'center_y': .375 }) self.add_widget(rec1) self.add_widget(label5) self.add_widget(label6) self.add_widget(label7) self.add_widget(pict1) else: self.clear_widgets() label = Button(text=' Checklist ', background_normal='bottone3.png', size_hint=(0.31, 0.14), bold=True, font_size='20sp', color=(1, 1, 1, .9), valign='top', pos_hint={ 'center_x': .5, 'center_y': .92 }) pict = Image(source='./logo.png', size_hint=(1, .16), pos_hint={ 'center_x': .68, 'center_y': .92 }) self.add_widget(label) self.add_widget(pict) label1 = Label( text= 'Assembled Device \n\nSample Added \n\nBL Substrate Added \n\nCartridge inserted', color=(1, 1, 1, .9), font_size='15sp', pos_hint={ 'center_x': .24, 'center_y': .56 }) checkbox = CheckBox(pos_hint={'center_x': .10, 'center_y': .61}) checkbox.bind(active=self.on_checkbox_active) self.add_widget(checkbox1) self.add_widget(label1) self.add_widget(checkbox) button4 = Button(text='Acquire', background_normal='bottone3.png', size_hint=(0.21, 0.11), bold=True, font_size='20sp', pos_hint={ 'center_x': .5, 'center_y': .1 }) self.add_widget(button4) button4.bind(on_press=self.camerabutton) button1 = Button(text='Home', background_normal='bottone3.png', size_hint=(0.11, 0.10), pos_hint={ 'center_x': .1, 'center_y': .1 }) button1.bind(on_press=self.start) self.add_widget(button1) def load(self, *latgs): """Open a dialog to load an image file.""" content = LoadDialog(load=self._load_helper, cancel=self._dismiss_popup) self._popup = Popup(title="Load image", content=content, size_hint=(0.9, 0.9)) self._popup.open() def _load_helper(self, path, filename): """Callback function for load. Called when user selects a file. This method loads the image file and redisplays the ImagePanels.""" print "filename:", filename[0] print "path:", path self._dismiss_popup() self.clear_widgets() global path_def path_def = path + "/" + filename[0] img = Image(source=(path_def), pos_hint={ 'center_x': .5, 'center_y': .5 }) self.add_widget(img) button1 = Button(text='Home', background_normal='bottone3.png', size_hint=(0.11, 0.10), pos_hint={ 'center_x': .1, 'center_y': .1 }) button1.bind(on_press=self.start) self.add_widget(button1) button2 = Button(text='Analyze', background_normal='bottone3.png', size_hint=(0.22, 0.12), bold=True, font_size='20sp', pos_hint={ 'center_x': .5, 'center_y': .1 }, state='down') button2.bind(on_press=self.calculatergb) self.add_widget(button2) def _dismiss_popup(self): """Used to dismiss the currently active pop-up""" self._popup.dismiss() def choosebutton(self, *latgs): self.clear_widgets() button1 = Button(text='Home', background_normal='bottone3.png', size_hint=(0.11, 0.10), pos_hint={ 'center_x': .1, 'center_y': .1 }) button1.bind(on_press=self.start) self.add_widget(button1) button2 = Button(text='Load', background_normal='background_normal.png', size_hint=(0.22, 0.12), pos_hint={ 'center_x': .5, 'center_y': .1 }) button2.bind(on_submit=self.load(FileChooserIconView.path)) #self.add_widget(button2) #self.add_widget(picture) def infobutton(self, *latgs): info = Widget() self.clear_widgets() self.add_widget(info) label = Label( text= 'This App was created by the group of Analytical & Bioanalytical Chemistry, \n Department of Chemistry "G.Ciamician", \n University of Bologna', italic=True, color=(1, 1, 1, .9), font_size='17sp', pos_hint={ 'center_x': .5, 'center_y': .4 }) self.add_widget(label) button1 = Button(text='Home', background_normal='bottone3.png', size_hint=(0.11, 0.10), pos_hint={ 'center_x': .1, 'center_y': .1 }) button1.bind(on_press=self.start) self.add_widget(button1) dang2 = Image(source="./logo.png", size_hint=(1, .3), pos_hint={ 'center_x': .5, 'center_y': .8 }) self.add_widget(dang2) def calculatergb(img, *largs): #img.clear_widgets #lab=Label(title=str(Logger.info('Progress: Wait.. work in progress')), size_hint=(0.9, 0.9)) print Logger.info('Progress: Wait.. work in progress') #popup = MsgPopup(msg="Wait.. work in progress") #Clock.schedule_interval(img.calculatergb) imag = pixel.open(path_def) pix = imag.load() w = imag.size[0] h = imag.size[1] L = [] A = [[[0, 0, 0] for i in range(700)] for i in range(550)] #700,550 B = [[[0, 0, 0] for i in range(700)] for i in range(1500)] #700,1500 C = [[[0, 0, 0] for i in range(1700)] for i in range(550)] #1700,550 D = [[[0, 0, 0] for i in range(1700)] for i in range(1500)] #1700,1500 a, b, c, n = 0, 0, 0, 0 a1, b1, c1, n1 = 0, 0, 0, 0 a2, b2, c2, n2 = 0, 0, 0, 0 a3, b3, c3, n3 = 0, 0, 0, 0 mctrR, mctrG, mctrB = 0, 0, 0 mctrR1, mctrG1, mctrB1 = 0, 0, 0 for i in range(350, 550): #350,550 for j in range(500, 700): #500,700 A[i][j] = imag.getpixel((i, j)) for i in range(350, 550): #350,550 for j in range(500, 700): #500,700 n = n + 1 a = a + A[i][j][0] b = b + A[i][j][1] c = c + A[i][j][2] Ta, Tb, Tc = a / n, b / n, c / n for i in range(1300, 1500): #1300,1500 for j in range(500, 700): #500,700 B[i][j] = imag.getpixel((i, j)) for i in range(1300, 1500): #1300,1500 for j in range(500, 700): #500,700 n1 = n1 + 1 a1 = a1 + B[i][j][0] b1 = b1 + B[i][j][1] c1 = c1 + B[i][j][2] Ta1, Tb1, Tc1 = a1 / n1, b1 / n1, c1 / n1 mctrR, mctrG, mctrB = (Ta + Ta1) / 2, (Tb + Tb1) / 2, (Tc + Tc1) / 2 for i in range(350, 550): #350,550 for j in range(1500, 1700): #1500,1700 C[i][j] = imag.getpixel((i, j)) for i in range(350, 550): #350,550 for j in range(1500, 1700): #1500,1700 n2 = n2 + 1 a2 = a2 + C[i][j][0] b2 = b2 + C[i][j][1] c2 = c2 + C[i][j][2] Ta2, Tb2, Tc2 = a2 / n2, b2 / n2, c2 / n2 for i in range(1300, 1500): #1300,1500 for j in range(1500, 1700): #1500,1700 D[i][j] = imag.getpixel((i, j)) for i in range(1300, 1500): #1300,1500 for j in range(1500, 1700): #1500,1700 n3 = n3 + 1 a3 = a3 + D[i][j][0] b3 = b3 + D[i][j][1] c3 = c3 + D[i][j][2] Ta3, Tb3, Tc3 = a3 / n3, b3 / n3, c3 / n3 mctrR1, mctrG1, mctrB1 = (Ta2 + Ta3) / 2, (Tb2 + Tb3) / 2, (Tc2 + Tc3) / 2 L = [(mctrR - mctrR1), (mctrG - mctrG1), (mctrB - mctrB1)] sommasample = mctrR + mctrG sommactr = mctrR1 + mctrG1 res = (sommasample * 100) / sommactr if res > 80: if res > 100: res = 100 img.clear_widgets() rec = Button(size_hint=(0.40, 0.39), pos_hint={ 'center_x': .5, 'center_y': .6 }, background_normal='green.png') label0 = Label(text='Result:', font_size='30sp', bold=True, valign='top', color=(0, 0, 0, .9), pos_hint={ 'center_x': .5, 'center_y': .7 }) label1 = Label(text='Cell viability ' + str(res) + "%", font_size='30sp', valign='top', color=(0, 0, 0, .9), pos_hint={ 'center_x': .5, 'center_y': .6 }) label2 = Label(text='SAFE', italic=True, bold=True, font_size='30sp', valign='top', color=(0, 0, 0, .9), pos_hint={ 'center_x': .5, 'center_y': .5 }) button1 = Button(text='Home', background_normal='bottone3.png', size_hint=(0.11, 0.10), pos_hint={ 'center_x': .1, 'center_y': .1 }) button1.bind(on_press=img.start) button4 = Button(text='Save Results', background_normal='bottone3.png', size_hint=(0.22, 0.12), bold=True, font_size='20sp', pos_hint={ 'center_x': .5, 'center_y': .1 }) button4.bind(on_press=img.show_save) dang2 = Image(source="./logo.png", size_hint=(1, .15), pos_hint={ 'center_x': .9, 'center_y': .1 }) img.add_widget(button4) img.add_widget(button1) img.add_widget(rec) img.add_widget(label0) img.add_widget(label1) img.add_widget(label2) img.add_widget(dang2) if res < 80 and res >= 40: img.clear_widgets() rec = Button(size_hint=(0.40, 0.39), pos_hint={ 'center_x': .5, 'center_y': .6 }, background_normal='yellow.png') label0 = Label(text='Result:', font_size='30sp', bold=True, valign='top', color=(0, 0, 0, .9), pos_hint={ 'center_x': .5, 'center_y': .7 }) label1 = Label(text='Cell viability ' + str(res) + "%", font_size='30sp', valign='top', color=(0, 0, 0, .9), pos_hint={ 'center_x': .5, 'center_y': .6 }) label2 = Label(text="HARMFUL", italic=True, bold=True, font_size='30sp', valign='top', color=(0, 0, 0, .9), pos_hint={ 'center_x': .5, 'center_y': .5 }) button1 = Button(text='Home', background_normal='bottone3.png', size_hint=(0.11, 0.10), pos_hint={ 'center_x': .1, 'center_y': .1 }) button1.bind(on_press=img.start) button4 = Button(text='Save Results', background_normal='bottone3.png', size_hint=(0.22, 0.12), bold=True, font_size='20sp', pos_hint={ 'center_x': .5, 'center_y': .1 }) button4.bind(on_press=img.show_save) dang2 = Image(source="./logo.png", size_hint=(1, .15), pos_hint={ 'center_x': .9, 'center_y': .1 }) img.add_widget(button4) img.add_widget(button1) img.add_widget(rec) img.add_widget(label0) img.add_widget(label1) img.add_widget(label2) img.add_widget(dang2) elif res < 40: img.clear_widgets() rec = Button(size_hint=(0.40, 0.39), pos_hint={ 'center_x': .5, 'center_y': .6 }, background_normal='red.png') label0 = Label(text='Result:', font_size='30sp', bold=True, valign='top', color=(0, 0, 0, .9), pos_hint={ 'center_x': .5, 'center_y': .7 }) label1 = Label(text='Cell viability ' + str(res) + "%", font_size='30sp', valign='top', color=(0, 0, 0, .9), pos_hint={ 'center_x': .5, 'center_y': .6 }) label2 = Label(text='HIGHLY TOXIC', italic=True, bold=True, font_size='30sp', valign='top', color=(0, 0, 0, .9), pos_hint={ 'center_x': .5, 'center_y': .5 }) button1 = Button(text='Home', background_normal='bottone3.png', size_hint=(0.11, 0.10), pos_hint={ 'center_x': .1, 'center_y': .1 }) button1.bind(on_press=img.start) button4 = Button(text='Save Results', background_normal='bottone3.png', size_hint=(0.22, 0.12), bold=True, font_size='20sp', pos_hint={ 'center_x': .5, 'center_y': .1 }) button4.bind(on_press=img.show_save) dang2 = Image(source="./logo.png", size_hint=(1, .15), pos_hint={ 'center_x': .9, 'center_y': .1 }) img.add_widget(button4) img.add_widget(rec) img.add_widget(button1) img.add_widget(label0) img.add_widget(label1) img.add_widget(label2) img.add_widget(dang2)
class TwitterAPIUI(App): def credentialPopUp(self): # Pop up layout self.credentialsRootLayout = AnchorLayout(anchor_x='center', anchor_y='center', padding=(5, 5, 5, 5)) # Content Layout self.credentialsContentLayout = BoxLayout(orientation='vertical', spacing=20) self.consumerKey = TextInput(hint_text="CONSUMER KEY") self.consumerSecret = TextInput(hint_text="CONSUMER SECRET KEY") self.accessToken = TextInput(hint_text="ACCESS_TOKEN") self.accessTokenSecret = TextInput(hint_text="ACCESS_TOKEN_SECRET") self.submitCreds = Button(text='Login', on_press=self.subCredentials) # Add items to the pop up layout self.credentialsContentLayout.add_widget(self.consumerKey) self.credentialsContentLayout.add_widget(self.consumerSecret) self.credentialsContentLayout.add_widget(self.accessToken) self.credentialsContentLayout.add_widget(self.accessTokenSecret) self.credentialsContentLayout.add_widget(self.submitCreds) # Attach the content Layout to the root layout self.credentialsRootLayout.add_widget(self.credentialsContentLayout) # Create the pop up and attach the layout self.popup = Popup(title="Credentials", content=self.credentialsRootLayout, auto_dismiss=False) self.popup.open() def build(self): Window.size = (600, 400) self.title = 'Twitter API' self.root = RelativeLayout() self.CONSUMER_KEY = None self.CONSUMER_SECRET = None self.ACCESS_TOKEN = None self.ACCESS_TOKEN_SECRET = None self.twitter = None self.followers = [] self.following = [] self.non_followers = [] # Get API credentials First # self.credentialPopUp() self.buttonLayout = BoxLayout(orientation='vertical', spacing=5, size_hint=(.2, .2), pos_hint={ 'x': .79, 'y': .75 }) self.getFollowers = Button(text="Get Followers", on_press=self.get_followers) self.getFollowing = Button(text="Get Following", on_press=self.get_following) self.newTweet = Button(text="New Tweet") self.buttonLayout.add_widget(self.newTweet) self.buttonLayout.add_widget(self.getFollowers) self.buttonLayout.add_widget(self.getFollowing) self.data = [{'text': str(x)} for x in range(20)] self.itemLayout = RV(self.data) self.root.add_widget(RV(self.data)) self.root.add_widget(self.buttonLayout) return self.root def get_followers(self): self.followers = self.twitter.get_followers() # Save the list to a json file self.twitter.save_file('followers', self.followers) # TODO : Figure out whether how the recyclerview displays dictonaries self.itemLayout.data = self.followers # Refresh the list self.itemLayout.refresh_from_data() def get_following(self): self.following = self.twitter.get_following() # Save the list to a json file self.twitter.save_file('following', self.following) # TODO : Figure out whether how the recyclerview displays dictonaries self.itemLayout.data = self.following # Refresh the list self.itemLayout.refresh_from_data() def subCredentials(self, instance): if self.consumerKey.text.find( " ") > -1 or self.consumerSecret.text.find( " ") > -1 or self.accessToken.text.find( " ") > -1 or self.accessTokenSecret.text.find( " ") > -1: # TODO : Make pop up message print("Token cannot have spaces") return elif self.consumerKey.text == "" or self.consumerSecret.text == "" or self.accessToken.text == "" or self.accessTokenSecret.text == "": # TODO : Make pop up message print("Fill in the input spaces") return else: self.ACCESS_TOKEN = self.accessToken.text self.ACCESS_TOKEN_SECRET = self.accessTokenSecret.text self.CONSUMER_KEY = self.consumerKey.text self.CONSUMER_SECRET = self.consumerSecret.text self.twitter = Twitter(self.CONSUMER_KEY, self.CONSUMER_SECRET, self.ACCESS_TOKEN, self.ACCESS_TOKEN_SECRET) self.popup.dismiss() self.buttonLayout.add_widget(self.newTweet) self.buttonLayout.add_widget(self.getFollowers) self.buttonLayout.add_widget(self.getFollowing)
class MyApp(App): # layout def build(self): layout = BoxLayout(orientation='vertical') self.lbl1 = Label(text="Amanda: Welcome\n",size_hint=(1,0.86),color=(255,255,255,1),font_size=25,text_size=(1150,450),halign='left',valign='bottom') layout.add_widget(self.lbl1) layout2 = BoxLayout(size_hint=(1,0.14)) self.txt1 = TextInput(text='',size_hint=(0.8,1),font_size=20) layout2.add_widget(self.txt1) self.btn1 = Button(text="Submit",size_hint=(0.2,1)) self.btn1.bind(on_press=self.buttonClicked) # self.btn1.bind(on_press=self.open_popup) layout2.add_widget(self.btn1) layout.add_widget(layout2) return layout def show_popup(self): print ("hi") content=Label(text="thinking") self.pop_up = Popup(title='Test popup', size_hint=(None, None), size=(256, 256), content=content, disabled=True) self.pop_up.open() # def open_popup(self,instance): # self.popup.open() # Clock.schedule_once(self.do_stuff(), 0) # def do_stuff(self): # self.buttonClicked() # self.popup.dismiss() # class myApp(App): # def build(self): # self.btn = Button(text='Run') # self.btn.bind(on_press = self.open_popup) # self.box = BoxLayout() # self.box.add_widget(self.btn) # self.popup = Popup(title='',content=Label(text='Loading')) # return self.box # def open_popup(self, instance): # self.popup.open() # t = threading.Thread(target=self.do_stuff).start() # def do_stuff(self): # self.box.clear_widgets() # self.box.add_widget(MyGraph()) # self.popup.dismiss() ################################################################################ # def __init__(self, **kwargs): # self._keyboard = Window.request_keyboard(self._keyboard_closed, self) # self._keyboard.bind(on_key_down=self._on_keyboard_down) # 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] == 'enter': # self.btn1.buttonClicked() # return True # button click function def dismiss_popup(self): print ("closing") self.pop_up.dismiss() def buttonClicked(self,button): # mythread = threading.Thread(target=self.show_popup) # mythread.start() # mythread.join() # print "clicked" myinput = self.txt1.text self.lbl1.text = self.lbl1.text + "\nUser: "******"" for i in temp: try: z = i[1] if (dict[z] != None): part_speech = dict[z] else: part_speech = 'NOUN' if(part_speech == 'NOUN'): word = wn.morphy(i[0],wn.NOUN) elif(part_speech == 'VERB'): word = wn.morphy(i[0],wn.VERB) elif(part_speech == 'ADV'): word = wn.morphy(i[0],wn.ADV) elif(part_speech == 'ADJ'): word = wn.morphy(i[0],wn.ADJ) word1 = wn.synsets(word)[0].lemmas()[0].name() if i[0] in grade_codes: word1 = i[0] except: word1 = i[0] new_sentence = new_sentence+" "+word1.lower() new_sentence = remove_aiml_char(new_sentence) #----------uncomment to debug---------------------- if DEBUG: #printing first output matchedPattern = k.matchedPattern(myinput) response = k.respond(myinput) try: if SHOW_MATCHES: print ("Matched Pattern: ") print (k.formatMatchedPattern(matchedPattern[0])) pattern = k.getPredicate("topic",'_global') print ("TOPIC:",pattern) else: print ("-------------------------") except: print ("No match found") print ("Normal Response: ",response) # printing after processing print ("--------------------------------") print ("new_sentence :",new_sentence) matchedPattern = k.matchedPattern(new_sentence) response = k.respond(new_sentence) try: if SHOW_MATCHES: print ("Matched Pattern: ") print (k.formatMatchedPattern(matchedPattern[0])) pattern = k.getPredicate("topic",'_global') print ("TOPIC:",pattern) else: print ("-------------------------") except: print ("No match found") print ("New Response: ",response) #-------------------------------------------------- response = k.respond(myinput) response1 = k.respond(new_sentence) if response1 != "" and response1[0] == '$': response = response1[1:] # print response # mythread = threading.Thread(target=self.dismiss_popup) # mythread.start() # mythread.join() # self.show_popup() self.lbl1.text = self.lbl1.text + "\nAmanda: "+response+"\n" self.txt1.text = ""
class mainApp(App): source = StringProperty(None) processName = StringProperty(None) result = ObjectProperty(None) threadProcess = ObjectProperty(None) popup = ObjectProperty(None) def build(self): self.source = "./backgroundDefault.jpg" self.pictureList = [] self.texture = Texture.create() self.texture.wrap="clamp_to_edge" self.customDropDown = CustomDropDown() root = RootWindow() return root def update_list_data(self, path, filename): exist = False if filename: print "Path : " + str(path) + " | Filename " + str(filename[0]) for i in self.root.ids["ViewPreProcess"].ids["SelectionList"].list_adapter.data: if filename is i.name: print "Filename "+str(Filename)+" already exist\n" exist = True if not exist: self.root.ids["ViewPreProcess"].ids["SelectionList"].update_list_data(path,filename) defPath = os.path.join(path, filename[0]) if re.search('.CR2',defPath): image = ImageRaw.ImageRaw(defPath).getndarray() #print "Append \n" self.pictureList.append(DataImage(path=filename[0],image=image)) h,l,r = image.shape self.texture = Texture.create(size=(l,h)) self.texture.blit_buffer(pbuffer = image.tostring(),bufferfmt="ushort",colorfmt='rgb') elif re.search('[.jpg|.png|.gif|.tiff]',defPath): image = io.imread(defPath) self.pictureList.append(DataImage(path=filename[0],image=image)) h,l,r = image.shape self.texture = Texture.create(size=(l,h)) self.texture.blit_buffer(pbuffer = image.tostring(),bufferfmt="ubyte",colorfmt='rgb') self.texture.flip_vertical() self.root.ids["ViewPreProcess"].ids["Image"].ids["currentImage"].texture = self.texture self.root.ids["ViewPreProcess"].ids["Image"].ids["currentImage"].size = self.texture.size self.root.ids["ViewPreProcess"].ids["Image"].ids["currentImage"].reload() def clear(self): self.root.ids["ViewPreProcess"].ids["Image"].ids["currentImage"].texture = Texture.create() self.root.ids["ViewPreProcess"].ids["Image"].ids["currentImage"].reload() self.pictureList = [] self.root.ids["ViewWindow"].ids["Image"].ids["currentImage"].texture = Texture.create() self.root.ids["ViewWindow"].ids["Image"].ids["currentImage"].reload() def preview(self): #self.root.ids["ViewPreProcess"].ids["SelectionList"].list_adapter.on_selection_change() select = self.root.ids["ViewPreProcess"].ids["SelectionList"].list_adapter.selection if select: print "Selection change to "+str(select[0].text) if re.search('.CR2',select[0].text): for i in self.pictureList: if i.path is select[0].text: print "Find Image\n" h,l,r = i.image.shape self.texture = Texture.create(size=(l,h)) self.texture.blit_buffer(pbuffer = i.image.tostring(),bufferfmt="ushort",colorfmt='rgb') else: if self.root.ids["ViewPreProcess"].ids["Explorer"].ids["icon_view_tab"].show_hidden: path = self.root.ids["ViewPreProcess"].ids["Explorer"].ids["list_view_tab"].path else: path = self.root.ids["ViewPreProcess"].ids["Explorer"].ids["icon_view_tab"].path self.texture = Image(source=os.path.join(path, select[0].text)).texture self.root.ids["ViewPreProcess"].ids["Image"].ids["currentImage"].texture = self.texture self.root.ids["ViewPreProcess"].ids["Image"].ids["currentImage"].reload() else: self.root.ids["ViewPreProcess"].ids["Image"].ids["currentImage"].texture = Texture.create() self.root.ids["ViewPreProcess"].ids["Image"].ids["currentImage"].reload() def remove(self): select = self.root.ids["ViewPreProcess"].ids["SelectionList"].list_adapter.selection if select: if re.search('.CR2',select[0].text): for i in self.pictureList: if i.path is select[0].text: print "Remove "+str(i.path) self.pictureList.remove(i) self.root.ids["ViewPreProcess"].ids["SelectionList"].remove(select[0].text) def startProcess(self): self.threadProcess = threading.Thread(target=self.process, args=()) self.threadProcess.start() self.popup = Popup(title='Render State', content=Label(text='Render in progress. It may take more than a minute'), auto_dismiss=False) self.popup.open() self.count = 0 Clock.schedule_interval(self.updatePopup, 0.5) def updatePopup(self,dt): if self.threadProcess.isAlive(): if self.count == 0: self.popup.content = Label(text='Render in progress. It may take more than a minute.') if self.count == 1: self.popup.content = Label(text='Render in progress. It may take more than a minute..') if self.count == 2: self.popup.content = Label(text='Render in progress. It may take more than a minute...') self.count = self.count+1 if self.count == 3 : self.count = 0 else: self.popup.dismiss() Clock.unschedule(self.updatePopup) def process(self): if len(self.pictureList) > 1: dataList = [] for i in self.pictureList: dataList.append(i.image) print "SizeData : " + str(len(dataList)) if self.processName is "MasterDark": print "processMasterDark" self.result = AstroProcess.processMasterDark(dataList) imageio.imsave('../../Pictures_test/MasterDark.tiff', self.result) elif self.processName is "MasterFlat": print "processMasterFlat" self.result = AstroProcess.processMasterFlat(dataList) imageio.imsave('../../Pictures_test/MasterFlat.tiff', self.result,'../../Pictures_test/MasterDark.tiff') elif self.processName is "MasterBias": print "processMasterBias" self.result = AstroProcess.processMasterBias(dataList) imageio.imsave('../../Pictures_test/MasterFlat.tiff', self.result) elif self.processName is "Registration": print "Registration" self.root.manager.current = 'MainView' h,l,r = self.result.shape self.texture = Texture.create(size=(l,h)) self.texture.blit_buffer(pbuffer = self.result.tostring(),bufferfmt="ushort",colorfmt='rgb') self.root.ids["ViewWindow"].ids["Image"].ids["currentImage"].texture = self.texture self.root.ids["ViewWindow"].ids["Image"].ids["currentImage"].reload() del self.pictureList self.clear() elif len(self.pictureList) == 1: if self.processName is "medianFilter": print "medianFilter" self.result = TreatmentProcess.medianFilter(self.pictureList[0].image) print self.result elif self.processName is "logCorrect": print "logCorrect" self.result = TreatmentProcess.logCorrect(self.pictureList[0].image) elif self.processName is "gammaCorrect": print "gammaCorrect" self.result = TreatmentProcess.gammaCorrect(self.pictureList[0].image) elif self.processName is "luminosityCorrect": print "luminosityCorrect" self.result = TreatmentProcess.luminosityCorrect(self.pictureList[0].image) elif self.processName is "saturationCorrect": print "saturationCorrect" self.result = TreatmentProcess.saturationCorrect(self.pictureList[0].image) elif self.processName is "deletionGreenDominant": print "deletionGreenDominant" self.result = TreatmentProcess.deletionGreenDominant(self.pictureList[0].image) self.root.manager.current = 'MainView' h,l,r = self.result.shape self.texture = Texture.create(size=(l,h)) self.texture.blit_buffer(pbuffer = self.result.tostring(),bufferfmt="ubyte",colorfmt='rgb') self.root.ids["ViewWindow"].ids["Image"].ids["currentImage"].texture = self.texture self.root.ids["ViewWindow"].ids["Image"].ids["currentImage"].reload() else: print "No enought pictures\n" def loadFile(self): if self.root.ids["ViewFileChooser"].ids["Explorer"].ids["icon_view_tab"].show_hidden: path = self.root.ids["ViewFileChooser"].ids["Explorer"].ids["list_view_tab"].path selection = self.root.ids["ViewFileChooser"].ids["Explorer"].ids["list_view_tab"].selection else: path = self.root.ids["ViewFileChooser"].ids["Explorer"].ids["icon_view_tab"].path selection = self.root.ids["ViewFileChooser"].ids["Explorer"].ids["icon_view_tab"].selection if selection: self.root.manager.current = 'MainView' di = self.pictureList[len(self.pictureList)-1] self.pictureList = [] self.pictureList.append(di) self.root.ids["ViewWindow"].ids["Image"].ids["currentImage"].texture = self.texture self.root.ids["ViewWindow"].ids["Image"].ids["currentImage"].reload() else: print "No picture selected\n" def findFile(self): if self.root.ids["ViewPreProcess"].ids["Explorer"].ids["icon_view_tab"].show_hidden: path = self.root.ids["ViewPreProcess"].ids["Explorer"].ids["list_view_tab"].path else: path = self.root.ids["ViewPreProcess"].ids["Explorer"].ids["icon_view_tab"].path file_system = FileSystemLocal() print "Path : " + str(path) for i in file_system.listdir(path): if re.search(".CR2",i): print "I : " + str(i) filename = [] filename.append(i) self.update_list_data(path,filename) def showProcess(self): self.customDropDown.open(self.root.ids["ViewWindow"].ids["Menu"].ids["editbutton"]) def saveFile(self): if not self.result == None: imageio.imsave('../../Pictures_test/'+'render.tiff', self.result) print "Save !"
class main(BoxLayout): charge = 1. particles = [] init_conds = [] plot_texture = ObjectProperty() def __init__(self, **kwargs): super(main, self).__init__(**kwargs) self.pot = Phi() self.set_texture() self.time = 0. self.T = 45 self.speedindex = 3 self.change_speed() self.running = False self.paused = False self.ready = False self.previewtimer = Clock.schedule_interval(self.preview, 0.04) self.previewlist = [] self.progress = 0. def set_texture(self): L = 200 dx = 1 self.nx = int(L / dx) self.im = np.zeros((self.nx, self.nx), dtype=np.uint8) self.plot_texture = Texture.create(size=self.im.shape, colorfmt='luminance', bufferfmt='uint') def background(self): xx, yy, = np.meshgrid( np.linspace(-L / 2., L / 2., self.nx, endpoint=True), np.linspace(-L / 2., L / 2., self.nx, endpoint=True)) self.im = np.zeros((self.nx, self.nx)) if (self.pot.functions.size == 0): self.im = np.uint8(self.im) else: self.im = self.pot.val(xx, yy) self.im = self.im + np.abs(self.im.min()) self.im = np.uint8(255. * (self.im / self.im.max())) def update_texture(self): L = 200 dx = 1 self.nx = int(L / dx) with self.plotbox.canvas: cx = self.plotbox.pos[0] cy = self.plotbox.pos[1] w = self.plotbox.size[0] h = self.plotbox.size[1] b = min(w, h) self.plot_texture.blit_buffer(self.im.reshape(self.im.size), colorfmt='luminance') Color(1.0, 1.0, 1.0) Rectangle(texture=self.plot_texture, pos=(cx, cy), size=(b, b)) def update_pos(self, touch): w = self.plotbox.size[0] h = self.plotbox.size[1] b = min(w, h) scale = b / 200. x = (touch.pos[0] - b / 2.) / scale y = (touch.pos[1] - b / 2.) / scale if (self.menu.current_tab.text == 'Potentials'): self.param0slider.value = x self.param1slider.value = y if (self.menu.current_tab.text == 'Particles'): self.x0slider.value = x self.y0slider.value = y def update_angle(self, touch): w = self.plotbox.size[0] h = self.plotbox.size[1] b = min(w, h) scale = b / 200. x = (touch.pos[0] - b / 2.) / scale y = (touch.pos[1] - b / 2.) / scale xdif = x - self.x0slider.value ydif = y - self.y0slider.value if (np.abs(xdif) < 0.01): if (ydif > 0): angle = np.pi / 2. else: angle = -np.pi / 2. elif (xdif > 0 and ydif > 0): angle = np.arctan((ydif) / (xdif)) elif (xdif < 0 and ydif < 0): angle = np.arctan((ydif) / (xdif)) + np.pi elif (xdif < 0 and ydif > 0): angle = np.arctan((ydif) / (xdif)) + np.pi else: angle = np.arctan((ydif) / (xdif)) + 2 * np.pi if (np.abs(x) < 100. and np.abs(y) < 100.): # if(self.partmenu.current_tab.text == 'Single'): # v = np.sqrt(self.vx0slider.value**2 + self.vy0slider.value**2) # self.vx0slider.value = round(v*np.cos(angle),0) # self.vy0slider.value = round(v*np.sin(angle),0) if (self.partmenu.current_tab.text == 'Dispersion'): self.thetaslider.value = int(round(angle * (180 / np.pi), 0)) if (self.partmenu.current_tab.text == 'Line'): self.thetalslider.value = int(round(angle * (180 / np.pi), 0)) # if(self.partmenu.current_tab.text == 'Free Part.'): # v = np.sqrt(self.vxfslider.value**2 + self.vyfslider.value**2) # self.vxfslider.value = round(v*np.cos(angle),1) # self.vyfslider.value = round(v*np.sin(angle),1) def add_pot_list(self): self.stop() if (self.potmenu.current_tab.text == 'Gauss'): self.pot.add_function(gauss, dgaussx, dgaussy, [ self.param0slider.value, self.param1slider.value, self.param2gslider.value, self.param3gslider.value ]) elif (self.potmenu.current_tab.text == 'Woods-Saxon'): self.pot.add_function(woodsaxon, dwoodsaxonx, dwoodsaxony, [ self.param0slider.value, self.param1slider.value, self.param2wsslider.value, self.param3wsslider.value / 2., self.param4wsslider.value / 2., self.param5wsslider.value ]) self.background() self.update_texture() self.ready = False # self.pcbutton.text = "Compute" self.pcbutton.background_normal = 'Icons/compute.png' self.pcbutton.background_down = 'Icons/computeb.png' self.statuslabel.text = 'Not Ready' def reset_pot_list(self): self.stop() self.pot.clear() self.plotbox.canvas.clear() self.background() self.ready = False # self.pcbutton.text = "Compute" self.pcbutton.background_normal = 'Icons/compute.png' self.pcbutton.background_down = 'Icons/computeb.png' self.statuslabel.text = 'Not Ready' def add_particle_list(self): self.stop() if (self.partmenu.current_tab.text == 'Single'): self.particles.append( Particle(self.massslider.value, self.charge, dt)) self.init_conds.append([ self.x0slider.value, self.y0slider.value, self.vx0slider.value, self.vy0slider.value ]) self.previewlist.append('Single') self.previewlist.append([ self.x0slider.value, self.y0slider.value, self.vx0slider.value, self.vy0slider.value ]) elif (self.partmenu.current_tab.text == 'Dispersion'): delta = self.alphaslider.value / (self.nslider.value - 1) theta = self.thetaslider.value - self.alphaslider.value / 2. for k in range(0, int(self.nslider.value)): vx = self.vslider.value * np.cos(theta * (np.pi / 180.)) vy = self.vslider.value * np.sin(theta * (np.pi / 180.)) self.particles.append( Particle(self.massslider.value, self.charge, dt)) self.init_conds.append( [self.x0slider.value, self.y0slider.value, vx, vy]) theta = theta + delta self.previewlist.append('Dispersion') self.previewlist.append([ self.x0slider.value, self.y0slider.value, self.vslider.value, self.thetaslider.value, self.alphaslider.value ]) elif (self.partmenu.current_tab.text == 'Line'): delta = self.lslider.value / (self.nlslider.value - 1) r = np.array([self.x0slider.value, self.y0slider.value ]) - self.lslider.value * 0.5 * np.array([ -np.sin(self.thetalslider.value * (np.pi / 180.)), np.cos(self.thetalslider.value * (np.pi / 180.)) ]) vx = self.vlslider.value * np.cos(self.thetalslider.value * (np.pi / 180.)) vy = self.vlslider.value * np.sin(self.thetalslider.value * (np.pi / 180.)) for k in range(0, int(self.nlslider.value)): self.particles.append( Particle(self.massslider.value, self.charge, dt)) self.init_conds.append([r[0], r[1], vx, vy]) r = r + delta * np.array([ -np.sin(self.thetalslider.value * (np.pi / 180.)), np.cos(self.thetalslider.value * (np.pi / 180.)) ]) self.previewlist.append('Line') self.previewlist.append([ self.x0slider.value, self.y0slider.value, self.nlslider.value, self.vlslider.value, self.thetalslider.value, self.lslider.value ]) elif (self.partmenu.current_tab.text == 'Free Part.'): x, y = acceptreject( int(self.nfslider.value), -100, 100, 1 / np.sqrt(2 * np.pi * self.sigfslider.value**2), freepart, [ self.x0slider.value, self.y0slider.value, self.vxfslider.value * self.massslider.value, self.vyfslider.value * self.massslider.value, self.sigfslider.value ]) px, py = acceptreject( int(self.nfslider.value), -10, 10, 1 / (np.sqrt(np.pi)), freepartp, [ self.x0slider.value, self.y0slider.value, self.vxfslider.value * self.massslider.value, self.vyfslider.value * self.massslider.value, self.sigfslider.value ]) for i in range(0, int(self.nfslider.value)): self.particles.append( Particle(self.massslider.value, self.charge, dt)) self.init_conds.append([ x[i], y[i], px[i] / self.massslider.value, py[i] / self.massslider.value ]) self.previewlist.append('Free Part.') self.previewlist.append([ self.x0slider.value, self.y0slider.value, self.vxfslider.value, self.vyfslider.value, self.sigfslider.value ]) self.ready = False # self.pcbutton.text = "Compute" self.pcbutton.background_normal = 'Icons/compute.png' self.pcbutton.background_down = 'Icons/computeb.png' self.statuslabel.text = 'Not Ready' def reset_particle_list(self): self.stop() self.particles = [] self.init_conds = [] self.previewlist = [] self.ready = False # self.pcbutton.text = "Compute" self.pcbutton.background_normal = 'Icons/compute.png' self.pcbutton.background_down = 'Icons/computeb.png' self.statuslabel.text = 'Not Ready' def playcompute(self): if (self.ready == False): self.statuslabel.text = 'Computing...' Clock.schedule_once(self.computation) elif (self.ready == True): if (self.running == False): self.timer = Clock.schedule_interval(self.animate, 0.04) self.running = True self.paused = False elif (self.running == True): pass def computation(self, *args): print('---Computation Start---') self.progress = 0. start = time.time() for i, p in enumerate(self.particles, 0): p.ComputeTrajectoryF(self.init_conds[i], self.T, self.pot) print('Particle ', i + 1, ' done') self.progress += 1 # self.energycheck() print('---Computation End---') print('Exec time = ', time.time() - start) self.ready = True # self.pcbutton.text = "Play" self.pcbutton.background_normal = 'Icons/play.png' self.pcbutton.background_down = 'Icons/playb.png' self.statuslabel.text = 'Ready' def updateprogress(self, *args): val = (self.progress + 1) / len(self.particles) self.progressbar.value = val * 100 def energycheck(self): ok = 0 tol = 10**(-6) for i, p in enumerate(self.particles, 0): # if(p.Energy().std() < tol): if (np.all(np.diff(p.Energy()) < tol)): ok += 1 print('{} particles conserved the total energy up to {}'.format( ok, tol)) print('{} particles did not conserve the total energy'.format( len(self.particles) - ok)) def pause(self): if (self.running == True): self.paused = True self.timer.cancel() self.running = False else: pass def stop(self): self.pause() self.paused = False self.time = 0 self.plotbox.canvas.clear() self.update_texture() def change_speed(self): sl = [1, 2, 5, 10] if (self.speedindex == len(sl) - 1): self.speedindex = 0 else: self.speedindex += 1 self.speed = sl[self.speedindex] self.speedbutton.text = str(self.speed) + 'x' def save(self, path, name, comp=False): if (comp == False): self.particles = [] self.init_conds = [] self.previewlist = [] savedata = np.array([ self.pot.functions, self.pot.dfunctionsx, self.pot.dfunctionsy, self.particles, self.init_conds, self.previewlist ]) with open(os.path.join(path, name + '.dat'), 'wb') as file: pickle.dump(savedata, file) self.dismiss_popup() def savepopup(self): content = savewindow(save=self.save, cancel=self.dismiss_popup) self._popup = Popup(title='Save File', content=content, size_hint=(1, 1)) self._popup.open() def load(self, path, name, demo=False): self.stop() with open(os.path.join(path, name[0]), 'rb') as file: savedata = pickle.load(file) self.pot.functions = savedata[0] self.pot.dfunctionsx = savedata[1] self.pot.dfunctionsy = savedata[2] self.particles = savedata[3] self.init_conds = savedata[4] self.previewlist = savedata[5] if (len(self.particles) > 0): if (self.particles[0].steps.size > 1): self.ready = True # self.pcbutton.text = "Play" self.pcbutton.background_normal = 'Icons/play.png' self.pcbutton.background_down = 'Icons/playb.png' self.statuslabel.text = 'Ready' print('Loaded simulation {} with computation'.format(name)) else: self.ready = False # self.pcbutton.text = "Compute" self.pcbutton.background_normal = 'Icons/compute.png' self.pcbutton.background_down = 'Icons/computeb.png' self.statuslabel.text = 'Not Ready' print('Loaded simulation {}'.format(name)) self.background() self.update_texture() if (demo == False): self.dismiss_popup() def loadpopup(self): content = loadwindow(load=self.load, cancel=self.dismiss_popup) self._popup = Popup(title='Load File', content=content, size_hint=(1, 1)) self._popup.open() def dismiss_popup(self): self._popup.dismiss() def timeinversion(self): if (self.ready == True): self.pause() t = self.time self.stop() reversedpart = [] reversedconds = [] reversedpreview = [] for p in self.particles: reversedpart.append( Particle(self.massslider.value, self.charge, dt)) reversedconds.append( [p.trax(t), p.tray(t), -p.travx(t), -p.travy(t)]) reversedpreview.append('Single') reversedpreview.append( [p.trax(t), p.tray(t), -p.travx(t), -p.travy(t)]) self.particles = reversedpart self.init_conds = reversedconds self.previewlist = reversedpreview self.ready = False # self.pcbutton.text = "Compute" self.pcbutton.background_normal = 'Icons/compute.png' self.pcbutton.background_down = 'Icons/computeb.png' self.statuslabel.text = 'Not Ready' else: pass def preview(self, interval): if (self.running == False and self.paused == False): if (self.menu.current_tab.text == 'Particles'): if (self.partmenu.current_tab.text == 'Single'): w = self.plotbox.size[0] h = self.plotbox.size[1] b = min(w, h) scalew = b / 200. scaleh = b / 200. self.plotbox.canvas.clear() self.update_texture() with self.plotbox.canvas: Color(1.0, 0.5, 0.0) Ellipse( pos=(self.x0slider.value * scalew + w / 2. - 5., self.y0slider.value * scaleh + h / 2. - 5.), size=(10, 10)) Line(points=[ self.x0slider.value * scalew + w / 2., self.y0slider.value * scaleh + h / 2., self.vx0slider.value * scalew + w / 2. + self.x0slider.value * scalew, self.vy0slider.value * scalew + w / 2. + self.y0slider.value * scalew ]) elif (self.partmenu.current_tab.text == 'Dispersion'): w = self.plotbox.size[0] h = self.plotbox.size[1] b = min(w, h) scalew = b / 200. scaleh = b / 200. vx1 = self.vslider.value * np.cos( (self.thetaslider.value - self.alphaslider.value / 2.) * (np.pi / 180.)) vy1 = self.vslider.value * np.sin( (self.thetaslider.value - self.alphaslider.value / 2.) * (np.pi / 180.)) vx2 = self.vslider.value * np.cos( (self.thetaslider.value + self.alphaslider.value / 2.) * (np.pi / 180.)) vy2 = self.vslider.value * np.sin( (self.thetaslider.value + self.alphaslider.value / 2.) * (np.pi / 180.)) self.plotbox.canvas.clear() self.update_texture() with self.plotbox.canvas: Color(1.0, 0.5, 0.0) Line(points=[ self.x0slider.value * scalew + w / 2., self.y0slider.value * scaleh + h / 2., vx1 * scalew + w / 2. + self.x0slider.value * scalew, vy1 * scalew + w / 2. + self.y0slider.value * scalew ]) Line(points=[ self.x0slider.value * scalew + w / 2., self.y0slider.value * scaleh + h / 2., vx2 * scalew + w / 2. + self.x0slider.value * scalew, vy2 * scalew + w / 2. + self.y0slider.value * scalew ]) elif (self.partmenu.current_tab.text == 'Line'): w = self.plotbox.size[0] h = self.plotbox.size[1] b = min(w, h) scalew = b / 200. scaleh = b / 200. r1 = np.array([self.x0slider.value, self.y0slider.value ]) - self.lslider.value * 0.5 * np.array([ -np.sin(self.thetalslider.value * (np.pi / 180.)), np.cos(self.thetalslider.value * (np.pi / 180.)) ]) r2 = np.array([self.x0slider.value, self.y0slider.value ]) + self.lslider.value * 0.5 * np.array([ -np.sin(self.thetalslider.value * (np.pi / 180.)), np.cos(self.thetalslider.value * (np.pi / 180.)) ]) r = r1 delta = self.lslider.value / (self.nlslider.value - 1) vx = self.vlslider.value * np.cos(self.thetalslider.value * (np.pi / 180.)) vy = self.vlslider.value * np.sin(self.thetalslider.value * (np.pi / 180.)) self.plotbox.canvas.clear() self.update_texture() with self.plotbox.canvas: Color(1.0, 0.5, 0.0) Line(points=[ r1[0] * scalew + w / 2., r1[1] * scaleh + h / 2., r2[0] * scalew + w / 2., r2[1] * scaleh + h / 2. ]) for k in range(0, int(self.nlslider.value)): Line(points=[ r[0] * scalew + w / 2., r[1] * scaleh + h / 2., r[0] * scalew + w / 2. + vx * scalew, r[1] * scaleh + h / 2. + vy * scalew ]) r = r + delta * np.array([ -np.sin(self.thetalslider.value * (np.pi / 180.)), np.cos(self.thetalslider.value * (np.pi / 180.)) ]) elif (self.partmenu.current_tab.text == 'Free Part.'): w = self.plotbox.size[0] h = self.plotbox.size[1] b = min(w, h) scalew = b / 200. scaleh = b / 200. self.plotbox.canvas.clear() self.update_texture() with self.plotbox.canvas: Color(1.0, 0.5, 0.0) Line(circle=(self.x0slider.value * scalew + w / 2., self.y0slider.value * scaleh + h / 2., self.sigfslider.value * scalew)) Line(points=[ self.x0slider.value * scalew + w / 2., self.y0slider.value * scaleh + h / 2., self.vxfslider.value * scalew + w / 2. + self.x0slider.value * scalew, self.vyfslider.value * scalew + w / 2. + self.y0slider.value * scalew ]) else: self.plotbox.canvas.clear() self.update_texture() else: self.plotbox.canvas.clear() self.update_texture() with self.plotbox.canvas: for i in range(0, len(self.previewlist), 2): if (self.previewlist[i] == 'Single'): x0 = self.previewlist[i + 1][0] y0 = self.previewlist[i + 1][1] vx0 = self.previewlist[i + 1][2] vy0 = self.previewlist[i + 1][3] w = self.plotbox.size[0] h = self.plotbox.size[1] b = min(w, h) scalew = b / 200. scaleh = b / 200. Color(0.0, 0.0, 1.0) Ellipse(pos=(x0 * scalew + w / 2. - 5., y0 * scaleh + h / 2. - 5.), size=(10, 10)) Line(points=[ x0 * scalew + w / 2., y0 * scaleh + h / 2., vx0 * scalew + w / 2. + x0 * scalew, vy0 * scalew + w / 2. + y0 * scalew ]) if (self.previewlist[i] == 'Dispersion'): x0 = self.previewlist[i + 1][0] y0 = self.previewlist[i + 1][1] v = self.previewlist[i + 1][2] theta = self.previewlist[i + 1][3] alpha = self.previewlist[i + 1][4] w = self.plotbox.size[0] h = self.plotbox.size[1] b = min(w, h) scalew = b / 200. scaleh = b / 200. vx1 = v * np.cos((theta - alpha / 2.) * (np.pi / 180.)) vy1 = v * np.sin((theta - alpha / 2.) * (np.pi / 180.)) vx2 = v * np.cos((theta + alpha / 2.) * (np.pi / 180.)) vy2 = v * np.sin((theta + alpha / 2.) * (np.pi / 180.)) with self.plotbox.canvas: Color(0.0, 0.0, 1.0) Line(points=[ x0 * scalew + w / 2., y0 * scaleh + h / 2., vx1 * scalew + w / 2. + x0 * scalew, vy1 * scalew + w / 2. + y0 * scalew ]) Line(points=[ x0 * scalew + w / 2., y0 * scaleh + h / 2., vx2 * scalew + w / 2. + x0 * scalew, vy2 * scalew + w / 2. + y0 * scalew ]) if (self.previewlist[i] == 'Line'): x0 = self.previewlist[i + 1][0] y0 = self.previewlist[i + 1][1] n = self.previewlist[i + 1][2] v = self.previewlist[i + 1][3] theta = self.previewlist[i + 1][4] l = self.previewlist[i + 1][5] w = self.plotbox.size[0] h = self.plotbox.size[1] b = min(w, h) scalew = b / 200. scaleh = b / 200. r1 = np.array([x0, y0]) - l * 0.5 * np.array([ -np.sin(theta * (np.pi / 180.)), np.cos(theta * (np.pi / 180.)) ]) r2 = np.array([x0, y0]) + l * 0.5 * np.array([ -np.sin(theta * (np.pi / 180.)), np.cos(theta * (np.pi / 180.)) ]) r = r1 delta = l / (n - 1) vx = v * np.cos(theta * (np.pi / 180.)) vy = v * np.sin(theta * (np.pi / 180.)) with self.plotbox.canvas: Color(0.0, 0.0, 1.0) Line(points=[ r1[0] * scalew + w / 2., r1[1] * scaleh + h / 2., r2[0] * scalew + w / 2., r2[1] * scaleh + h / 2. ]) for k in range(0, int(self.nlslider.value)): Line(points=[ r[0] * scalew + w / 2., r[1] * scaleh + h / 2., r[0] * scalew + w / 2. + vx * scalew, r[1] * scaleh + h / 2. + vy * scalew ]) r = r + delta * np.array([ -np.sin(theta * (np.pi / 180.)), np.cos(theta * (np.pi / 180.)) ]) if (self.previewlist[i] == 'Free Part.'): x0 = self.previewlist[i + 1][0] y0 = self.previewlist[i + 1][1] vx = self.previewlist[i + 1][2] vy = self.previewlist[i + 1][3] sig = self.previewlist[i + 1][4] w = self.plotbox.size[0] h = self.plotbox.size[1] b = min(w, h) scalew = b / 200. scaleh = b / 200. with self.plotbox.canvas: Color(0.0, 0.0, 1.0) Line(circle=(x0 * scalew + w / 2., y0 * scaleh + h / 2., sig * scalew)) Line(points=[ x0 * scalew + w / 2., y0 * scaleh + h / 2., vx * scalew + w / 2. + x0 * scalew, vy * scalew + w / 2. + y0 * scalew ]) def animate(self, interval): w = self.plotbox.size[0] h = self.plotbox.size[1] b = min(w, h) scalew = b / 200. scaleh = b / 200. self.plotbox.canvas.clear() self.update_texture() with self.plotbox.canvas: for p in self.particles: Color(1.0, 0.0, 0.0) Ellipse(pos=(p.trax(self.time) * scalew + w / 2. - 5., p.tray(self.time) * scaleh + h / 2. - 5.), size=(10, 10)) self.time += interval * self.speed if (self.time >= self.T): self.time = 0.
class EditableLabel(Label): ## # Class Method: toggle_edit # ---------------------------- # This method removes the edit button and adds the confirm button once # the edit button is pressed and sets self.edit to true thus trigerring # the text box to be created. # # @params # (EditableLabel) self This instance of EditableLabel # (HoverButton) instance This is the button which triggers the function call ## def toggle_edit(self, instance): self.remove_widget(self.edit_button) self.edit = True self.add_widget(self.confirm_button) ## # Class Method: move_buttons # ---------------------------- # This method moves the buttons in accordance to the widgets height # and width on a change in position of the whole label. # # @params # (EditableLabel) self This instance of EditableLabel # (EditableLabel) instance This is the same instance of EditableLabel # (List) value This is the list of the x and y size of the EditableLabel ## def move_buttons(self, instance, value): self.edit_button.pos = (self.x + self.width, self.y) self.confirm_button.pos = (self.x + self.width, self.y) self.delete_button.pos = (self.x + self.width + 30, self.y) self.clear_button.pos = (self.x + self.width - 30, self.y) self.drop_button.pos= (self.x - 60, self.y) self.category_display.pos = (self.x - 60, self.y) ## # Class Method: validate_button # ---------------------------- # This method is a wrapper function for the on_text_vaidate function. # This is called when the confirm button is pressed. # # @params # (EditableLabel) self This instance of EditableLabel # (HoverButton) instance This is the button that cause this function to be called ## def validate_button(self, instance): self.on_text_validate(self) ## # Class Method: determine_category # ---------------------------- # This method adds group to the category section if the editable label # is being used for a group. i.e. radcheck ----> radgroupcheck # # @params # (EditableLabel) self This instance of EditableLabel # (string) instance This is the original category string to be edited ## def determine_category(self, category): index = 3 if self.group: return category[:index] + "group" + category[index:] else: return category ## # Class Constructor: __init__ # --------------------------- # This method is called during creation of the EditableLabel class. # This function initializes all of the buttons and labels used in the creation # of the editable label class. This function also sets all of the class variables # to their original status # # @params # (EditableLabel) self This instance of EditableLabel # (bool) editable Whether the label should be treated as editable # (string) attr_category The category in which the label should be placed # (bool) group This decides whether or noit the label is part of a group attribute # (Various) **kwargs various arguments for the internal Label ## def __init__(self, editable = True, attr_category = "radreply", group = False, **kwargs): super(EditableLabel, self).__init__(**kwargs) self.editable = editable self.group = group self.error_present = False self.current_attr = None self.attr_category = attr_category if self.text: attr_values = database.split_attributes(self.text) self.current_attr = Attribute(attr_values[0], attr_values[1], attr_values[2], self.attr_category) self.edit_button = HoverButton(button_up=BTN_EDIT[0], button_down=BTN_EDIT[1], size_hint=(None,None), size=(30,30), pos_hint={"center_y":.5}, pos=(self.x + self.width, self.y), on_release=self.toggle_edit) self.confirm_button = HoverButton(button_up=BTN_CONFIRM[0], button_down=BTN_CONFIRM[1], size_hint=(None,None), size=(30,30), pos_hint={"center_y":.5}, pos=(self.x + self.width, self.y), on_release=self.validate_button) self.delete_button = HoverButton(button_up=BTN_DELET[0], button_down=BTN_DELET[1], size_hint=(None,None), size=(30,30), pos_hint={"center_y":.5}, pos=(self.x + self.width + 30, self.y), on_release=self.prompt_delete) self.clear_button = Button(text="x", size=(30, 30), background_normal=BTN_TRANSP[0], background_down=BTN_TRANSP[0], color=(150.0/255, 150.0/255, 150.0/255, 1), font_size=20, pos=(self.x + self.width - 30, self.y), on_press=self.clear_label) self.text_input = TextInput(text=self.text, size=self.size, size_hint=(None, None), font_size=self.font_size, font_name=self.font_name, pos=self.pos, multiline=False) self.dropdown = DropDown(auto_width=False, width=60, pos=(self.x - 60, self.y)) category = "R" if self.attr_category == "radcheck": category = "C" if self.group: self.attr_category = self.determine_category(self.attr_category) self.drop_button = HoverButton(text=category, size=(60,30), size_hint=(None,None), button_up=DD_LCHRC[0], button_down=DD_LCHRC[1], font_size=12, pos=(self.x - 60, self.y), on_release=self.dropdown.open) self.rr_button = HoverButton(text="Reply", button_up=DD_DCHRC[0], button_down=DD_DCHRC[1], font_size=12, size=(60,30), size_hint=(None,None), on_press=self.select_rr) self.rc_button = HoverButton(text="Check", button_up=DD_DCHRC[0], button_down=DD_DCHRC[1], font_size=12, size=(60,30), size_hint=(None,None), on_press=self.select_rc) self.category_display = HoverButton(text=category, button_up=BKGD_CHRC, button_down=BKGD_CHRC, font_size=12, size=(60,30), pos=(self.x - 60, self.y), size_hint=(None,None)) self.dropdown.add_widget(self.rr_button) self.dropdown.add_widget(self.rc_button) self.bind(pos=self.text_input.setter('pos'), size=self.text_input.setter('size')) self.bind(pos=self.move_buttons) self.text_input.bind(on_text_validate=self.on_text_validate) if self.editable: self.add_widget(self.edit_button) self.add_widget(self.delete_button) self.add_widget(self.category_display) edit = BooleanProperty(False) textinput = ObjectProperty(None, allownone=True) ## # Class Method: select_rr # ---------------------------- # This method selects the rad reply option from the dropdown # and sets the main button label with an 'R'. The attr category # is updated as well. # # @params # (EditableLabel) self This instance of EditableLabel # (HoverButton) instance This is the button which triggers this function call ## def select_rr(self, instance): self.drop_button.text="R" self.attr_category = self.determine_category("radreply") self.category_display.text = "R" self.dropdown.dismiss() ## # Class Method: select_rc # ---------------------------- # This method selects the rad check option from the dropdown # and sets the main button label with an 'C'. The attr category # is updated as well. # # @params # (EditableLabel) self This instance of EditableLabel # (HoverButton) instance This is the button which triggers this function call ## def select_rc(self, instance): self.drop_button.text = "C" self.attr_category = self.determine_category("radcheck") self.category_display.text = "C" self.dropdown.dismiss() ## # Class Method: on_edit # ---------------------------- # This method is triggered by an internal call. if self.edit is True, the text # box will appear for the end user to edit the label. In the case that self.edit # becomes False, the text box will be removed. # # @params # (EditableLabel) self This instance of EditableLabel # (HoverButton) instance This is the button which triggers this function call # (bool) value This is the value of self.edit ## def on_edit(self, instance, value): if not value: if self.text_input: self.remove_widget(self.text_input) return self.remove_widget(self.category_display) self.add_widget(self.text_input) self.add_widget(self.clear_button) self.add_widget(self.drop_button) ## # Class Method: clear_label # ---------------------------- # This method sets the text of all the labels to nothing. # # @params # (EditableLabel) self This instance of EditableLabel # (HoverButton) instance This is the button which triggers this function call ## def clear_label(self, instance): self.text = '' self.text_input.text = '' ## # Class Method: clear_label # ---------------------------- # This method creates a popup confirming whether or not the user # wants to delete an attribute as a backup check. # # @params # (EditableLabel) self This instance of EditableLabel # (HoverButton) instance This is the button which triggers this function call ## def prompt_delete(self, instance): self.pop_layout = FloatLayout(size=(Window.width, 200)) self.del_popup = Popup(title='Delete Attribute', content=self.pop_layout, size_hint=(None,None), size=(400,200), background=BKGD_DCHRC, pos_hint={"center_x":.5, 'top':.7}, auto_dismiss=False) self.pop_layout.add_widget(Label(text=("Delete Attribute?"), color=(1,1,1,1), pos_hint={'top':1.2, "center_x":.5}, font_size=14)) self.pop_layout.add_widget(HoverButton(text="Delete", button_up=BTN_DCHRC[0], button_down=BTN_DCHRC[1], font_size=14, size_hint=(None,None), size=(100,40), pos_hint={"center_x":.7, 'top':.35}, on_press=self.delete_label)) self.pop_layout.add_widget(HoverButton(text="Cancel", button_up=BTN_DCHRC[0], button_down=BTN_DCHRC[1], font_size=14, size_hint=(None,None), size=(100,40), pos_hint={"center_x":.3, 'top':.35}, on_press=self.del_popup.dismiss)) self.del_popup.open() ## # Class Method: delete_label # ---------------------------- # This method removes the visible label from the user or group and # also removes the instance from the database, completely getting rid # of any trace of the curtrent label. # # @params # (EditableLabel) self This instance of EditableLabel # (HoverButton) instance This is the button which triggers this function call ## def delete_label(self, instance): try: self.del_popup.dismiss() except: pass self.clear_from_db() if self.error_present: self.parent.parent.remove_widget(self.err_label) self.parent.parent.remove_widget(self.parent) ## # Class Method: clear_from_db # ---------------------------- # This method removes the labels contents from the database depending # on within what category they are placed. The method then attempts to # update the database or text file to match the GUI # # @params # (EditableLabel) self This instance of EditableLabel ## def clear_from_db(self): if self.current_attr: attr = self.current_attr if manager.sm.current == "menu": try: if not self.group: attr.value = "" database.modify_user_attr(manager.CURRENT_USER, attr) self.current_attr = None else: attr.value = "" database.modify_group_attr(manager.CURRENT_GROUP, attr) self.current_attr = None except SyntaxError: pass else: for preset in manager.presets: if preset.name == manager.CURRENT_PRESET: try: preset.delete_attribute(attr.name, attr.operator, attr.category) presets.save_presets(manager.presets, "user_presets.txt") return except SyntaxError: pass error_present = False ## # Class Method: on_text_validate # ---------------------------- # This method deals with what to do when the label is validated. First it checks to # see if a valid attribute is presented. If not, an error label is displayed. Then, the # database is updated with the correct information that matches the GUI. # # @params # (EditableLabel) self This instance of EditableLabel # (HoverButton) instance The button that triggered this function call ## def on_text_validate(self, instance): if self.error_present: self.parent.parent.remove_widget(self.err_label) self.text = self.text_input.text self.clear_from_db() if self.text_input.text == '': self.delete_label(self) return try: attr_values = database.split_attributes(self.text) if attr_values[2].strip() == '': self.delete_label(self) return except SyntaxError: self.err_label = Label(text="Please enter a valid attribute", pos_hint={"x-center":.5,"bottom":.95}, color=(1,0,0,1), font_size=14) self.parent.parent.add_widget(self.err_label) self.error_present = True return self.remove_widget(self.confirm_button) self.remove_widget(self.drop_button) self.add_widget(self.edit_button) self.add_widget(self.category_display) self.remove_widget(self.clear_button) self.current_attr = Attribute(attr_values[0].strip(), attr_values[1].strip(), attr_values[2].strip(), self.attr_category) if manager.sm.current == "menu": if not self.group: database.modify_user_attr(manager.CURRENT_USER, self.current_attr) else: database.modify_group_attr(manager.CURRENT_GROUP, self.current_attr) manager.menu.recolor_info_panel() else: for preset in manager.presets: if preset.name == manager.CURRENT_PRESET: try: preset.update_attribute(attr_values[0], attr_values[1], attr_values[2], self.attr_category) except SyntaxError: error_button = Button(text='Please enter a valid attribute, press to close') error_popup = Popup(title='Error Popup', content=error_button, size_hint=(.5, .5), pos_hint={'center_x': .5, 'center_y': .5}) error_button.bind(on_press=error_popup.dismiss) error_popup.open() return presets.save_presets(manager.presets, "user_presets.txt") self.edit = False
class LogViewerScreen(MobileInsightScreenBase): cancel = ObjectProperty(None) loaded = ObjectProperty(None) loadinggrid = ObjectProperty(None) ok = ObjectProperty(None) ReadComplete = ObjectProperty(None) name = StringProperty('LogViewerScreen') def __init__(self, **kw): super(LogViewerScreen, self).__init__(**kw) self._log_analyzer = None self.selectedTypes = None def SetInitialGrid(self, *args): if self.ReadComplete == 'Yes': self.ReadComplete = '' self.loaded = 'Yes' self.grid_scroll.effect_y = ScrollEffect() self.onReset() def exit_open_popup(self, instance): idx = self.app.available_screens.index('HomeScreen') self.app.go_screen(idx) return False def dismiss_open_popup(self): self.open_popup.dismiss() return False def dismiss_filter_popup(self, *args): self.filter_popup.dismiss() def dismiss_search_popup(self, *args): self.search_popup.dismiss() def dismiss_goto_popup(self, *args): self.goto_popup.dismiss() # Open # Pick a .mi2log file that you would like to load. # Logs are organized by their Type ID. # Click the row to see the whole log def onOpen(self, *args): self.open_popup = Popup( title='Open file', content=Open_Popup(load=self.load), # background_normal='', background_color=(0 / 255.0, 161 / 255.0, 247 / 255.0, 1), # color=(0/255.0, 161/255.0, 247/255.0, 1), auto_dismiss=True) # self.open_popup.bind(on_dismiss=self.exit_open_popup) self.open_popup.open() def load(self, path, filename, *args): load_failed_popup = Popup( title='Error while opening file', content=Label(text='Please select a valid file'), size_hint=(0.8, 0.2)) if filename == []: self.dismiss_open_popup() load_failed_popup.open() else: name, extension = os.path.splitext(filename[0]) if extension == ['.mi2log'][0]: self.loading_num = 2 self.loading_popup = Popup(title='', content=Label(text='Loading.', font_size=self.width / 25), size_hint=(0.3, 0.2), separator_height=0, title_size=0) self.loading_popup.open() Clock.schedule_interval(self.loading, 1) Clock.unschedule(self.check_scroll_limit) self.grid.clear_widgets() with open(os.path.join(path, filename[0])) as stream: t = Thread(target=self.openFile, args=(os.path.join(path, filename[0]), self.selectedTypes)) t.start() self.dismiss_open_popup() else: self.dismiss_open_popup() load_failed_popup.open() def openFile(self, Paths, selectedTypes): if not self._log_analyzer: Logger.info("Logviewer: Importing LogAnalyzer") from mobile_insight.analyzer import LogAnalyzer self._log_analyzer = LogAnalyzer(self.OnReadComplete) self._log_analyzer.AnalyzeFile(Paths, selectedTypes) def OnReadComplete(self): self.data = self._log_analyzer.msg_logs self.data_view = self.data self.ReadComplete = 'Yes' Clock.schedule_once(self.SetInitialGrid, 0.1) def check_scroll_limit(self, *args): if not self.loadinggrid == 'Yes': Move = '0' rows = len(self.data_view) scrolltop = self.grid_scroll.vbar[0] + self.grid_scroll.vbar[1] scrollbottom = self.grid_scroll.vbar[0] if rows <= 50: nrows = rows else: nrows = 50 if scrolltop >= 1 and self.k != 0: Move = 'up' self.SetUpGrid(self.data_view, rows, Move) if scrollbottom <= 0 and self.k != rows - nrows: Move = 'down' self.SetUpGrid(self.data_view, rows, Move) def SetUpGrid(self, data, rows, Move): self.grid.bind(minimum_height=self.grid.setter('height')) self.grid.clear_widgets() if rows <= 50: nrows = rows else: nrows = 50 if Move == 'init': self.k = 0 if Move == 'up' or Move == 'up!': self.k -= 25 if Move == 'down': self.k += 25 if rows <= self.k + 50 and Move != '': self.k = rows - 50 Move == 'over' if 0 >= self.k and Move != 'up!': self.k = 0 self.loadinggrid = 'Yes' if Move == 'init' or '': self.grid_scroll.scroll_y = 1 if Move == 'over': self.grid_scroll.scroll_y = 0 if Move == 'up' or Move == 'up!': self.grid_scroll.scroll_y = 1 - 25 / (nrows - 13.5) if Move == 'down': self.grid_scroll.scroll_y = 1 - 11.5 / (nrows - 13.5) if Move == '': self.grid_scroll.scroll_y = -13.5 / \ (nrows - 13.5) + (rows - self.k) / (nrows - 13.5) self.k = rows - nrows for i in range(self.k, self.k + nrows): self.grid.add_widget( Label(text=str(i + 1), size_hint_x=0.1, color=(0, 0, 0, 1))) self.grid.add_widget( Button(text=' ' + str(data[i]["Timestamp"]) + '\n ' + str(data[i]["TypeID"]), font_size=self.height / 50, on_release=self.grid_popup, id=str(data[i]["Payload"]), text_size=(self.width * 0.9, self.height * 0.05), background_normal='', background_color=(0 / 255.0, 161 / 255.0, 247 / 255.0, 0.65), halign='left')) self.loadinggrid = 'No' if self.loading_num != '': Clock.unschedule(self.loading) self.loading_popup.dismiss() self.loading_num = '' def grid_popup(self, data): val = xml.dom.minidom.parseString(data.id) pretty_xml_as_string = val.toprettyxml(indent=" ", newl="\n") scroll = ScrollView() label = TextInput(text=str(pretty_xml_as_string), readonly=True, size_hint_y=None) # label = TextInput(text = json.dumps(xmltodict.parse(pretty_xml_as_string), indent = 1), readonly = True, size_hint_y = None) label.bind(minimum_height=label.setter('height')) scroll.add_widget(label) popup = Popup(title='Timestamp : %s\nType : %s' % (str.split(data.text)[0], str.split(data.text)[2]), content=scroll, size_hint=(0.8, 0.8)) popup.open() def loading(self, *args): if self.loading_num == 1: self.loading_popup.content = Label(text='Loading.', font_size=self.width / 25) if self.loading_num == 2: self.loading_popup.content = Label(text='Loading..', font_size=self.width / 25) if self.loading_num == 3: self.loading_popup.content = Label(text='Loading...', font_size=self.width / 25) self.loading_num = 0 self.loading_num += 1 # GoBack # Go back to Home Screen def onGoBack(self, app): idx = app.available_screens.index('HomeScreen') app.go_screen(idx) # app.root.ids.sm.switch_to(app.home_screen) # Filter # Pick certain Type IDs to view # To reset everything, press the Reset button def onFilter(self): popup = BoxLayout(orientation='vertical', size=self.size, pos=self.pos) self.filter_popup = Popup(title='Filter', content=popup, size_hint=(0.9, 0.9), auto_dismiss=False) scroll = ScrollView() checkbox = GridLayout(cols=2, row_force_default=True, row_default_height=self.height / 20, size_hint_y=None) checkbox.bind(minimum_height=checkbox.setter('height')) select_all = GridLayout(cols=2, row_force_default=True, row_default_height=self.height / 20, size_hint_y=0.08) self.select_all_checkbox = CheckBox(size_hint_x=0.2) select_all_label = Label(text='Select All', text_size=(self.width * 0.7, None), halign='left') select_all.add_widget(self.select_all_checkbox) select_all.add_widget(select_all_label) cancel = Button(text='Cancel', on_release=self.dismiss_filter_popup) ok = Button(text='Ok', on_release=self.filter_ok) buttons = BoxLayout(size_hint_y=None, height=self.height / 20) buttons.add_widget(cancel) buttons.add_widget(ok) scroll.add_widget(checkbox) popup.add_widget(scroll) popup.add_widget(select_all) popup.add_widget(buttons) self.filter_rows = {} for i in range(len(self._log_analyzer.supported_types)): self.filter_rows[i] = CheckBox(size_hint_x=0.2) checkbox.add_widget(self.filter_rows[i]) checkbox.add_widget( Label(text=str(list(self._log_analyzer.supported_types)[i]))) self.select_all_checkbox.bind(active=self.filter_select_all) self.filter_popup.open() def filter_ok(self, *args): if self.loaded == 'Yes': self.selectedtypes = [] for i in range(len(self._log_analyzer.supported_types)): if self.filter_rows[i].active: self.selectedtypes += [ list(self._log_analyzer.supported_types)[i] ] if not self.selectedtypes == []: self.data_view = [ x for x in self.data_view if x["TypeID"] in self.selectedtypes ] self.SetUpGrid(self.data_view, len(self.data_view), 'init') Clock.unschedule(self.check_scroll_limit) Clock.schedule_interval(self.check_scroll_limit, 0.11) self.dismiss_filter_popup() else: self.dismiss_filter_popup() def filter_select_all(self, *args): if self.select_all_checkbox.active: for i in range(len(self._log_analyzer.supported_types)): self.filter_rows[i].active = True else: for i in range(len(self._log_analyzer.supported_types)): self.filter_rows[i].active = False # Search # Search for a keyword in the Payload that shows up when a row is pressed # To reset everything, press the Reset button def onSearch(self): popup = BoxLayout(orientation='vertical', size=self.size, pos=self.pos) self.search_popup = Popup(title='Search', content=popup, size_hint=(0.9, 0.25), auto_dismiss=False) self.search_textinput = TextInput() cancel = Button(text='Cancel', on_release=self.dismiss_search_popup) ok = Button(text='Ok', on_release=self.search_ok) buttons = BoxLayout(size_hint_y=None, height=self.height / 20) buttons.add_widget(cancel) buttons.add_widget(ok) popup.add_widget(self.search_textinput) popup.add_widget(buttons) self.search_popup.open() def search_ok(self, *args): if self.loaded == 'Yes': self.data_view = [ x for x in self.data_view if self.search_textinput.text in x["Payload"] ] self.SetUpGrid(self.data_view, len(self.data_view), 'init') self.dismiss_search_popup() Clock.unschedule(self.check_scroll_limit) Clock.schedule_interval(self.check_scroll_limit, 0.11) else: self.dismiss_search_popup() # Reset # Reset the grid to the state before filtering and/or searching def onReset(self): if self.loaded == 'Yes': self.data_view = self.data self.SetUpGrid(self.data_view, len(self.data_view), 'init') Clock.unschedule(self.check_scroll_limit) Clock.schedule_interval(self.check_scroll_limit, 0.11) # Go To # Go to the selected row def onGoTo(self): if self.loaded == 'Yes': popup = BoxLayout(orientation='vertical', size=self.size, pos=self.pos) self.goto_popup = Popup(title='Go To' + ' (1~' + str(len(self.data_view)) + ')', content=popup, size_hint=(0.9, 0.25), auto_dismiss=False) self.goto_textinput = TextInput() cancel = Button(text='Cancel', on_release=self.dismiss_goto_popup) ok = Button(text='Ok', on_release=self.goto_ok) buttons = BoxLayout(size_hint_y=None, height=self.height / 20) buttons.add_widget(cancel) buttons.add_widget(ok) popup.add_widget(self.goto_textinput) popup.add_widget(buttons) self.goto_popup.open() def goto_ok(self, *args): rows = len(self.data_view) num = self.goto_textinput.text if num.isdigit(): if int(num) > 0 and rows >= int(num): if int(num) >= rows - 12: self.k = rows self.dismiss_goto_popup() self.SetUpGrid(self.data, len(self.data), 'over') else: self.k = int(num) - 1 self.dismiss_goto_popup() if self.k >= rows - 24: self.SetUpGrid(self.data, len(self.data), '') else: self.SetUpGrid(self.data, len(self.data), 'up!') Clock.unschedule(self.check_scroll_limit) Clock.schedule_interval(self.check_scroll_limit, 0.11) else: self.dismiss_goto_popup() goto_failed_popup = Popup( title='Error', content=Label( text='Please write an integer in the given range'), size_hint=(0.8, 0.2)) goto_failed_popup.open() else: self.dismiss_goto_popup() goto_failed_popup = Popup( title='Error', content=Label( text='Please write an integer in the given range'), size_hint=(0.8, 0.2)) goto_failed_popup.open()
class AFDT(App): loadfile = ObjectProperty(None) savefile = ObjectProperty(None) # ui font size codeFontSize = ObjectProperty(20) uiFontSize = ObjectProperty(20) # source path of diagram getDiagram = ObjectProperty('') def __init__(self, **kwargs): super(AFDT, self).__init__(**kwargs) self.image = None self.code = '' self.sysMessage = 'Welcome to AFDT' self.fileName = '' self.hasOpenFolder = False Window.bind(on_key_down=self._on_keyboard_down) Window.bind(on_dropfile=self._on_file_drop) # POP UP function def show_help(self): content = userHelpDialog(ok=self.dismiss_popup) self._popup = Popup(title="help", content=content, size_hint=(0.9, 0.9)) self._popup.open() def show_setting(self): content = settingDialog(ok=self.set_text_size, cancel=self.dismiss_popup) self._popup = Popup(title="User Preferences", content=content, size_hint=(0.8, 0.3)) self._popup.open() def set_text_size(self, text_size): self.UI.displayCode.font_size = text_size print('Txt size set to ' + text_size) self.dismiss_popup() pass def dismiss_popup(self): self._popup.dismiss() def show_load(self): content = LoadDialog(load=self.load, cancel=self.dismiss_popup) self._popup = Popup(title="Load file", content=content, size_hint=(0.9, 0.9)) self._popup.open() def show_save(self): content = SaveDialog(save=self.save, cancel=self.dismiss_popup) self._popup = Popup(title="Save file", content=content, size_hint=(0.9, 0.9)) self._popup.open() def viewImage(self): content = floatImage() self._popup = Popup(title="Diagram", content=content, size_hint=(1, 0.8), auto_dismiss=True) self._popup.open() # laod & save def load(self, path, filename): try: with open(os.path.join(path, filename[0]), encoding='utf-8') as stream: self.code = stream.read() self.UI.displayCode.text = self.code self.setSystemMessage('Import ' + filename[0] + ' success!') except: self.setSystemMessage('Error file type!') pass self.dismiss_popup() def save(self, path, filename): try: p = path + '/' + filename + '.png' print(p) self.image.save(p, 'png') self.dismiss_popup() self.setSystemMessage('Save image success') except: self.setSystemMessage( 'Save image error!Check if you have generated the diagram') def _on_file_drop(self, window, file_path): print(file_path.decode()) try: with open(file_path.decode()) as stream: self.code = stream.read() self.UI.displayCode.text = self.code self.setSystemMessage('Import ' + file_path.decode() + ' success!') except: self.setSystemMessage('Error file type!') pass return def saveFile(self): self.show_save() def setSystemMessage(self, text): self.UI.sysMessageLabel.text = text def setUserHintMessage(self, text): self.UI.userHintMessageLabel.text = text def importFile(self): self.show_load() def clear(self): self.setSystemMessage('Clear file success') self.UI.displayCode.text = '' self.fileName = '' self.code = '' self.image = '' self.getDiagram = '' def _on_mouse_pos(self, w, pos): pass #print (pos) def _on_keyboard_down(self, instance, keyboard, keycode, text, modifiers): if len(modifiers) > 0 and modifiers[0] == 'ctrl': if text == 'o': # Ctrl+a print('open folder') self.setSystemMessage('open folder') self.show_load() elif text == 's': self.setSystemMessage('save img') print('save img') elif text == 'p': self.setSystemMessage('analyze code') print('analyze code') def draw(self): # self.code try: analysis_tool(code=self.code) self.getDiagram = './out.gv.png' self.image = Image.open(self.getDiagram) self.setSystemMessage('Generate diagram success') self.UI.imageButton.reload() # self.image.show() except: self.setSystemMessage( 'Cannot Parse Source. Please Check You Source Code Or Try Other Program.' ) def build(self): self.UI = UI() return self.UI
class MainGrid(GridLayout): """1st level grid. The main grid of the app. This is where ALL the labels, buttons, inputs etc. go.""" def __init__(self, **kwargs): super(MainGrid, self).__init__(**kwargs) self.voice = False self.wordlanguage = 'en' self.cols = 1 self.possibletries = 11 # 11 incorrect guesses allowed self.randomword = '' self.myword = '' self.placeholderchar = '_ ' self.placeholdercharvoiced = 'blank' self.tryword = 'tries' self.incorrectguesses = [] # string for incorrectly guessed letters self.correctguesses = '' # extended alphabet chars (cannot be used in Python 2!) if sys.version_info[0] < 3: self.extendedalpha = '' else: self.extendedalpha = {"ä":"ae", "ö":"oe", "ü":"ue", "ß":"ss", "é":"e", "è":"e"} # start actual game self.randomword, self.theword = self.pickAWord( self.wordlanguage, self.extendedalpha) self.occurencelist = analyseWords(self.mywords, additionals='') self.placeholderword = list(self.placeholderchar*len(self.theword)) self.placeholderword_str = ''.join(self.placeholderword) # title widget self.title = TitleBlock() self.add_widget(self.title) # placeholder word self.guessword = PlaceholderWordBlock() self.add_widget(self.guessword) self.guessword.blankword.text = self.placeholderword_str self.alabel = Label(text="empty labellll") self.add_widget(self.alabel) # hangman goes here self.userinput = InputBlock() self.add_widget(self.userinput) self.userinput.height = 20 self.message = MessageBlock() self.add_widget(self.message) # settings and exit button self.settingsexit = SettingsExitBlock() self.add_widget(self.settingsexit) # just checking for correct output # TODO remove at end print("The word to guess is: ", self.theword) def settings_popup(self): description = Label(text='Here you can change the settings\n' 'of the game', height='100sp') voiceon = ToggleButton(group="voice", state="down", text='text-to-speech', size_hint_y=None, height='50sp') voiceoff = ToggleButton(group="voice", text='text-only', size_hint_y=None, height='50sp') lang_en = ToggleButton(group="language", state="down", text='English words', size_hint_y=None, height='50sp') lang_de = ToggleButton(group="language", text='German words', size_hint_y=None, height='50sp') closebutton = Button(text='Apply settings', size_hint_y=None, height='50sp') content = BoxLayout(orientation='vertical') # content = GridLayout(cols=2) # TODO turn this into a two-column layout content.add_widget(description) content.add_widget(voiceon) content.add_widget(voiceoff) content.add_widget(lang_en) content.add_widget(lang_de) content.add_widget(closebutton) self.popup = Popup(content=content, title='Hangman settings', size_hint=(None, None), size=('300dp', '400dp')) closebutton.bind(on_release=self.close_popup) voiceon.bind(on_release=self.turn_voice_on) voiceoff.bind(on_release=self.turn_voice_off) lang_en.bind(on_release=self.pick_lang_en) lang_de.bind(on_release=self.pick_lang_de) self.popup.open() col = AnchorLayout() return col def pick_lang_en(self, bla): self.wordlanguage = 'en' print("language: ", self.wordlanguage) def pick_lang_de(self, bla): self.wordlanguage = 'de' print("language: ", self.wordlanguage) def turn_voice_on(self, bla): self.voice = True print("voice: ", self.voice) def turn_voice_off(self, bla): self.voice = False print("voice: ", self.voice) def pickAWord(self, wordlanguage, additionals): theword = [] self.mywords = createMyWords(wordlanguage, additionals='') randomword = random.choice(list(self.mywords)) for letter in randomword.lower(): if self.extendedalpha and (letter in self.extendedalpha): letter = self.extendedalpha[letter] theword.append(letter) theword = ''.join(theword) return randomword, theword def close_popup(self, bla): self.randomword, self.theword = self.pickAWord(self.wordlanguage, additionals='') self.placeholderword = list(self.placeholderchar*len(self.theword)) self.placeholderword_str = ''.join(self.placeholderword) self.word_to_guess.text = self.placeholderword_str self.popup.dismiss() print("word language is: ", self.wordlanguage) print("this is the word: ", self.theword) print(self.placeholderword)
class DataViewer(GridLayout): display = ObjectProperty() def update_linecount(self): global gLines gLines = self.ids.linecounter.text def parse(self): global gLines global gFilename if gFilename == "No file chosen": return # parse (lines) lines from (filename) # then get columns that match selected set data = get_data_by_line(gFilename, gLines) result = "" sep = "=======================================================\n" if len(gSelectedCols) == 0: result = "Dumping data (WARNING: LARGE DATA SET)\n" + sep for datum in data: r = get_cols(datum, '', '') if r is None: r = "<Not found>" result = result + r + '\n' + sep else: for datum in data: for col in gSelectedCols: r = get_cols(datum, '', col) if r is None: r = "<Not found>" result = result + col + ": " + r + '\n' result = result + sep self.display.text = result def show_load(self): content = LoadDialog(load=self.load, cancel=self.dismiss_popup) self._popup = Popup(title="Load file", content=content, size_hint=(0.9, 0.9)) self._popup.open() def load(self, path, file): global gFilename gFilename = os.path.join(path, file[0]) self.dismiss_popup() def dismiss_popup(self): global gFilename newtext = gFilename if len(gFilename) > 29: newtext = gFilename[-29:] self.ids.filename.text = newtext self._popup.dismiss() def reset(self): global gLines global gSelectedCols global gFilename gFilename = "No file chosen" gLines = 1 gSelectedCols = [] self.ids.linecounter.text = "1" self.display.text = '' self.ids.filename.text = gFilename self.ids.rv.reset()
class AddFileDialog(BoxLayout): '''AddFileDialog is a dialog for adding files to current project. It emits 'on_added' event if file has been added successfully, 'on_error' if there has been some error in adding file and 'on_cancel' when user wishes to cancel the operation. ''' text_file = ObjectProperty() '''An instance to TextInput showing file path to be added. :data:`text_file` is a :class:`~kivy.properties.ObjectProperty` ''' text_folder = ObjectProperty() '''An instance to TextInput showing folder where file has to be added. :data:`text_folder` is a :class:`~kivy.properties.ObjectProperty` ''' always_check = ObjectProperty() '''An instance to :class:`~kivy.uix.checkbox.CheckBox`, which will determine whether same folder will be used for all files of same type or not. :data:`always_check` is a :class:`~kivy.properties.ObjectProperty` ''' __events__ = ('on_cancel', 'on_added', 'on_error') def __init__(self, proj_loader, **kwargs): super(AddFileDialog, self).__init__(**kwargs) self.proj_loader = proj_loader def on_cancel(self): pass def on_added(self): pass def on_error(self): pass def _perform_add_file(self): '''To copy file from its original path to new path ''' if self.text_file.text == '' or self.text_folder.text == '': return self.proj_loader.proj_watcher.stop() folder = os.path.join(self.proj_loader.proj_dir, self.text_folder.text) if not os.path.exists(folder): os.mkdir(folder) try: shutil.copy( self.text_file.text, os.path.join(folder, os.path.basename(self.text_file.text))) if self.always_check.active: self.proj_loader.add_dir_for_file_type( self.text_file.text[self.text_file.text.rfind('.') + 1:], self.text_folder.text) self.proj_loader.proj_watcher.start_watching( self.proj_loader.proj_dir) self.dispatch('on_added') except (OSError, IOError): self.dispatch('on_error') def update_from_file(self, *args): '''To determine the folder associated with current file type. ''' curr_type = self.text_file.text curr_type = curr_type[curr_type.find('.') + 1:] if curr_type == '': return try: folder = self.proj_loader.dict_file_type_and_path[curr_type] self.text_folder.text = folder self.always_check.active = True except KeyError: pass def _cancel_popup(self, *args): '''To dismiss popup when cancel is pressed. ''' self._popup.dismiss() def _file_load(self, instance): '''To set the text of text_file, to the file selected. ''' self._popup.dismiss() if instance.selection != []: self.text_file.text = instance.selection[0] def open_file_btn_pressed(self, *args): '''To load File Browser for selected file when 'Open File' is clicked ''' self._fbrowser = FileBrowser(select_string='Open') self._fbrowser.bind(on_success=self._file_load, on_canceled=self._cancel_popup) self._popup = Popup(title='Open File', content=self._fbrowser, size_hint=(0.9, 0.9), auto_dismiss=False) self._popup.open() def _folder_load(self, instance): '''To set the text of text_folder, to the folder selected. ''' if hasattr(self, '_popup'): self._popup.dismiss() proj_dir = '' if instance.ids.tabbed_browser.current_tab.text == 'List View': proj_dir = instance.ids.list_view.path else: proj_dir = instance.ids.icon_view.path proj_dir = os.path.join(proj_dir, instance.filename) if proj_dir.find(self.proj_loader.proj_dir) != -1: proj_dir = proj_dir.replace(self.proj_loader.proj_dir, '') if proj_dir[0] == '/': proj_dir = proj_dir[1:] self.text_folder.text = proj_dir def open_folder_btn_pressed(self, *args): '''To load File Browser for selected folder when 'Open Folder' is clicked ''' self._fbrowser = FileBrowser(select_string='Open') self._fbrowser.ids.list_view.path = self.proj_loader.proj_dir self._fbrowser.bind(on_success=self._folder_load, on_canceled=self._cancel_popup) self._popup = Popup(title='Open File', content=self._fbrowser, size_hint=(0.9, 0.9), auto_dismiss=False) self._popup.open()
class GUI(Screen): def __init__(self): self.sm = ScreenManager() self.sm.add_widget(self.menu()) def render(self): return self.sm def menu(self): screen = Screen(name='Home') menu_background = Image(source=ROOT + 'main_background.jpg', allow_stretch=True, keep_ratio=False) layout = FloatLayout(size=(500, 500)) layout.add_widget(menu_background) btn_play = Button(text='Play', size_hint=(.15, .08), pos_hint={ 'x': .025, 'y': .875 }) btn_play.bind(on_press=self.play) btn_quit = Button(text='Quit', size_hint=(.15, .08), pos_hint={ 'x': .825, 'y': .025 }) btn_quit.bind(on_press=self.quit) layout.add_widget(btn_play) layout.add_widget(btn_quit) screen.add_widget(layout) return screen def play(self, source): self.settingsview = self.settings() self.sm.add_widget(self.settingsview) self.sm.current = 'Settings' self.random_generation_setting = False def quit(self, source): sys.exit(0) def settings(self): screen = Screen(name=ROOT + 'Settings') settings_background = Image(source='settings_background.jpg', allow_stretch=True, keep_ratio=False) layout = FloatLayout(size=(500, 500)) layout.add_widget(settings_background) btn_singleplayer = Button(text='Single Player', size_hint=(.15, .08), pos_hint={ 'x': .65, 'y': .45 }) btn_singleplayer.bind(on_press=self.singleplayer) btn_multiplayer = Button(text='Multiplayer', size_hint=(.15, .08), pos_hint={ 'x': .825, 'y': .45 }) btn_multiplayer.bind(on_press=self.multiplayer) label_switch = Label(text='Random Map Generator', size_hint=(.15, .08), pos_hint={ 'x': .5, 'y': .1 }) switch = Switch(active=False, size_hint=(.15, .08), pos_hint={ 'x': .7, 'y': .1 }) switch.bind(active=self.map_setting) layout.add_widget(btn_multiplayer) layout.add_widget(btn_singleplayer) layout.add_widget(label_switch) layout.add_widget(switch) screen.add_widget(layout) return screen def map_setting(self, source, isActive): if isActive: self.random_generation_setting = True else: self.random_generation_setting = False def singleplayer(self, source): self.multiplayer_status = False self.widget = [] self.game = Game(mode=self.random_generation_setting) self.gridview = self.grid(name='Game') self.sm.add_widget(self.gridview) self.sm.current = 'Game' def multiplayer(self, source): self.multiplayer_status = True self.widget = [] self.game_1 = Game(mode=self.random_generation_setting) self.game_2 = Game(mode=self.random_generation_setting) self.gridview_1 = self.grid(name='Player_1') self.gridview_2 = self.grid(name='Player_2') self.sm.add_widget(self.gridview_1) self.sm.add_widget(self.gridview_2) self.sm.current = 'Player_1' self.turn = 1 def grid(self, name): screen = Screen(name=name) main_layout = GridLayout(cols=2) layout = GridLayout(cols=11, rows=11, width=700, size_hint=(None, 1)) border = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] for y in range(11): for x in range(11): if (x == 0 and y == 0): layout.add_widget(Label(text='')) elif (y == 0 and x != 0): layout.add_widget(Label(text=str(x))) elif (x == 0 and y != 0): layout.add_widget(Label(text=border[y - 1])) else: btn = Button(id=str((x, y))) btn.bind(on_press=self.game_call) layout.add_widget(btn) main_layout.add_widget(layout) self.game_label = Label(text='Start playing by clicking on the grid') if self.multiplayer_status == True: self.widget.append(self.game_label) print(self.widget) main_layout.add_widget(self.game_label) screen.add_widget(main_layout) return screen def current_game(self): if self.turn == 2: game = self.game_2 else: game = self.game_1 return game def game_call(self, btn): a = literal_eval(btn.id) if self.multiplayer_status == True: #multiplayer btn.background_disabled_normal = '' _, status, btn.background_color, message = self.current_game( ).update_map(a) if status == 0: self.sm.current = 'Home' self.score_popup() self.sm.remove_widget(self.gridview_1) self.sm.remove_widget(self.gridview_2) else: if self.turn == 2: self.widget[1].text = message self.turn = 1 self.sm.transition.direction = 'right' else: self.widget[0].text = message self.turn = 2 self.sm.transition.direction = 'left' self.sm.current = 'Player_' + str(self.turn) self.turn_popup() else: #singleplayer btn.background_disabled_normal = '' _, status, btn.background_color, self.game_label.text = self.game.update_map( a) if status == 0: self.sm.current = 'Home' self.score_popup() self.sm.remove_widget(self.gridview) btn.disabled = True def score_popup(self): if self.multiplayer_status == True: score_label = Label(text="You scored a ratio of " + str(self.current_game().show_score()) + " %") self.player_name_input = TextInput(text="Enter your name") popup_title = "Player " + str(self.turn) else: score_label = Label(text="You scored a ratio of " + str(self.game.show_score()) + " %") self.player_name_input = TextInput(text="Enter your name") popup_title = "Game Over" print("after if statement") score_layout = GridLayout(rows=2) score_layout.add_widget(score_label) save_layout = GridLayout(cols=2) save_layout.add_widget(self.player_name_input) save_btn = Button(text="Save") save_btn.bind(on_press=self.save) save_layout.add_widget(save_btn) score_layout.add_widget(save_layout) self.popup = Popup(title=popup_title, content=score_layout, size_hint=(None, None), size=(400, 400), auto_dismiss=False) self.popup.open() def save(self, src): if self.multiplayer_status == True: self.current_game().save(self.player_name_input.text) self.popup.dismiss() else: self.game.save(self.player_name_input.text) self.popup.dismiss() def turn_popup(self): popup = Popup(title='Player ' + str(self.turn) + ' turn', size_hint=(None, None), size=(120, 80), auto_dismiss=True) popup.open() Clock.schedule_once(popup.dismiss, 0.5)
def scanAllEcus(self): SEFname = mod_globals.user_data_dir + '/savedEcus.p' if mod_globals.opt_can2: SEFname = mod_globals.user_data_dir + '/savedEcus2.p' if mod_globals.opt_demo and not os.path.isfile(SEFname): SEFname = './savedEcus.p' if os.path.isfile(SEFname) and not mod_globals.opt_scan: self.detectedEcus = pickle.load(open(SEFname, 'rb')) if len(self.detectedEcus ) > 0 and 'idTx' not in self.detectedEcus[0].keys(): self.allecus = OrderedDict() for i in self.detectedEcus: self.allecus[i['ecuname']] = i self.read_Uces_file() self.detectedEcus = [] for i in self.allecus.keys(): self.detectedEcus.append(self.allecus[i]) self.detectedEcus = sorted(self.detectedEcus, key=lambda k: int(k['idf'])) if len(self.detectedEcus): pickle.dump(self.detectedEcus, open(SEFname, 'wb')) return None mod_globals.opt_scan = True mod_globals.state_scan = True lbltxt = Label(text='Init', font_size=20) popup_scan = Popup(title='Scanning CAN bus', content=lbltxt, size=(400, 400), size_hint=(None, None)) base.runTouchApp(slave=True) popup_scan.open() EventLoop.idle() self.reqres = [] self.errres = [] i = 0 lbltxt.text = 'Scanning:' + str(i) + '/' + str(len( self.allecus)) + ' Detected: ' + str(len(self.detectedEcus)) EventLoop.idle() canH = '6' canL = '14' if mod_globals.opt_can2: canH = '13' canL = '12' self.elm.init_can() for ecu, row in sorted(self.allecus.iteritems(), key=lambda (x, y): y['idf'] + y['protocol']): if self.allecus[ecu]['pin'] == 'can' and self.allecus[ecu][ 'pin1'] == canH and self.allecus[ecu]['pin2'] == canL: i = i + 1 lbltxt.text = 'Scanning:' + str(i) + '/' + str( len(self.allecus)) + ' Detected: ' + str( len(self.detectedEcus)) EventLoop.idle() self.elm.set_can_addr(self.allecus[ecu]['dst'], self.allecus[ecu]) self.scan_can(self.allecus[ecu]) self.elm.close_protocol() if not mod_globals.opt_can2: popup_scan.title = 'Scanning ISO bus' self.elm.init_iso() for ecu, row in sorted(self.allecus.iteritems(), key=lambda (x, y): y['idf'] + y['protocol']): if self.allecus[ecu]['pin'] == 'iso' and self.allecus[ecu][ 'pin1'] == '7' and self.allecus[ecu]['pin2'] == '15': i = i + 1 lbltxt.text = 'Scanning:' + str(i) + '/' + str( len(self.allecus)) + ' Detected: ' + str( len(self.detectedEcus)) EventLoop.idle() self.elm.set_iso_addr(self.allecus[ecu]['dst'], self.allecus[ecu]) self.scan_iso(self.allecus[ecu]) lbltxt.text = 'Scanning:' + str(i) + '/' + str(len( self.allecus)) + ' Detected: ' + str(len(self.detectedEcus)) EventLoop.idle() mod_globals.state_scan = False self.detectedEcus = sorted(self.detectedEcus, key=lambda k: int(k['idf'])) if len(self.detectedEcus): pickle.dump(self.detectedEcus, open(SEFname, 'wb')) EventLoop.window.remove_widget(popup_scan) popup_scan.dismiss() base.stopTouchApp() EventLoop.window.canvas.clear() del popup_scan
class positive_transaction(GridLayout): #innherit class GridLayout def __init__(self, **kwargs): #defining constructor for class page super().__init__(**kwargs) #defining constructor for class GridLayout self.rows = 2 self.cols = 1 # self.label = Label(text = "This is positive transaction") # self.add_widget(self.label) self.add_asset = Button(text="Add Asset") # self.add_liability.bind(on_press = self.add_liability_pressed) self.add_asset.bind(on_press=lambda instance: self.button_pressed(1)) self.add_widget(self.add_asset) self.reduce_liability = Button(text="Reduce Liability") # self.reduce_asset.bind(on_press = self.reduce_asset_pressed) self.reduce_liability.bind( on_press=lambda instance: self.button_pressed(2)) self.add_widget(self.reduce_liability) def button_pressed(self, option): self.popup_layout = GridLayout(rows=2) # popup_layout.add_widget(Label(text='Transaction Added')) self.file_chooser = FileChooserIconView( size_hint_y=4, path= 'C:\\Users\\anshs\\Desktop\\study\\5th_sem\\DBD\\project\\bills', multiselect=True) self.popup_layout.add_widget(self.file_chooser) self.close_popup = Button(text="OK", height=44) if option == 1: self.close_popup.bind(on_press=self.add_asset_pressed) else: self.close_popup.bind(on_press=self.reduce_liability_pressed) self.popup_layout.add_widget(self.close_popup) self.file_chooser_popup = Popup(title='Choose Files', content=self.popup_layout, size_hint=(.7, .7)) # close_popup.bind(on_press = success_popup.dismiss) self.file_chooser_popup.open() def reduce_liability_pressed(self, instance): self.file_chooser_popup.dismiss() print("you pressed reduce liability") self.file_path = self.file_chooser.selection print(self.file_path) id = self.store_documents() sql.execute("INSERT INTO `liability` VALUES (%s, %s)", (str(id), '-' + amount)) sql.execute( "INSERT INTO `keep_in_book` VALUES (%s, %s, %s, %s, %s, %s)", (str(id), cashflow, book_no, date_time, amount, tax_payed)) commit() self.go_back() def add_asset_pressed(self, instance): self.file_chooser_popup.dismiss() print("you pressed add asset") self.file_path = self.file_chooser.selection id = self.store_documents() sql.execute("INSERT INTO `asset` VALUES (%s, %s)", (str(id), amount)) sql.execute( "INSERT INTO `keep_in_book` VALUES (%s, %s, %s, %s, %s, %s)", (str(id), cashflow, book_no, date_time, amount, tax_payed)) commit() self.go_back() def store_documents(self): # print(self.file_path) self.loading_popup_open() with open(self.file_path[0], 'rb') as file: self.data = file.read() text = convert(self.file_path[0]) if self.file_path[0][-4:] == 'JPEG' or self.file_path[0][-4:] == 'jpeg': self.extension = self.file_path[0][-5:] else: self.extension = self.file_path[0][-4:] id = (db['files'].insert_one({ 'file_data': self.data, 'text': text, 'extension': self.extension })).inserted_id print(id) # sql.execute("INSERT INTO `revenue` VALUES (%s, %s, %s)", (str(id), amount, tax_payed)) self.loading_popup.dismiss() return id def go_back(self): popup_layout = GridLayout(rows=2) popup_layout.add_widget(Label(text='Transaction Added')) close_popup = Button(text="OK") popup_layout.add_widget(close_popup) success_popup = Popup(title='Success', content=popup_layout, size_hint=(.3, .3)) close_popup.bind(on_press=success_popup.dismiss) success_popup.open() app.screenmanager.current = 'main_menu_screen' def loading_popup_open(self): print("Loading popup") self.loading_popup = Popup( title='Loading', content=Label(text="Extracting text and uploading documents"), size_hint=(.3, .3)) self.loading_popup.open()
class GroundControlApp(App): def get_application_config(self): return super(GroundControlApp, self).get_application_config( '~/%(appname)s.ini') 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.targetIndicatorColor = [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.targetIndicatorColor = [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.targetIndicatorColor = [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 def build_config(self, config): """ Set the default values for the config sections. """ # Calculate computed settings on load config.add_callback(self.computeSettings) config.setdefaults('Computed Settings', maslowSettings.getDefaultValueSection('Computed Settings')) config.setdefaults('Maslow Settings', maslowSettings.getDefaultValueSection('Maslow Settings')) config.setdefaults('Advanced Settings', maslowSettings.getDefaultValueSection('Advanced Settings')) config.setdefaults('Ground Control Settings', maslowSettings.getDefaultValueSection('Ground Control Settings')) config.setdefaults('Background Settings', maslowSettings.getDefaultValueSection('Background Settings')) config.setdefaults('Optical Calibration Settings', maslowSettings.getDefaultValueSection('Optical Calibration Settings')) config.remove_callback(self.computeSettings) def build_settings(self, settings): """ Add custom section to the default configuration object. """ settings.add_json_panel('Maslow Settings', self.config, data=maslowSettings.getJSONSettingSection('Maslow Settings')) settings.add_json_panel('Advanced Settings', self.config, data=maslowSettings.getJSONSettingSection('Advanced Settings')) settings.add_json_panel('Ground Control Settings', self.config, data=maslowSettings.getJSONSettingSection("Ground Control Settings")) def computeSettings(self, section, key, value): # Update Computed settings if key == 'kinematicsType': if value == 'Quadrilateral': self.config.set('Computed Settings', 'kinematicsTypeComputed', "1") else: self.config.set('Computed Settings', 'kinematicsTypeComputed', "2") elif (key == 'gearTeeth' or key == 'chainPitch') and self.config.has_option('Advanced Settings', 'gearTeeth') and self.config.has_option('Advanced Settings', 'chainPitch'): distPerRot = float(self.config.get('Advanced Settings', 'gearTeeth')) * float(self.config.get('Advanced Settings', 'chainPitch')) self.config.set('Computed Settings', "distPerRot", str(distPerRot)) if self.config.has_option('Advanced Settings', 'leftChainTolerance'): distPerRotLeftChainTolerance = (1 + (float(self.config.get('Advanced Settings', 'leftChainTolerance')) / 100)) * float(self.config.get('Advanced Settings', 'gearTeeth')) * float(self.config.get('Advanced Settings', 'chainPitch')) self.config.set('Computed Settings', "distPerRotLeftChainTolerance", str("{0:.5f}".format(distPerRotLeftChainTolerance))) if self.config.has_option('Advanced Settings', 'rightChainTolerance'): distPerRotRightChainTolerance = (1 + (float(self.config.get('Advanced Settings', 'rightChainTolerance')) / 100)) * float(self.config.get('Advanced Settings', 'gearTeeth')) * float(self.config.get('Advanced Settings', 'chainPitch')) self.config.set('Computed Settings', "distPerRotRightChainTolerance", str("{0:.5f}".format(distPerRotRightChainTolerance))) elif key == 'leftChainTolerance' and self.config.has_option('Advanced Settings', 'leftChainTolerance') and self.config.has_option('Computed Settings', 'distPerRot'): distPerRotLeftChainTolerance = (1 + (float(self.config.get('Advanced Settings', 'leftChainTolerance')) / 100)) * float(self.config.get('Computed Settings', 'distPerRot')) self.config.set('Computed Settings', "distPerRotLeftChainTolerance", str("{0:.5f}".format(distPerRotLeftChainTolerance))) elif key == 'rightChainTolerance' and self.config.has_option('Advanced Settings', 'rightChainTolerance') and self.config.has_option('Computed Settings', 'distPerRot'): distPerRotRightChainTolerance = (1 + (float(self.config.get('Advanced Settings', 'rightChainTolerance')) / 100)) * float(self.config.get('Computed Settings', 'distPerRot')) self.config.set('Computed Settings', "distPerRotRightChainTolerance", str("{0:.5f}".format(distPerRotRightChainTolerance))) elif key == 'enablePosPIDValues': for key in ('KpPos', 'KiPos', 'KdPos', 'propWeight'): if int(self.config.get('Advanced Settings', 'enablePosPIDValues')) == 1: value = float(self.config.get('Advanced Settings', key)) else: value = maslowSettings.getDefaultValue('Advanced Settings', key) self.config.set('Computed Settings', key + "Main", value) #updated computed values for z-axis for key in ('KpPosZ', 'KiPosZ', 'KdPosZ', 'propWeightZ'): if int(self.config.get('Advanced Settings', 'enablePosPIDValues')) == 1: value = float(self.config.get('Advanced Settings', key)) else: value = maslowSettings.getDefaultValue('Advanced Settings', key) self.config.set('Computed Settings', key, value) elif key == 'enableVPIDValues': for key in ('KpV', 'KiV', 'KdV'): if int(self.config.get('Advanced Settings', 'enablePosPIDValues')) == 1: value = float(self.config.get('Advanced Settings', key)) else: value = maslowSettings.getDefaultValue('Advanced Settings', key) self.config.set('Computed Settings', key + "Main", value) #updated computed values for z-axis for key in ('KpVZ', 'KiVZ', 'KdVZ'): if int(self.config.get('Advanced Settings', 'enablePosPIDValues')) == 1: value = float(self.config.get('Advanced Settings', key)) else: value = maslowSettings.getDefaultValue('Advanced Settings', key) self.config.set('Computed Settings', key, value) elif key == 'chainOverSprocket': if value == 'Top': self.config.set('Computed Settings', 'chainOverSprocketComputed', 1) else: self.config.set('Computed Settings', 'chainOverSprocketComputed', 2) elif key == 'fPWM': if value == '31,000Hz': self.config.set('Computed Settings', 'fPWMComputed', 1) elif value == '4,100Hz': self.config.set('Computed Settings', 'fPWMComputed', 2) else: self.config.set('Computed Settings', 'fPWMComputed', 3) def configSettingChange(self, section, key, value): """ Respond to changes in the configuration. """ # Update GC things if section == "Maslow Settings": if key == "COMport": self.data.comport = value if (key == "bedHeight" or key == "bedWidth"): self.frontpage.gcodecanvas.drawWorkspace() if (key == "macro1_title") or (key == "macro2_title"): self.frontpage.update_macro_titles() if section == "Advanced Settings": if (key == "truncate") or (key == "digits"): self.frontpage.gcodecanvas.reloadGcode() if (key == "spindleAutomate"): if (value == "Servo"): value = 1 elif (value == "Relay_High"): value = 2 elif (value == "Relay_Low"): value = 3 else: value = 0 # Update Computed Settings self.computeSettings(section, key, value) # Write the settings change to the Disk self.data.config.write() # only run on live connection if self.data.connectionStatus != 1: return # Push settings that can be directly written to machine print section+", "+key firmwareKey = maslowSettings.getFirmwareKey(section, key) print "pre-firmwareKey="+str(firmwareKey) if firmwareKey is not None: if ( (firmwareKey == 45) ): print "firmwareKey = 45" if (value != ""): maslowSettings.sendErrorArray(firmwareKey, value, self.data) else: print "firmwareKey="+str(firmwareKey) self.data.gcode_queue.put("$" + str(firmwareKey) + "=" + str(value)) def requestMachineSettings(self, *args): ''' Requests the machine to report all settings. This will implicitly cause a sync of the machine settings because if GroundControl sees a reported setting which does match its expected value, GC will push the correct setting to the machine. ''' if self.data.connectionStatus == 1: self.data.gcode_queue.put("$$") def receivedSetting(self, message): ''' This parses a settings report from the machine, usually received in response to a $$ request. If the value received does not match the expected value. ''' parameter, position = self.parseFloat(message, 0) value, position = self.parseFloat(message, position) if (parameter is not None and value is not None): maslowSettings.syncFirmwareKey(int(parameter), value, self.data) def parseFloat(self, text, position=0): ''' Takes a string and parses out the float found at position default to 0 returning a list of the matched float and the ending position of the float ''' # This regex comes from a python docs recommended regex = re.compile("[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?") match = regex.search(text[position:]) if match: return (float(match.group(0)), match.end(0)) else: return (None, position) ''' Update Functions ''' def writeToTextConsole(self, message): try: newText = self.frontpage.consoleText[-2000:] + message self.frontpage.consoleText = newText self.frontpage.textconsole.gotToBottom() except: self.frontpage.consoleText = "text not displayed correctly" def runPeriodically(self, *args): ''' this block should be handled within the appropriate widget ''' while not self.data.message_queue.empty(): #if there is new data to be read message = self.data.message_queue.get() if message[0] == "<": self.setPosOnScreen(message) elif message[0] == "$": self.receivedSetting(message) elif message[0] == "[": if message[1:4] == "PE:": self.setErrorOnScreen(message) elif message[1:8] == "Measure": measuredDist = float(message[9:len(message)-3]) try: self.data.measureRequest(measuredDist) except: print "No function has requested a measurement" elif message[0:13] == "Maslow Paused": self.data.uploadFlag = 0 self.writeToTextConsole(message) elif message[0:8] == "Message:": if self.data.calibrationInProcess and message[0:15] == "Message: Unable": #this suppresses the annoying messages about invalid chain lengths during the calibration process break self.previousUploadStatus = self.data.uploadFlag self.data.uploadFlag = 0 try: self._popup.dismiss() #close any open popup except: pass #there wasn't a popup to close content = NotificationPopup(continueOn = self.dismiss_popup_continue, text = message[9:]) if sys.platform.startswith('darwin'): self._popup = Popup(title="Notification: ", content=content, auto_dismiss=False, size=(360,240), size_hint=(.3, .3)) else: self._popup = Popup(title="Notification: ", content=content, auto_dismiss=False, size=(360,240), size_hint=(None, None)) self._popup.open() if global_variables._keyboard: global_variables._keyboard.bind(on_key_down=self.keydown_popup) self._popup.bind(on_dismiss=self.ondismiss_popup) elif message[0:6] == "ALARM:": self.previousUploadStatus = self.data.uploadFlag self.data.uploadFlag = 0 try: self._popup.dismiss() #close any open popup except: pass #there wasn't a popup to close content = NotificationPopup(continueOn = self.dismiss_popup_continue, text = message[7:]) if sys.platform.startswith('darwin'): self._popup = Popup(title="Alarm Notification: ", content=content, auto_dismiss=False, size=(360,240), size_hint=(.3, .3)) else: self._popup = Popup(title="Alarm Notification: ", content=content, auto_dismiss=False, size=(360,240), size_hint=(None, None)) self._popup.open() if global_variables._keyboard: global_variables._keyboard.bind(on_key_down=self.keydown_popup) self._popup.bind(on_dismiss=self.ondismiss_popup) elif message[0:8] == "Firmware": self.data.logger.writeToLog("Ground Control Version " + str(self.data.version) + "\n") self.writeToTextConsole("Ground Control " + str(self.data.version) + "\r\n" + message + "\r\n") #Check that version numbers match if float(message[-7:]) < float(self.data.version): self.data.message_queue.put("Message: Warning, your firmware is out of date and may not work correctly with this version of Ground Control\n\n" + "Ground Control Version " + str(self.data.version) + "\r\n" + message) if float(message[-7:]) > float(self.data.version): self.data.message_queue.put("Message: Warning, your version of Ground Control is out of date and may not work with this firmware version\n\n" + "Ground Control Version " + str(self.data.version) + "\r\n" + message) elif message == "ok\r\n": pass #displaying all the 'ok' messages clutters up the display else: self.writeToTextConsole(message) def ondismiss_popup(self, event): if global_variables._keyboard: global_variables._keyboard.unbind(on_key_down=self.keydown_popup) def keydown_popup(self, keyboard, keycode, text, modifiers): if (keycode[1] == 'enter') or (keycode[1] =='numpadenter') or (keycode[1] == 'escape'): self.dismiss_popup_continue() return True # always swallow keypresses since this is a modal dialog def dismiss_popup_continue(self): ''' Close The Pop-up and continue cut ''' self._popup.dismiss() self.data.quick_queue.put("~") #send cycle resume command to unpause the machine self.data.uploadFlag = self.previousUploadStatus #resume cutting if the machine was cutting before def dismiss_popup_hold(self): ''' Close The Pop-up and continue cut ''' self._popup.dismiss() self.data.uploadFlag = 0 #stop cutting def setPosOnScreen(self, message): ''' This should be moved into the appropriate widget ''' try: startpt = message.find('MPos:') + 5 endpt = message.find('WPos:') numz = message[startpt:endpt] units = "mm" #message[endpt+1:endpt+3] valz = numz.split(",") self.xval = float(valz[0]) self.yval = float(valz[1]) self.zval = float(valz[2]) if math.isnan(self.xval): self.writeToTextConsole("Unable to resolve x Kinematics.") self.xval = 0 if math.isnan(self.yval): self.writeToTextConsole("Unable to resolve y Kinematics.") self.yval = 0 if math.isnan(self.zval): self.writeToTextConsole("Unable to resolve z Kinematics.") self.zval = 0 except: print "One Machine Position Report Command Misread" return self.frontpage.setPosReadout(self.xval, self.yval, self.zval) self.frontpage.gcodecanvas.positionIndicator.setPos(self.xval,self.yval,self.data.units) for widget in self.root_window.children: if isinstance(widget,Popup): if widget.title == "Maslow Optical Calibration": widget.content.updatePositionIndicator(self.xval,self.yval,self.data.units) def setErrorOnScreen(self, message): try: startpt = message.find(':')+1 endpt = message.find(',', startpt) leftErrorValueAsString = message[startpt:endpt] leftErrorValueAsFloat = float(leftErrorValueAsString) startpt = endpt + 1 endpt = message.find(',', startpt) rightErrorValueAsString = message[startpt:endpt] rightErrorValueAsFloat = float(rightErrorValueAsString) if self.data.units == "INCHES": rightErrorValueAsFloat = rightErrorValueAsFloat/25.4 leftErrorValueAsFloat = leftErrorValueAsFloat/25.4 avgError = (abs(leftErrorValueAsFloat) + abs(rightErrorValueAsFloat))/2 self.frontpage.gcodecanvas.positionIndicator.setError(0, self.data.units) self.data.logger.writeErrorValueToLog(avgError) self.frontpage.gcodecanvas.targetIndicator.setPos(self.xval - .5*rightErrorValueAsFloat + .5*leftErrorValueAsFloat, self.yval - .5*rightErrorValueAsFloat - .5*leftErrorValueAsFloat,self.data.units) except: print "Machine Position Report Command Misread Happened Once"
class ListScreen(Screen): def __init__(self, **kwargs): super(ListScreen, self).__init__(**kwargs) # run clock Clock.schedule_interval(self.init_gui, 0.2) Clock.schedule_interval(self.show_status, 0.03) def init_gui(self, dt): self.new_file() Clock.unschedule(self.init_gui) Clock.schedule_interval(self.cam_update, 0.03) def cam_update(self, dt): try: _, frame = self.capture.read() buf1 = cv2.flip(frame, 0) buf = buf1.tostring() texture1 = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='rgb') texture1.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte') self.ids['img_cam'].texture = texture1 except Exception as e: pass #### File menu def exit_app(self): self.camera_disconnect() self.printer_disconnect() App.get_running_app().stop() def new_file(self): ## File menu / New Project self.init_project() def init_project(self): # init data self.project_file_path = "" self.project_data=data.init_project_data() self.project_data['CADMode']="None" self.ids["img_cad_origin"].set_cad_view(self.project_data) self.ids["img_cad_origin"].redraw_cad_view() self.capture = None self.print = None self.paneldisselection=[] try: self.camera_disconnect() self.camera_connect() self.printer_disconnect() self.printer_connect() except Exception as e: print(e, "cam or printer start problem") pass def load_file(self): ### File Menu / Load project content = LoadDialog(load=self.load, cancel=self.dismiss_popup) self._popup = Popup(title="Load file", content=content, size_hint=(0.9, 0.9)) self._popup.open() self.project_data['CADMode']="None" def load(self, path, filename): ### click load button of Loading Dialog ### load all info from pre saved project file try: ### if proper project file self.project_file_path = os.path.expanduser(filename[0]) self.project_data=data.read_project_data(self.project_file_path) self.paneldisselection=[] try: self.camera_disconnect() self.camera_connect() self.printer_disconnect() self.printer_connect() except Exception as e: print(e, "cam or printer start problem") pass self.ids["img_cad_origin"].set_cad_view(self.project_data) self.ids["img_cad_origin"].redraw_cad_view() except: ### if not proper project file print("Problem loading file") self.dismiss_popup() return self.dismiss_popup() def save_file(self): ### File Menu / Save Project if self.project_file_path == "": self.save_as_file() else: data.write_project_data(self.project_file_path, self.project_data) def save_as_file(self): ### File Menu / Save as Project content = SaveDialog(save=self.save, cancel=self.dismiss_popup) self._popup = Popup(title="Save file", content=content, size_hint=(0.9, 0.9)) self._popup.open() self.project_data['CADMode']="None" def save(self, path, filename): ### after click Save button of Save Dialog self.project_file_path = os.path.expanduser(os.path.join(path, filename)) print(path, filename, self.project_file_path) data.write_project_data(self.project_file_path, self.project_data) self.dismiss_popup() #### program menu #### def import_file(self): ### Program menu / import NC drills content = ImportDialog(load=self.import_ncdrill, cancel=self.dismiss_popup) self._popup = Popup(title="Import file", content=content, size_hint=(0.9, 0.9)) self._popup.open() self.project_data['CADMode']="None" def import_ncdrill(self, path, filename): ### after click load button of Loading button try: ### if proper project file nc_file_path = os.path.expanduser(filename[0]) ncdata=excellon.load_nc_drill(nc_file_path) print("ncdata", ncdata) # convert tool list for selection self.project_data['NCTool']=excellon.convert_to_tools(ncdata) # convert soldering tool path self.project_data['SolderToolpath']=excellon.convert_to_json(ncdata) # redraw self.ids["img_cad_origin"].redraw_cad_view() except: ### if not proper project file self.dismiss_popup() return self.dismiss_popup() def select_side(self): ### Program menu / Select Soldering Side side = [ { "text" : "Top", "is_selected" : self.project_data['SolderSide']=="Top" }, { "text" : "Bottom", "is_selected" : self.project_data['SolderSide']=="Bottom" } ] self.ignore_first=not side[0]['is_selected'] content = ListPopup() args_converter = lambda row_index, rec: {'text': rec['text'], 'is_selected': rec['is_selected'], 'size_hint_y': None, 'height': 50} list_adapter = ListAdapter(data=side, args_converter=args_converter, propagate_selection_to_data=True, cls=ListItemButton, selection_mode='single', allow_empty_selection=False) list_view = ListView(adapter=list_adapter) content.ids.profile_list.add_widget(list_view) list_view.adapter.bind(on_selection_change=self.selected_side) self._popup = Popup(title="Select Soldering Side", content=content, size_hint=(0.5, 0.6)) self._popup.open() self.project_data['CADMode']="None" def selected_side(self, adapter): if self.ignore_first: self.ignore_first=False return self.project_data['SolderSide']=adapter.selection[0].text self.dismiss_popup() self.ids["img_cad_origin"].redraw_cad_view() def select_profile(self): ### Program menu / Select Soldering Profile profile = excellon.convert_to_solderingprofile(self.project_data) if len(profile) < 1: return self.ignore_first=not profile[0]['is_selected'] content = ListPopup() args_converter = lambda row_index, rec: {'text': rec['text'], 'is_selected': rec['is_selected'], 'size_hint_y': None, 'height': 50} list_adapter = ListAdapter(data=profile, args_converter=args_converter, propagate_selection_to_data=True, cls=ListItemButton, selection_mode='single', allow_empty_selection=False) list_view = ListView(adapter=list_adapter) content.ids.profile_list.add_widget(list_view) list_view.adapter.bind(on_selection_change=self.selected_profile) self._popup = Popup(title="Select Soldering Profile", content=content, size_hint=(0.5, 0.6)) self._popup.open() self.project_data['CADMode']="None" def selected_profile(self, adapter): ### select profile on soldering profile list if self.ignore_first: self.ignore_first=False return num=excellon.get_solderingprofile_index_by_id(self.project_data['SolderingProfile']['SolderingProfile'], adapter.selection[0].text) self.project_data['SelectedSolderingProfile']=num self.dismiss_popup() self.ids["img_cad_origin"].redraw_cad_view() self.project_data['CADMode']="Select" def select_by_dia(self): ### Program Menu / Select soldering pad by diameter tools=self.project_data['NCTool'] if len(tools) < 1: return self.ignore_first=not tools[0]['is_selected'] content = ListPopup() args_converter = lambda row_index, rec: {'text': rec['text'], 'is_selected': rec['is_selected'], 'size_hint_y': None, 'height': 40} list_adapter = ListAdapter(data=tools, args_converter=args_converter, propagate_selection_to_data=True, cls=ListItemButton, selection_mode='single', allow_empty_selection=False) list_view = ListView(adapter=list_adapter) content.ids.profile_list.add_widget(list_view) list_view.adapter.bind(on_selection_change=self.selected_tools) self._popup = Popup(title="Select Soldering Pad by Tools", content=content, size_hint=(0.5, 0.7)) self._popup.open() self.project_data['CADMode']="None" def selected_tools(self, adapter): ### select tool on tools' list if self.ignore_first: self.ignore_first=False return soldertoolpath=self.project_data['SolderToolpath'] num=int(adapter.selection[0].text.split(":")[0]) excellon.select_by_tool(soldertoolpath, num, self.project_data['SelectedSolderingProfile']) # redraw self.dismiss_popup() self.ids["img_cad_origin"].redraw_cad_view() def select_by_view(self): ### Program menu / Select Soldering pads by View self.project_data['CADMode']="Select" def deselect_by_view(self): ### Program Menu / Deselect by view self.project_data['CADMode']="Deselect" def set_reference1(self): ### Program Menu / Set Reference point 1 self.project_data['CADMode']="Ref1" def set_reference2(self): ### Program Menu / Set Reference Point 2 self.project_data['CADMode']="Ref2" def optmize_nc(self): ### Program Menu / Optmize NC drills soldertoolpath=self.project_data['SolderToolpath'] excellon.optimize_soldertoolpath(soldertoolpath) ##### panel menu def set_num_panel(self): num=excellon.get_num_panel(self.project_data['Panel']) content = EditPopup(save=self.save_panel_num, cancel=self.dismiss_popup) content.ids["btn_connect"].text = "Save" content.ids["text_port"].text = str(num) self._popup = Popup(title="Select panel num", content=content, size_hint=(0.5, 0.4)) self._popup.open() self.project_data['CADMode']="None" def save_panel_num(self, txt_port): # set num of panels num = int(txt_port) num = max(1, num) num = min(self.project_data['Setup']['MaxPanel'], num) excellon.set_num_panel(self.project_data['Panel'], num) self.dismiss_popup() def set_reference_panel(self): # show dialpad print("ref") self.ids["tab_panel"].switch_to(self.ids["tab_panel"].tab_list[0]) self.content = ControlPopup(controlXYZ=self.control_XYZ, set_panel_ref1=self.set_panel_ref1, set_panel_ref2=self.set_panel_ref2, get_panel_ref1=self.get_panel_ref1, get_panel_ref2=self.get_panel_ref2, cancel=self.dismiss_popup) self.content.ids["cur_X"].text = format(self.project_data['Setup']['TravelX'],".2f") self.content.ids["cur_Y"].text = format(self.project_data['Setup']['TravelY'],".2f") self.content.ids["cur_Z"].text = format(self.project_data['Setup']['TravelZ'],".2f") self.content.ids["cur_panel"].text = "1" self._popup = Popup(title="Set reference point", content=self.content, size_hint=(0.4, 0.4), background_color=[0, 0, 0, 0.0]) self._popup.pos_hint={"center_x": .8, "center_y": .8} self._popup.open() self.project_data['CADMode']="None" # home printer gcode=robotcontrol.go_home(self.project_data) self.queue_printer_command(gcode) def control_XYZ(self, axis, value): ### click any button on dialpad, calculate new position index=int(self.content.ids["cur_panel"].text) x=float(self.content.ids["cur_X"].text) y=float(self.content.ids["cur_Y"].text) z=float(self.content.ids["cur_Z"].text) if axis == "X": x += float(value) elif axis == "Y": y += float(value) elif axis == "Z": z += float(value) elif axis == "HomeXY": x=self.project_data['Setup']['TravelX'] y=self.project_data['Setup']['TravelY'] elif axis == "HomeZ": z=self.project_data['Setup']['TravelZ'] index = max(1, index) index = min(self.project_data['Setup']['MaxPanel'], index) x=max(self.project_data['Setup']['MinX'],x) x=min(self.project_data['Setup']['MaxX'],x) y=max(self.project_data['Setup']['MinY'],y) y=min(self.project_data['Setup']['MaxY'],y) z=max(self.project_data['Setup']['MinZ'],z) z=min(self.project_data['Setup']['MaxZ'],z) self.content.ids["cur_panel"].text = str(index) self.content.ids["cur_X"].text = format(x,".2f") self.content.ids["cur_Y"].text = format(y,".2f") self.content.ids["cur_Z"].text = format(z,".2f") # go xyz printer gcode=robotcontrol.go_xyz(self.project_data,x,y,z) self.queue_printer_command(gcode) def set_panel_ref1(self): ### click set1 button on dialpad index=int(self.content.ids["cur_panel"].text) index=min(index,excellon.get_num_panel(self.project_data['Panel'])) index=max(index,1) x=float(self.content.ids["cur_X"].text) y=float(self.content.ids["cur_Y"].text) z=float(self.content.ids["cur_Z"].text) excellon.set_panel_reference_1(self.project_data['Panel'], index-1, x, y, z) def set_panel_ref2(self): ### click set2 button on dialpad index=int(self.content.ids["cur_panel"].text) x=float(self.content.ids["cur_X"].text) y=float(self.content.ids["cur_Y"].text) z=float(self.content.ids["cur_Z"].text) excellon.set_panel_reference_2(self.project_data['Panel'], index-1, x, y, z) def get_panel_ref1(self): ### click on get1 button on dialpad index=int(self.content.ids["cur_panel"].text) x,y,z = excellon.get_panel_reference_1(self.project_data['Panel'], index-1) if x==-1 and y==-1 and z==-1: x=self.project_data['Setup']['TravelX'] y=self.project_data['Setup']['TravelY'] z=self.project_data['Setup']['TravelZ'] self.content.ids["cur_X"].text = format(x,".2f") self.content.ids["cur_Y"].text = format(y,".2f") self.content.ids["cur_Z"].text = format(z,".2f") # go xyz printer gcode=robotcontrol.go_xyz(self.project_data,x,y,z) self.queue_printer_command(gcode) def get_panel_ref2(self): ### click on get2 button on dialpad index=int(self.content.ids["cur_panel"].text) x,y,z = excellon.get_panel_reference_2(self.project_data['Panel'], index-1) if x==-1 and y==-1 and z==-1: x=self.project_data['Setup']['TravelX'] y=self.project_data['Setup']['TravelY'] z=self.project_data['Setup']['TravelZ'] self.content.ids["cur_X"].text = format(x,".2f") self.content.ids["cur_Y"].text = format(y,".2f") self.content.ids["cur_Z"].text = format(z,".2f") # go xyz printer gcode=robotcontrol.go_xyz(self.project_data,x,y,z) self.queue_printer_command(gcode) def select_pcb_in_panel(self): num=excellon.get_num_panel(self.project_data['Panel']) content = EditPopup(save=self.save_pcb_in_panel, cancel=self.dismiss_popup) content.ids["btn_connect"].text = "Save" content.ids["text_port"].text = "" self._popup = Popup(title="Select Panels to exclude from Soldering example \"1,2\"", content=content, size_hint=(0.5, 0.4)) self._popup.open() self.project_data['CADMode']="None" def save_pcb_in_panel(self, txt_port): # set array of panels excludepanels=txt_port.split(",") panel=[] for p in range(excellon.get_num_panel(self.project_data['Panel'])): if str(p+1) in excludepanels: panel.append(p) self.paneldisselection=panel self.dismiss_popup() def start_soldering(self): ### toolbar start soldering button # prepare panel panel=[] for p in range(excellon.get_num_panel(self.project_data['Panel'])): if p not in self.paneldisselection: panel.append(p) # print print("panel", panel) gcode=robotcontrol.panel_soldering(self.project_data, panel, False) self.queue_printer_command(gcode) def test_soldering(self): ### toolbar test soldering button # prepare panel panel=[] for p in range(excellon.get_num_panel(self.project_data['Panel'])): if p not in self.paneldisselection: panel.append(p) # print gcode=robotcontrol.panel_soldering(self.project_data, panel, True) self.queue_printer_command(gcode) def pause_soldering(self): ### toolbar pause soldering button if self.print.printing: self.print.pause() def resume_soldering(self): ### toolbar resume soldering button if self.print.printing: self.print.resume() def stop_soldering(self): ### toolbar stop soldering button if self.print.printing: self.print.cancelprint() def queue_printer_command(self, gcode): garray=robotcontrol.make_array(gcode) #print("gcode raw", gcode, garray) gcoded = gcoder.LightGCode(garray) #print("gcoded", gcoded) if hasattr(self,'print') and self.print is not None: if not self.print.online or not self.print.printer: print("Problem with printer", self.print.online, self.print.printer) if self.print.printing: self.print.send(gcoded) else: self.print.startprint(gcoded) else: print("Problem with printer interface") #### Connect menu def set_printer(self): ### Connect Menu / Connect Printer content = EditPopup(save=self.save_printer_port, cancel=self.dismiss_popup) content.ids["text_port"].text = self.project_data['Setup']['RobotPort'] self._popup = Popup(title="Select Printer port", content=content, size_hint=(0.5, 0.4)) self._popup.open() self.project_data['CADMode']="None" def save_printer_port(self, txt_port): self.project_data['Setup']['RobotPort'] = txt_port try: self.printer_disconnect() self.printer_connect() except Exception as e: print(e,"exception save robot port") pass self.dismiss_popup() def set_camera(self): # set camera device content = EditPopup(save=self.save_camera_port, cancel=self.dismiss_popup) content.ids["text_port"].text = self.project_data['Setup']['CameraPort'] self._popup = Popup(title="Select Camera port", content=content, size_hint=(0.5, 0.4)) self._popup.open() self.project_data['CADMode']="None" def save_camera_port(self, txt_port): self.project_data['Setup']['CameraPort'] = txt_port try: self.camera_disconnect() self.camera_connect() except Exception as e: print(e,"exception save cam port") pass self.dismiss_popup() def dismiss_popup(self): self._popup.dismiss() def camera_connect(self): ### connect camera self.capture = VideoCaptureAsync(self.project_data['Setup']['CameraPort']) self.capture.start() def camera_disconnect(self): if self.capture is not None: self.capture.stop() self.capture = None def printer_connect(self): if self.print is None: self.print = printcore(self.project_data['Setup']['RobotPort'], 115200) def printer_disconnect(self): if self.print is not None: self.print.disconnect() self.print = None def show_status(self, dt): self.ids["lbl_layer_status"].text="Layer: "+self.project_data['SolderSide'] self.ids["lbl_cad_status"].text="CADMode: "+self.project_data['CADMode'] profile=excellon.get_list_soldering_profile(self.project_data['SolderingProfile']) self.ids["lbl_profile_status"].text="Profile: "+profile[self.project_data['SelectedSolderingProfile']] if hasattr(self,'capture') and self.capture is not None: self.ids["lbl_cam_status"].text="Camera: Connected" else: self.ids["lbl_cam_status"].text="Camera: Not Found" #printer if hasattr(self,'print') and self.print is not None: if self.print.printer is None: self.ids["lbl_printer_status"].text="Robot: No 3d printer found" elif self.print.printing: if len(self.print.mainqueue)>0: self.ids["lbl_printer_status"].text="Robot: Soldering "+ str(round(float(self.print.queueindex) / len(self.print.mainqueue)*100,2))+"%" else: self.ids["lbl_printer_status"].text="Robot: Soldering" elif self.print.online: self.ids["lbl_printer_status"].text="Robot: Idle" else: self.ids["lbl_printer_status"].text="Robot: Connected" else: self.ids["lbl_printer_status"].text="Robot: Not Found"