class CinemaManager(BaseWidget): def __init__(self, *args, **kwargs): super().__init__('Cinema manager') self._pesel = "" self._client = Client('http://localhost:8080/projekt?wsdl') self._selected_date = date.today() # Screening window self._search_screenings_button = ControlButton("Search") self._screening_day = ControlNumber("Day:", default=self._selected_date.day, minimum=1, maximum=monthrange(self._selected_date.year, self._selected_date.month)[1], changed_event=self._change_day) self._screening_month = ControlNumber("Month:", default=self._selected_date.month, minimum=1, maximum=12, changed_event=self._change_month) self._screening_year = ControlNumber("Year:", default=self._selected_date.year, minimum=self._selected_date.year, maximum=self._selected_date.year + 1, changed_event=self._change_day) self._screening_list = ControlList('Screenings', readonly=True, select_entire_row=True, cell_double_clicked_event=self._screening_changed_event) self._screening_list.horizontal_headers = ['Time', 'Movie', 'Description'] self._all_showings = self._client.service.getShowingsByDate(self._selected_date.year, self._selected_date.month, self._selected_date.day) self._search_screenings_button.value = self._searchScreeningsButton for showing in self._all_showings: self._screening_list += [showing.date.strftime("%H:%M"), str(showing.movie.title), str(showing.movie.description)] # Client window self._all_reservations = [] self._reservation_list = ControlList('Reservations', readonly=True, select_entire_row=True, cell_double_clicked_event=self._reservation_changed_event) self._reservation_list.horizontal_headers = ['Date', 'Time', 'Movie', 'Seats', 'Paid'] self._screening_panel = ControlDockWidget() self._screening_panel.hide() self._reservation_panel = ControlDockWidget() self._reservation_panel.hide() self._loginWindow = LoginWindow(self._client) self.hide() self._loginWindow.parent = self self._loginWindow.show() print(self._client.service) # Define the organization of the Form Controls self.formset = [{ 'a:Screening': [('_screening_day', '_screening_month', '_screening_year', '_search_screenings_button'), '=', '_screening_list'], 'b:Client': ['_reservation_list'] }, ] def _screening_changed_event(self, row, column): self._all_showings = self._client.service.getShowingsByDate(self._selected_date.year, self._selected_date.month, self._selected_date.day) print(self._all_showings) win = ScreeningWindow(self._all_showings[row], self._client, self._pesel) win.parent = self self._screening_panel.show() self._reservation_panel.hide() self._screening_panel.label = "Screening info" self._screening_panel.value = win def _reservation_changed_event(self, row, column): self._all_reservations = self._client.service.getUserReservationsByPesel(self._pesel) win = ClientReservationWindow(self._all_reservations[row], self._client) win.parent = self self._screening_panel.hide() self._reservation_panel.show() self._reservation_panel.label = "Reservation details" self._reservation_panel.value = win def setUserPesel(self,pesel): self._pesel = pesel self.updateInfo() def updateInfo(self): self._screening_list.clear() self._all_showings = self._client.service.getShowingsByDate(self._selected_date.year, self._selected_date.month, self._selected_date.day) for show in self._all_showings: self._screening_list += [show.date.strftime("%H:%M"), str(show.movie.title), str(show.movie.description)] self._reservation_list.clear() self._all_reservations = self._client.service.getUserReservationsByPesel(self._pesel) for reservation in self._all_reservations: self._reservation_list += [reservation['showing']['date'].strftime("%d-%m-%Y"), reservation['showing']['date'].strftime("%H:%M"), str(reservation['showing']['movie']['title']), str(reservation['places']), "Yes" if reservation['isPaid'] is True else "No"] def _searchScreeningsButton(self): self._screening_list.clear() self._all_showings = self._client.service.getShowingsByDate(self._selected_date.year, self._selected_date.month, self._selected_date.day) for show in self._all_showings: self._screening_list += [show.date.strftime("%H:%M"), str(show.movie.title), str(show.movie.description)] def _change_day(self): self._selected_date = self._selected_date.replace(day=int(self._screening_day.value)) def _change_month(self): self._selected_date = self._selected_date.replace(month=int(self._screening_month.value), day=1) self._screening_day.max = monthrange(self._selected_date.year, self._selected_date.month)[1] self._screening_day.value = 1
class MBUI(BaseWidget): # pass in global vars global loader global timerThread # Default Constructor # -------------------------------------------------------------------------------- # Primarily used to create and set up UI components and class variables. def __init__(self): # Class Vars: self.__players = [] # List of players # Player Setup Tab -- Init UI Elements #super(MBUI, self).__init__("Millennium Blades Helper") BaseWidget.__init__(self, "Millennium Blades Helper") self._lstPlayers = ControlList('Player List') self._btnAddPl = ControlButton('Add Player') self._btnRemPl = ControlButton('Remove Selected Player') self._btnGenPl = ControlButton('Generate Player Setup') # Player Setup Tab -- Set up properties of UI elements, attach callbacks, etc. self._lstPlayers.horizontal_headers = [ 'Name', 'Character', 'Starter Deck' ] self._btnAddPl.value = self.__onAddPlayerClick self._btnRemPl.value = self.__onRemoveSelectedPlayerClick self._btnGenPl.value = self.__onGeneratePlayerSetupClick # Store Setup Tab -- Init UI Elements self._lstStore = ControlList('Store Components') self._ckAreaLabel = ControlLabel('Sets To Use') self._btnGenerateSt = ControlButton('Generate Store') # Store Setup Tab -- Set up properties of UI elements, attach callbacks etc. self._lstStore.horizontal_headers = ['Category', 'Sets'] self._btnGenerateSt.value = self.__onGenerateStoreClick # Scoring Tab -- Init UI Components self._scoringPanel = ControlEmptyWidget() self._btnGetScoring = ControlButton('Generate Score Sheet') # Scoring Tab -- Set up properties of UI elements, attach callbacks etc. self._btnGetScoring.value = self.__onGenerateScoringClick # Set Selection Tab -- Init UI Components self._chkArea = ControlCheckBoxList('Sets To Use') # Set Selection Tab -- Set up properties of UI elements, attach callbacks etc. self._chkArea += ('Base Set', True) self._chkArea += ('Set Rotation', True) self._chkArea += ('MX #1: Crossover', True) self._chkArea += ('MX #2: Sponsors', True) self._chkArea += ('MX #3: Fusion Chaos', True) self._chkArea += ('MX #4: Final Bosses', True) self._chkArea += ('MX #5: Futures', True) self._chkArea += ('MX #6: Professionals', True) # Set up tabs and component flow for UI self.formset = [{ '1. Player Setup': ['_lstPlayers', ' ', ('_btnAddPl', '_btnRemPl', '_btnGenPl')], '2. Store Setup': ['_lstStore', ' ', '_btnGenerateSt'], '3. Scoring': ['_scoringPanel', '_btnGetScoring'], '4. Set Selection': ['_chkArea'] }] # Add Player Method # -------------------------------------------------------------------------------- # Used to add a single player to the list of players in the Player Setup tab. def addPlayer(self, player): # Add player to list self._lstPlayers += [ player.name + '\t\t', player.character + '\t\t', player.deck ] # Mark deck and character player chose as chosen loader.markSetChosen(player.character) loader.markSetChosen(player.deck) # Append player to list of players self.__players.append(player) # Close the choose player UI player.close() # Add Multi Player Method # -------------------------------------------------------------------------------- # Used to add multiple players to the player list. Unlike the add player method, # this assumes that the player objects have already been marked chosen and simply # appends them to the list under Player Setup and also adds them to the global # players list. It also takes in a separate reference to a window to close. def addMultiPlayer(self, players, window): for player in players: self._lstPlayers += [ player.name + '\t\t', player.character + '\t\t', player.deck ] self.__players.append(player) window.close() # Player Setup Tab -- Button Callbacks def __onAddPlayerClick(self): win = AddPlayerUI(self._chkArea.checked_indexes) win.parent = self win.show() def __onRemoveSelectedPlayerClick(self): self._lstPlayers -= self._lstPlayers.selected_row_index def __onGeneratePlayerSetupClick(self): loader.clearPlayerSetup() self._lstPlayers.clear() win = GeneratePlayersUI(self._chkArea.checked_indexes) win.parent = self win.show() # Store Setup Tab -- Button Callbacks def __onGenerateStoreClick(self): expansion = "" premium = "" master = "" fusion = "" tournament = "" seed(datetime.now()) loader.clearStoreSetup() self._lstStore.clear() # Randomly select expansion sets and add to store for _ in range(0, 5): expansions = loader.getFilteredList(MBType.EXPANSION, self._chkArea.checked_indexes) exIdx = randint(0, len(expansions) - 1) expansion += expansions[exIdx] + ', ' loader.markSetChosen(expansions[exIdx]) expansion = expansion[:-2] self._lstStore += ['Expansion Sets\t\t', expansion] # Randomly select premium sets and add to store for _ in range(0, 4): premiums = loader.getFilteredList(MBType.PREMIUM, self._chkArea.checked_indexes) preIdx = randint(0, len(premiums) - 1) premium += premiums[preIdx] + ', ' loader.markSetChosen(premiums[preIdx]) premium = premium[:-2] self._lstStore += ['Premium Sets\t\t', premium] # Randomly select master sets and add to store for _ in range(0, 3): masters = loader.getFilteredList(MBType.MASTER, self._chkArea.checked_indexes) masIdx = randint(0, len(masters) - 1) master += masters[masIdx] + ', ' loader.markSetChosen(masters[masIdx]) master = master[:-2] self._lstStore += ['Master Sets\t\t', master] # Randomly select fusion area sets and add to store fusionBronze = loader.getFilteredList(MBType.BRONZE, self._chkArea.checked_indexes) fusionSilver = loader.getFilteredList(MBType.SILVER, self._chkArea.checked_indexes) fusionGold = loader.getFilteredList(MBType.GOLD, self._chkArea.checked_indexes) fbIdx = randint(0, len(fusionBronze) - 1) fsIdx = randint(0, len(fusionSilver) - 1) fgIdx = randint(0, len(fusionGold) - 1) fusion = '(Bronze) ' + fusionBronze[fbIdx] + ', ' fusion += '(Silver) ' + fusionSilver[fsIdx] + ', ' fusion += '(Gold) ' + fusionGold[fgIdx] loader.markSetChosen(fusionBronze[fbIdx]) loader.markSetChosen(fusionSilver[fsIdx]) loader.markSetChosen(fusionGold[fgIdx]) self._lstStore += ['Fusion Area Sets\t\t', fusion] # Randomly select tournament prizes and add to store tournamentBronze = loader.getFilteredList( MBType.BRONZE, self._chkArea.checked_indexes) tournamentSilver = loader.getFilteredList( MBType.SILVER, self._chkArea.checked_indexes) tbIdx = randint(0, len(tournamentBronze) - 1) tsIdx = randint(0, len(tournamentSilver) - 1) tournament = '(Bronze) ' + tournamentBronze[tbIdx] + ', ' tournament += '(Silver) ' + tournamentSilver[tsIdx] loader.markSetChosen(tournamentBronze[tbIdx]) loader.markSetChosen(tournamentSilver[tsIdx]) self._lstStore += ['Tournament Prize Sets\t\t', tournament] # Scoring Tab -- Callback Functions def __onGenerateScoringClick(self): win = None if len(self.__players) > 0: win = ScoringUI(self.__players) win.parent = self self._scoringPanel.value = win win.show() # Close Application Callback def before_close_event(self): # If we have an executing timer thread, join it before exiting otherwise this # will hang if timerThread is not None: timerThread.join()
class NotificationsWidget(Notifications, BaseWidget): def __init__(self, user = None, connection = None): Notifications.__init__(self) BaseWidget.__init__(self) self._user = user self._connection = connection self._refresh_button = ControlToolButton('Refresh', maxheight= 50, maxwidth= 100) self._notifCache=None self._notifList = ControlList('Notifications', select_entire_row = True) self._notifList.readonly = True self._notifList.cell_double_clicked_event = self.__onDouble #self._notifList.item_selection_changed_event = self.__softSelect self._notifList.horizontal_headers = [ 'Timestamp', 'Symbol', 'Price', 'Message'] self._notifList.add_popup_menu_option('Edit', function_action= self.__popEdit) self._notifList.add_popup_menu_option('Delete', function_action= self.__deleteNotif) self._plusBtn = ControlButton('New Notification') self._plusBtn.value= self.__addNotifBtnAction if self._user!=None and self._connection!=None: self._refresh_button.value= self._refresh self._retreive_existing() def _refresh(self): self._notifList.clear() self._retreive_existing() if self.parent!=None: self.parent.persist_login() def _retreive_existing(self): try: pull_list = pull_notifications(self._user, self._connection) self._notifCache=pull_list except ValueError as err: err= ErrorWin(err) err.parent = self err.show() return if pull_list: for i in pull_list: ts = pull_list[i]['timestamp'] datestring=datetime.fromtimestamp(ts/1e3).strftime('%Y-%m-%d %H:%M:%S') self._notifList.__add__([datestring, pull_list[i]['symbol'], pull_list[i]['price'], pull_list[i]['message']]) def __addNotifBtnAction(self): if self.parent!=None: self.parent.persist_login() win = NotificationWidget(self._user, self._connection, '', '', '', '', 'new') win.parent = self win.show() def __rmNotifBtnAction(self): self.__deleteNotif(self) def __onDouble(self, row, column): if self.parent!=None: self.parent.persist_login() timestamp = self._notifList.get_value(0, row) symbol = self._notifList.get_value(1, row) index = self._notifList.get_value(2, row) message = self._notifList.get_value(3, row) win = NotificationWidget(self._user, self._connection, timestamp, symbol, index, message, 'view') win.parent = self win.show() def __popEdit(self): row = self._notifList.selected_row_index timestamp = self._notifList.get_value(0, row) symbol = self._notifList.get_value(1, row) index = self._notifList.get_value(2, row) message = self._notifList.get_value(3, row) for i in self._notifCache: if self._notifCache[i]['message']== message: key = i #print("popedit key found: " + key) win = NotificationWidget(self._user, self._connection, timestamp, symbol, index, message, "edit", key) win.parent = self win.show() def __softSelect(self, row, column): self._notifList.form.get_value(row, column) def __deleteNotif(self): row = self._notifList.selected_row_index message = self._notifList.get_value(3, row) for i in self._notifCache: if self._notifCache[i]['message']== message: key= i try: del_notification(self._user, self._connection, key) self._notifList.__sub__(row) except ValueError as error: err= ErrorWin(error) err.parent = self err.show() return
class AlyaGUI(BaseWidget): def __init__(self): super(AlyaGUI,self).__init__('Alya Case Editor') #Layer for IO handling self._fileio = AlyaFileIO() self._log = ControlTextArea('Log') self._fileio.SetLogControl(self.__addlog) #Main form fields self._casepath = ControlDir('Case path', default='/home/costa/Downloads/1111') self._fileio.SetCasePath(self._casepath._value) self._casename = ControlCombo('Case') self._casePathScan = ControlButton('Scan Path') self._casePathScan.value = self.___casePathScan_pressed self._caseReload = ControlButton('Load Case') self._caseReload.value = self.___caseReload_pressed self._casepath.changed_event = self.__casePathChanged #General tab. Here everythong most important to check self._dat_casename = ControlText('Name','') self._dat_run_type = ControlText('Run type','') self._dat_time_interval = ControlText('Time interval to run','') self._dat_number_of_steps = ControlText('Number of steps to run','') self._dom_nodal_points = ControlText('Number of points','') self._dom_elements = ControlText('Number of all elements','') self._dom_number_of_boundary_faces = ControlText('Number of boundary faces','') self._dom_mesh_numbers_verify_button = ControlButton('Verify') self._dom_types_of_elements = ControlText('Types of elements','') self._dom_domain_integration_points = ControlText('Number of integration points','') self._ker_density = ControlText('Density','') self._ker_viscosity = ControlText('Viscosity','') self._ker_steps_to_save = ControlText('Every how many steps to save','') self._nsi_boundary_conditions = ControlTextArea('Nastin boundary conditions') general_tab = [('_dat_casename','_dat_run_type'),('_dat_time_interval','_dat_number_of_steps'),\ ('_dom_nodal_points','_dom_elements','_dom_number_of_boundary_faces','_dom_mesh_numbers_verify_button'),\ ('_dom_types_of_elements','_dom_domain_integration_points'),\ ('_ker_density','_ker_viscosity'),\ '_ker_steps_to_save','_nsi_boundary_conditions'] #Raw casefile tab self._FileEditor = ControlTextArea('File editor') self._FileEditorSaveButton = ControlButton("Save file") self._DatPicker = ControlList('Dat files') self._DatPicker.horizontal_headers = ['Filename','Relative Path'] self._DatPicker.item_selection_changed_event = self.__DAT_selection_changed self._DatPicker.readonly = True self._IncludedFilePicker = ControlList('Included files') self._IncludedFilePicker.horizontal_headers = ['Filename','Section'] self._IncludedFilePicker.readonly = True self._IncludedFilePicker.item_selection_changed_event = self.__INCLUDE_selection_changed self.formset = [ ('_casepath','_casePathScan','||','_casename','_caseReload'),\ {'General': general_tab, \ 'Raw Casefile':[('_FileEditor','||','_DatPicker','||','_IncludedFilePicker'),\ '_FileEditorSaveButton']},'=','_log'] self._log.autoscroll = True self._log.readonly = True def ___fill_general_tab(self, params): self._dat_casename.value = params['alya'] self._dat_run_type.value = params['run_type'] self._dat_time_interval.value = params['time_interval'] self._dat_number_of_steps.value = params['number_of_steps'] self._dom_nodal_points.value = params['nodal_points'] self._dom_elements.value = params['elements'] self._dom_number_of_boundary_faces.value = params['boundaries'] self._dom_types_of_elements.value = params['types_of_elements'] self._dom_domain_integration_points.value = params['domain_integration_points'] self._ker_density.value = params['density'] self._ker_viscosity.value = params['viscosity'] self._ker_steps_to_save.value = params['steps'] self._nsi_boundary_conditions.value = params['nsi_boundary_conditions'] def ___caseReload_pressed(self): # # Reload the case # self.__addlog(f'Loading case {self._casename.value}') params = self._fileio.ExtractImportantParameters( self._casename.value ) self.__addlog(f'Loaded parameters {params}') self.___fill_general_tab(params) def ___casePathScan_pressed(self): # # Scan path for the cases, fill the listbox of cases # Not fully implmented. Does not support more than one case per path yet # self._fileio.SetCasePath(self._casepath._value) self.__addlog(f'Scanning {self._casepath._value} for cases') cases = self._fileio.ListCases() self.__addlog(f'Found the following cases {cases}') self._casename.clear() if cases!=[]: for case in cases: self._casename.add_item(case) self._casename.current_index = 0 self.___caseReload_pressed() dats = self._fileio.ListDats() self._DatPicker.clear() for dat in dats: self._DatPicker += [dat, '.'] def __casePathChanged(self): self.__addlog(f'Case path changed to: {self._casepath._value}') self.___casePathScan_pressed() return True def __addlog(self, string): self._log.__add__(f'{datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}: {string}') def __INCLUDE_selection_changed(self): # # Activated when user clicks on an INCLUDED file # selection = self._IncludedFilePicker.get_currentrow_value() print(selection[0]) data = self._fileio.ReadFullFile( selection[0] ) self._FileEditor.value = '' if data!=[]: self._FileEditor.value = ''.join(data) def __DAT_selection_changed(self): # # Activated when user clicks on a dat file # selection = self._DatPicker.get_currentrow_value() data = self._fileio.ReadFullFile( os.path.join(selection[1],selection[0]) ) includes = self._fileio.FindAllIncludedFiles(selection[0]) self.__addlog(f'Found {includes} included files') self._IncludedFilePicker.clear() if includes!=[]: for include in includes: self._IncludedFilePicker += [include[0], include[1]] self._FileEditor.value = '' if data!=[]: self._FileEditor.value = ''.join(data)
class TaskWindow(Task, BaseWidget): """ Define here which fields from the task model should appear on the details section. The model fields shall be defined as UI components like text fields, buttons, combo boxes, etc. You may also assign actions to these components. **Properties** name :class:`string` Name associated with this task. Returns the current value stored in the :py:attr:`_name` text field. **Private attributes** _name :class:`pyforms.controls.ControlText` Text field to edit task name. Editing this field fires the event :meth:`TaskWindow._TaskWindow__name_edited_evt`. _edit_btn :class:`pyforms.controls.ControlButton` Button to edit task code. Pressing the button fires the event :meth:`BoardWindow._BoardWindow__install_framework_btn_evt`. _formset Describe window fields organization to PyForms. **Methods** """ def __init__(self, project=None): BaseWidget.__init__(self, 'Task') self.layout().setContentsMargins(5, 10, 5, 5) self.precmdwin = None self.postcmdwin = None self._namefield = ControlText('Task name', changed_event=self.__name_edited_evt) self._use_server = ControlCheckBox('Trigger soft codes using a UDP port') self._precmds = ControlList( 'Pre commands', add_function=self.__add_pre_command, remove_function=self.__remove_pre_command, readonly=True ) self._postcmds = ControlList( 'Post commands', add_function=self.__add_post_command, remove_function=self.__remove_post_command, readonly=True ) self._formset = [ '_namefield', '_use_server', '_precmds', '_postcmds', ' ' ] Task.__init__(self, project) self.update_commands() def update_commands(self): self._precmds.clear() self._postcmds.clear() self._precommands_list = [] self._postcommands_list = [] for cmd in self.commands: if cmd.when == TaskCommand.WHEN_PRE: self._precmds += [str(cmd)] self._precommands_list.append(cmd) elif cmd.when == TaskCommand.WHEN_POST: self._postcmds += [str(cmd)] self._postcommands_list.append(cmd) def __add_pre_command(self): if self.precmdwin is not None: self.precmdwin.show() self.precmdwin.activateWindow() self.precmdwin.raise_() else: self.precmdwin = CommandEditor(self, when=TaskCommand.WHEN_PRE) self.precmdwin.show() def __remove_pre_command(self): row = self._precmds.selected_row_index if row is not None: obj = self._precommands_list.pop(row) self._commands.remove(obj) self._precmds -= -1 def __add_post_command(self): if self.postcmdwin is not None: self.postcmdwin.show() self.postcmdwin.activateWindow() self.postcmdwin.raise_() else: self.postcmdwin = CommandEditor(self, when=TaskCommand.WHEN_POST) self.postcmdwin.show() def __remove_post_command(self): row = self._postcmds.selected_row_index if row is not None: obj = self._postcommands_list.pop(row) self._commands.remove(obj) self._postcmds -= -1 def __use_server_changed_evt(self): self._netport.enabled = True if self._use_server.value else False def __name_edited_evt(self): """ React to changes on text field :py:attr:`_name`. This methods is called every time the user changes the field. """ if not hasattr(self, '_update_name') or not self._update_name: self.name = self._namefield.value @property def name(self): return Task.name.fget(self) @name.setter def name(self, value): try: Task.name.fset(self, value) except FileNotFoundError as e: self.critical(str(e), 'File not found') # Flag to avoid recurse calls when editing the name text field self._update_name = True self._namefield.value = value self._update_name = False @property def trigger_softcodes(self): return self._use_server.value @trigger_softcodes.setter def trigger_softcodes(self, value): self._use_server.value = (value is True) def load(self, path): super(TaskWindow, self).load(path) self.update_commands()
class AdminWidget(BaseWidget): def __init__(self, user=None, connection=None): BaseWidget.__init__(self) self._admin = user self._connection = connection self._add_user_button = ControlButton('New User') self._refresh_button = ControlButton('Refresh List') self._add_user_button.value= self.__add_User_btnAction self._refresh_button.value= self.__refresh self._userList = ControlList('Users',select_entire_row=True) self._userList.readonly=True self._userList.cell_double_clicked_event = self.__onSelect self._userList.horizontal_headers=['Admin', 'Name', 'Email'] self._userList.add_popup_menu_option('Toggle Admin Status', function_action=self.__admin_power) self._userList.add_popup_menu_option('Edit', function_action=self.__popEdit) if self._admin!=None and self._connection!=None: self.__retreive_users() def __refresh(self): self._userList.clear() self.__retreive_users() if self.parent!=None: self.parent.persist_login() def __retreive_users(self): try: self._user_pull= pull_users(self._admin, self._connection) except ValueError as err: err=ErrorWin(err) err.parent=self err.show() return if self._user_pull!=None: admins = self._connection['Database'].child('admins').shallow().get(self._admin['idToken']) for user in self._user_pull: check = False if user in admins.val(): check = True self._userList.__add__([check, self._user_pull[user]['name'], self._user_pull[user]['email']]) def __onSelect(self, row, column): if self.parent!=None: self.parent.persist_login() name = self._userList.get_value(1, row) email = self._userList.get_value(2, row) for i in self._user_pull: if self._user_pull[i]['email'] == email: uid = i try: services = self._user_pull[i]['services'] except: services = {"notifications" : False, "analysis": False, "newsletter" : False} win = UserWidget(self._admin, self._connection, 'edit', uid, email, name, services) win.parent = self win.show() def _refresh(self): self._userList.clear() self._user_pull= pull_users(self._admin, self._connection) if self._user_pull!=None: for user in self._user_pull: self._userList.__add__([self._user_pull[user]['name'], self._user_pull[user]['email']]) def __popEdit(self): row = self._userList.selected_row_index name = self._userList.get_value(1, row) email = self._userList.get_value(2, row) print(email) for i in self._user_pull: if self._user_pull[i]['email'] == email: uid = i try: services = self._user_pull[i]['services'] except: services = {"notifications" : False, "analysis": False, "newsletter" : False} win = UserWidget(self._admin, self._connection,'edit', uid, email, name, services) win.parent = self win.show() def __add_User_btnAction(self): if self.parent!=None: self.parent.persist_login() win = UserWidget(self._admin, self._connection, 'new') win.parent = self win.show() def _add_User(self, user): pass def _update_user(self, account): self._connection['Database'].child("users").child(account._uid).update({"name": account.name, "email": account.email, "services": account.services}) def __admin_power(self): if self.parent!=None: self.parent.persist_login() row = self._userList.selected_row_index email = self._userList.get_value(2, row) for i in self._user_pull: if self._user_pull[i]['email'] == email: self._selected_uid = i if self._selected_uid == self._admin['localId']: err = ErrorWin('Action not allowed - Cannot remove self as admin.') err.parent= self err.show() return if self._userList.get_value(0, row)== 'true':#already admin conf= ConfirmWin('Are you sure you want to remove this admin?', self._userList.get_value(1, row)) conf.parent = self conf.show() return else: conf= ConfirmWin('Are you sure you want to make this account admin?', self._userList.get_value(1, row)) conf.parent = self conf.show() return def _admin_toggle(self): toggle_admin(self._admin, self._connection, self._selected_uid) self._selected_uid='' self.__refresh()
class LibMaster(BaseWidget): def __init__(self, title='LibMaster'): super(LibMaster, self).__init__(title) self.debug = False #Import controls self._openImportFile = None self._openImportDir = None self._importPathText = ControlText() self._openFileButton = ControlButton('Open a file') self._openDirButton = ControlButton('Open a directory') self._importButton = ControlButton('Import') self._importTextArea = ControlTextArea() #Configure controls self._configCombo = ControlCombo('Library') self._configNameText = ControlText('Loop name') self._configPageNumber = ControlNumber('Start page', default=1, min=1, max=20000) self._configDict = {} self._configList = ControlList('Application Plan', add_function=self.__buttonAction_Add, remove_function=self.__buttonAction_Del) self._configLoadButton = ControlButton('Load') self._configAddButton = ControlButton('Add') self._configDelButton = ControlButton('Delete') self._configClearButton = ControlButton('Clear') self._configSaveButton = ControlButton('Save') self._configGenButton = ControlButton('Generate') self._configTextArea = ControlTextArea() #Combine controls self._openDBFile = ControlFileOpen('Choose the database file: ', opened_file_type='txt') self._openArgFile = ControlFileOpen('Choose the argument file: ', opened_file_type='xlsx') self._combineButton = ControlButton('Combine') self._combineTextArea = ControlTextArea() #setup all controls self.formset = [{ ' 1. Import ': [ '', ('', '_importPathText', ''), ('', '_openFileButton', '', '_openDirButton', ''), (' ', '_importButton', ' '), '', ('', '_importTextArea', ''), '' ], ' 2. Configure ': [ '', ('', '_configCombo', '', '_configNameText', '', '_configPageNumber', ''), ('', '_configList', ''), ('', '_configAddButton', '', '_configDelButton', '', '_configClearButton', ''), ('', '_configLoadButton', '', '_configSaveButton', '', '_configGenButton', ''), '', ('', '_configTextArea', ''), '' ], ' 3. Combine ': [ '', ('', '_openDBFile', ''), ('', '_openArgFile', ''), (' ', '_combineButton', ' '), '', ('', '_combineTextArea', ''), '' ] }] #Button Actions self._openFileButton.value = self.__buttonAction_OpenFile self._openDirButton.value = self.__buttonAction_OpenDir self._importButton.value = self.__buttonAction_Import self._configLoadButton.value = self.__buttonAction_Load self._configAddButton.value = self.__buttonAction_Add self._configDelButton.value = self.__buttonAction_Del self._configClearButton.value = self.__buttonAction_Clear self._configSaveButton.value = self.__buttonAction_Save self._configGenButton.value = self.__buttonAction_Gen self._combineButton.value = self.__buttonAction_Combine #set all text area to read only self._importTextArea.readonly = True self._configTextArea.readonly = True self._combineTextArea.readonly = True #Combo box lists correct library files in './Library' directory self._configCombo += 'Select library' if not os.path.exists('Library'): os.mkdir('Library') else: file_lst = os.listdir('Library') for file in file_lst: if file[-4:] == '.txt' and (file[:-4] + '.xlsx') in file_lst: self._configCombo += file[:-4] else: pass #set configuration list property headers = [] headers.append(' ' * 10 + 'Library' + ' ' * 10) headers.append(' ' * 10 + 'Loop Name' + ' ' * 10) headers.append(' Start Page ') headers.append(' End Page ') self._configList.horizontal_headers = headers self._configList.select_entire_row = True self._configList.readonly = True def __buttonAction_OpenFile(self): try: self._openImportFile = ControlFileOpen('Choose library file:', opened_file_type='txt') self._openImportFile.click() self._importPathText.value = self._openImportFile.value except Exception as err: self._importTextArea.__add__('Open file error: ' + repr(err)) if self.debug: self._importTextArea.__add__(traceback.format_exc()) def __buttonAction_OpenDir(self): try: self._openImportDir = ControlDir('Choose directory:') self._openImportDir.click() self._importPathText.value = self._openImportDir.value except Exception as err: self._importTextArea.__add__('Open file error: ' + repr(err)) if self.debug: self._importTextArea.__add__(traceback.format_exc()) def __buttonAction_Import(self): try: #import a file, using main import function from 'Import.py' if self._openImportFile is not None and self._openImportFile.value == self._importPathText.value: addedFiles = Import([self._openImportFile.value], self._importTextArea.__add__) self._importTextArea.__add__( 'Import finish. Libraries are exported under \'./Library\' directory.' ) for add_file in addedFiles: self._configCombo += addedFiles[0][:-4] #import a directory, find valid files in directory before calling Import elif self._openImportDir is not None and self._openImportDir.value == self._importPathText.value: files = [] dirs = os.listdir(self._openImportDir.value) for file in dirs: if file[-4:] == '.txt': files.append(self._openImportDir.value + '/' + file) else: pass if len(files) > 0: addedFiles = Import(files, self._importTextArea.__add__) self._importTextArea.__add__( 'Import finish. Libraries are exported under \'./Library\' directory.' ) for add_file in addedFiles: self._configCombo += add_file[:-4] else: self._importTextArea.__add__( 'No valid file in the directory.') #no file selected else: self._importTextArea.__add__('No file or directory selected.') except Exception as err: self._importTextArea.__add__('Error: ' + repr(err)) if self.debug: self._importTextArea.__add__(traceback.format_exc()) def __helper_Add2Dict(self, lst): combo, name, pageNum = lst[0], lst[1], int(lst[2]) if name in self._configDict.values(): raise Exception('Loop name conflict.') else: pass wb = load_workbook('./Library/' + combo + '.xlsx') ws = wb['Info'] for row in list(ws.rows): if row[0].value == 'Page count': pageCount = row[1].value else: pass for i in range(pageCount): if pageNum + i in self._configDict: raise Exception('Page conflict.') else: pass lst[3] = pageNum + pageCount - 1 for i in range(pageCount): self._configDict[pageNum + i] = name def __buttonAction_Load(self): try: self._loadConfigFile = ControlFileOpen(opened_file_type='json') self._loadConfigFile.click() if self._loadConfigFile.value != '': with open(self._loadConfigFile.value, 'r') as f: jstr = json.load(f) table = jstr['value'] self._configDict.clear() for row in table: self.__helper_Add2Dict(row) self._configList.load_form(jstr, None) else: raise Exception('No file selected.') self._configTextArea.__add__('List loaded from ' + self._loadConfigFile.value) except Exception as err: self._configTextArea.__add__('\'Load\' error: ' + repr(err)) if self.debug: self._configTextArea.__add__(traceback.format_exc()) def __buttonAction_Add(self): try: nameText = '__' + self._configCombo.text if self._configNameText.value == '' else self._configNameText.value lst = [ self._configCombo.text, nameText, self._configPageNumber.value, 0 ] self.__helper_Add2Dict(lst) self._configList.__add__(lst) self._configList.resizecolumns = False except Exception as err: self._configTextArea.__add__('\'Add\' error: ' + repr(err)) if self.debug: self._configTextArea.__add__(traceback.format_exc()) def __buttonAction_Del(self): try: if self._configList.selected_row_index is None: raise Exception('No row selected.') for i in range(int(self._configList.get_currentrow_value()[2]), int(self._configList.get_currentrow_value()[3]) + 1): del self._configDict[i] self._configList.__sub__(self._configList.selected_row_index) except Exception as err: self._configTextArea.__add__('\'Delete\' error: ' + repr(err)) if self.debug: self._configTextArea.__add__(traceback.format_exc()) def __buttonAction_Clear(self): try: self._configDict.clear() self._configList.clear() except Exception as err: self._configTextArea.__add__('\'Clear\' error: ' + repr(err)) if self.debug: self._configTextArea.__add__(traceback.format_exc()) def __buttonAction_Save(self): try: self._saveConfigFile = ControlFileSave(saved_file_type='json') self._saveConfigFile.click() if self._saveConfigFile.value != '': with open(self._saveConfigFile.value, 'w') as f: json.dump(self._configList.save_form({}, None), f) else: raise Exception('File not specified.') self._configTextArea.__add__('List saved to ' + self._saveConfigFile.value) except Exception as err: self._configTextArea.__add__('\'Save\' error: ' + repr(err)) if self.debug: self._configTextArea.__add__(traceback.format_exc()) def __buttonAction_Gen(self): try: table = self._configList.value for i in range(len(table)): table[i][0] += '.txt' table.insert(0, ['Library', 'Loop Name', 'Start Page', 'End Page']) self._saveArgFile = ControlFileSave(saved_file_type='xlsx') self._saveArgFile.click() Config(table, self._saveArgFile.value) self._configTextArea.__add__('Arguments file is generated.') self._openArgFile.value = self._saveArgFile.value except Exception as err: self._configTextArea.__add__('\'Generate\' error: ' + repr(err)) if self.debug: self._configTextArea.__add__(traceback.format_exc()) def __buttonAction_Combine(self): try: self._saveDPUFile = ControlFileSave(saved_file_type='txt') self._saveDPUFile.click() Combine(self._openDBFile.value, self._saveDPUFile.value, self._openArgFile.value) self._combineTextArea.__add__('New DPU file is generated.') except Exception as err: self._combineTextArea.__add__('Error: ' + repr(err)) if self.debug: self._combineTextArea.__add__(traceback.format_exc())
class AlyaGUI(BaseWidget): def __init__(self): super(AlyaGUI, self).__init__('Alya Case Editor') #Layer for IO handling self._fileio = AlyaFileIO() self._log = ControlTextArea('Log') self._fileio.SetLogControl(self.__addlog) #Main form fields self._casepath = ControlDir('Case path', default='/home/costa/Downloads/1111') self._fileio.SetCasePath(self._casepath._value) self._casename = ControlCombo('Case') self._casePathScan = ControlButton('Scan Path') self._casePathScan.value = self.___casePathScan_pressed self._caseReload = ControlButton('Load Case') self._caseReload.value = self.___caseReload_pressed self._casepath.changed_event = self.__casePathChanged #General tab. Here everythong most important to check self._dat_casename = ControlText('Name', '') self._dat_run_type = ControlText('Run type', '') self._dat_time_interval = ControlText('Time interval to run', '') self._dat_number_of_steps = ControlText('Number of steps to run', '') self._dom_nodal_points = ControlText('Number of points', '') self._dom_elements = ControlText('Number of all elements', '') self._dom_number_of_boundary_faces = ControlText( 'Number of boundary faces', '') self._dom_mesh_numbers_verify_button = ControlButton('Verify') self._dom_types_of_elements = ControlText('Types of elements', '') self._dom_domain_integration_points = ControlText( 'Number of integration points', '') self._ker_density = ControlText('Density', '') self._ker_viscosity = ControlText('Viscosity', '') self._ker_steps_to_save = ControlText('Every how many steps to save', '') self._nsi_boundary_conditions = ControlTextArea( 'Nastin boundary conditions') general_tab = [('_dat_casename','_dat_run_type'),('_dat_time_interval','_dat_number_of_steps'),\ ('_dom_nodal_points','_dom_elements','_dom_number_of_boundary_faces','_dom_mesh_numbers_verify_button'),\ ('_dom_types_of_elements','_dom_domain_integration_points'),\ ('_ker_density','_ker_viscosity'),\ '_ker_steps_to_save','_nsi_boundary_conditions'] #Raw casefile tab self._FileEditor = ControlTextArea('File editor') self._FileEditorSaveButton = ControlButton("Save file") self._DatPicker = ControlList('Dat files') self._DatPicker.horizontal_headers = ['Filename', 'Relative Path'] self._DatPicker.item_selection_changed_event = self.__DAT_selection_changed self._DatPicker.readonly = True self._IncludedFilePicker = ControlList('Included files') self._IncludedFilePicker.horizontal_headers = ['Filename', 'Section'] self._IncludedFilePicker.readonly = True self._IncludedFilePicker.item_selection_changed_event = self.__INCLUDE_selection_changed self.formset = [ ('_casepath','_casePathScan','||','_casename','_caseReload'),\ {'General': general_tab, \ 'Raw Casefile':[('_FileEditor','||','_DatPicker','||','_IncludedFilePicker'),\ '_FileEditorSaveButton']},'=','_log'] self._log.autoscroll = True self._log.readonly = True def ___fill_general_tab(self, params): self._dat_casename.value = params['alya'] self._dat_run_type.value = params['run_type'] self._dat_time_interval.value = params['time_interval'] self._dat_number_of_steps.value = params['number_of_steps'] self._dom_nodal_points.value = params['nodal_points'] self._dom_elements.value = params['elements'] self._dom_number_of_boundary_faces.value = params['boundaries'] self._dom_types_of_elements.value = params['types_of_elements'] self._dom_domain_integration_points.value = params[ 'domain_integration_points'] self._ker_density.value = params['density'] self._ker_viscosity.value = params['viscosity'] self._ker_steps_to_save.value = params['steps'] self._nsi_boundary_conditions.value = params['nsi_boundary_conditions'] def ___caseReload_pressed(self): # # Reload the case # self.__addlog(f'Loading case {self._casename.value}') params = self._fileio.ExtractImportantParameters(self._casename.value) self.__addlog(f'Loaded parameters {params}') self.___fill_general_tab(params) def ___casePathScan_pressed(self): # # Scan path for the cases, fill the listbox of cases # Not fully implmented. Does not support more than one case per path yet # self._fileio.SetCasePath(self._casepath._value) self.__addlog(f'Scanning {self._casepath._value} for cases') cases = self._fileio.ListCases() self.__addlog(f'Found the following cases {cases}') self._casename.clear() if cases != []: for case in cases: self._casename.add_item(case) self._casename.current_index = 0 self.___caseReload_pressed() dats = self._fileio.ListDats() self._DatPicker.clear() for dat in dats: self._DatPicker += [dat, '.'] def __casePathChanged(self): self.__addlog(f'Case path changed to: {self._casepath._value}') self.___casePathScan_pressed() return True def __addlog(self, string): self._log.__add__( f'{datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}: {string}' ) def __INCLUDE_selection_changed(self): # # Activated when user clicks on an INCLUDED file # selection = self._IncludedFilePicker.get_currentrow_value() print(selection[0]) data = self._fileio.ReadFullFile(selection[0]) self._FileEditor.value = '' if data != []: self._FileEditor.value = ''.join(data) def __DAT_selection_changed(self): # # Activated when user clicks on a dat file # selection = self._DatPicker.get_currentrow_value() data = self._fileio.ReadFullFile( os.path.join(selection[1], selection[0])) includes = self._fileio.FindAllIncludedFiles(selection[0]) self.__addlog(f'Found {includes} included files') self._IncludedFilePicker.clear() if includes != []: for include in includes: self._IncludedFilePicker += [include[0], include[1]] self._FileEditor.value = '' if data != []: self._FileEditor.value = ''.join(data)