def write(self, message, loggerName='log', logLevel='debug', showErrorDialog=True): message = str(message).strip() if message != '': logLevel = logLevel.lower() myLogger = logging.getLogger(loggerName) if logLevel == 'debug': myLogger.debug(message) elif logLevel == 'info': myLogger.info(message) self.rtobjectWrite(message) elif logLevel == 'warning': myLogger.warning(message) self.rtobjectWrite(message) elif logLevel == 'error': myLogger.error(message) self.rtobjectWrite(message) if showErrorDialog: MessageDialog('Error', message, Gtk.MessageType.ERROR, self.parent).show() elif logLevel == 'critical': myLogger.critical(message) self.rtobjectWrite(message) if showErrorDialog: MessageDialog('Critical', message, Gtk.MessageType.ERROR, self.parent).show() elif logLevel == 'exception': myLogger.exception(message) self.rtobjectWrite(message) if showErrorDialog: MessageDialog('Exception', message, Gtk.MessageType.ERROR, self.parent).show()
def onShowStats(self): stats = self.data.get_stats() stats_str = "" for key, val in stats: key = '_'.join(key) if type(key) is list else key stats_str += f"{key} = {val}\n" dlg = MessageDialog('Label stats', stats_str) dlg.exec_()
def launchSaveChanges(self): if not self.changesSaved: saveDialog = MessageDialog( 'Not saved changes!', 'Some labeled images were not saved, do you want to save the changes?' ) if saveDialog.exec_(): # save csv self.data.save()
def add_reservation(self, reservation=None): if not self.database.get_resources(): self.error = MessageDialog("Please add atleast one resource.") self.error.show() elif not self.database.get_services(): self.error = MessageDialog("Please add atleast one service.") self.error.show() else: self.reservation_dialog = ReservationDialog( self, reservation=reservation) self.reservation_dialog.show()
def on_start_button(self, start_button): handler.send_message(event=handler.EVENT_CHECK_STATUS) if not Globals.icabthread.isAlive(): dlg = MessageDialog() dlg.message_label.text = "Bot Thread is dead something went wrong!!" dlg.open() if start_button.text == "Start": show_toast("Scanning Started", 2) start_button.text = "Stop" else: show_toast("Scanning Stopped", 2) start_button.text = "Start"
def on_radUnneeded_toggled(self, widget): if widget.get_active(): message = _("You might need to run this several times.\n\n%s" % self.lblMaintenanceHelp.get_label().replace("\n", " ")) MessageDialog(self.btnMaintenance.get_label(), message, Gtk.MessageType.WARNING, self.window) self.fillTreeViewMaintenance()
def on_radDowngradable_toggled(self, widget): if widget.get_active(): message = _("Downgrading packages may break your system!\n\n%s" % self.lblMaintenanceHelp.get_label().replace("\n", " ")) MessageDialog(self.btnMaintenance.get_label(), message, Gtk.MessageType.WARNING, self.window) self.fillTreeViewMaintenance()
def handleHardware(self, actionString): hwSelected = False selHw = [] selHwString = '' chkList = functions.getColumnValues(self.tvHardware, 0) statList = functions.getColumnValues(self.tvHardware, 5) hwList = functions.getColumnValues(self.tvHardware, 4) for i in range(len(chkList)): if chkList[i]: self.log.write(actionString + ' hardware code: ' + hwList[i], 'ddm.handleHardware', 'info') selHw.append([hwList[i], statList[i]]) hwSelected = True if hwSelected: # Install selected drivers self.toggleGuiElements(True) # Start saving in a separate thread self.log.write('Start driver ' + actionString + ' thread', 'ddm.handleHardware', 'info') if actionString == 'install': t = DriverInstall(selHw, self.log) else: t = DriverRemove(selHw, self.log) t.start() # Run spinner as long as the thread is alive self.log.write('Check every 5 seconds if thread is still active', 'ddm.installHardware', 'debug') glib.timeout_add(5, self.checkThread, actionString) else: msg = 'Select a driver to install.' MessageDialog('Driver install', msg, gtk.MESSAGE_INFO, self.window.get_icon()).show()
def saveGeneralSettings(self): lst = [] for tab in self.umglobal.settings["hide-tabs"]: if tab != "maintenance": lst.append(tab) if self.chkHideMaintenance.get_active(): lst.append("maintenance") if lst: self.umglobal.saveSettings('misc', 'hide-tabs', ",".join(lst)) else: self.umglobal.saveSettings('misc', 'hide-tabs', "") # Automatically start updatemanager on boot autostart = self.chkAutostart.get_active() self.umglobal.settings["autostart"] = autostart if autostart: if exists(self.umglobal.autostartSourceFile) and \ exists(self.umglobal.autostartDir): copy(self.umglobal.autostartSourceFile, self.umglobal.autostartDir) elif exists(self.umglobal.autostartDestFile): remove(self.umglobal.autostartDestFile) msg = _("The new settings will take effect after UM restart.") MessageDialog(self.lblGeneral.get_label(), msg)
def fill_treeview_ddm(self): # Fill a list with supported hardware self.get_supported_hardware() # columns: checkbox, image (logo), device, driver columnTypes = ['bool', 'GdkPixbuf.Pixbuf', 'str'] # Keep some info from the user showHw = [] for hw in self.hardware: showHw.append([hw[0], hw[1], hw[2]]) # Fill treeview self.tvDDMHandler.fillTreeview(contentList=showHw, columnTypesList=columnTypes, firstItemIsColName=True, fontSize=12000) # Show message if nothing is found or hardware is not supported title = _("Hardware scan") if self.notSupported: if len(self.hardware) < 2: self.set_buttons_state(False) msg = _("There are no available drivers for your hardware:") msg = "{}\n\n{}".format(msg, '\n'.join(self.notSupported)) self.log.write(msg, 'fill_treeview_ddm') WarningDialog(title, msg) elif len(self.hardware) < 2: self.set_buttons_state(False) msg = _("DDM did not find any supported hardware.") self.log.write(msg, 'fill_treeview_ddm') MessageDialog(title, msg)
def on_radOldKernel_toggled(self, widget): if widget.get_active(): message = _( "Once removed you will not be able to boot these kernels!\n\n%s" % self.lblMaintenanceHelp.get_label().replace("\n", " ")) MessageDialog(self.btnMaintenance.get_label(), message, Gtk.MessageType.WARNING, self.window) self.fillTreeViewMaintenance()
def quit_tray(self, widget): if self.umglobal.isUpgrading(): MessageDialog(self.quitText, _("Cannot quit: upgrade in progress")) else: self.umglobal.killScriptProcess("updatemanager.py") self.umglobal.killScriptProcess("updatemanagerpref.py") self.notifier.quit() Gtk.main_quit()
def show_message(self, cmdOutput): try: self.log.write("Command output: {}".format(cmdOutput), 'show_message') ret = int(cmdOutput) if ret > 1 and ret != 255: if ret == 1: ErrorDialog( self.btnExecute.get_label(), _("Run this application with root permission.")) elif ret == 2: ErrorDialog( self.btnExecute.get_label(), _("Wrong arguments were passed to usb-creator.")) elif ret == 3: ErrorDialog( self.btnExecute.get_label(), _("The device was not found or no device was given.")) elif ret == 4: ErrorDialog(self.btnExecute.get_label(), _("Given ISO path was not found.")) elif ret == 5: ErrorDialog(self.btnExecute.get_label(), _("Device is in use by another application.")) elif ret == 6: ErrorDialog(self.btnExecute.get_label(), _("Unable to mount the device.")) elif ret == 7: ErrorDialog(self.btnExecute.get_label(), _("Hash mismatch.")) elif ret == 8: ErrorDialog(self.btnExecute.get_label(), _("The device has no fat32 partition.")) elif ret == 9: ErrorDialog(self.btnExecute.get_label(), _("The device has no bootloader installed.")) elif ret == 10: ErrorDialog( self.btnExecute.get_label(), _("There is not enough space available on the device.") ) elif ret == 11: ErrorDialog( self.btnExecute.get_label(), _("Unable to guess distribution from ISO name.\n" "Make sure you have the distribution name in the ISO name." )) else: msg = _( "An unknown error accured.\n" "Please, visit our forum for support: http://forums.solydxk.com" ) ErrorDialog(self.window.get_title(), msg) else: msg = _("The USB was successfully written.") MessageDialog(self.window.get_title(), msg) except: ErrorDialog(self.btnExecute.get_label(), cmdOutput)
def on_btnUnmount_clicked(self, widget): unmount_text = _("Unmount") device = self.device["path"] self.unmount_device(device) self.on_btnRefresh_clicked() if device in self.devices: msg = _("Could not unmount the device.\n" "Please unmount the device manually.") else: msg = _("You can now safely remove the device.") MessageDialog(unmount_text, msg)
def onCreateCsv(self, s): main_folder = str( QFileDialog.getExistingDirectory(self, "Choose dataset directory")) # if there is no folder, do nothing if not os.path.isdir(main_folder): return False optDialog = CsvNameDialog() # get desired filename and if images are organized from user if optDialog.exec_() == CsvNameDialog.Accepted: filename, have_labels = optDialog.getValues() else: # if cancel, do nothing return False # reset if was labeling if self.isLabeling: self.stopLabeling() # initialize data handler self.data = DataHandler(os.path.join(main_folder, filename)) self.data.create(have_labels) if len(self.data) > 0: message = "{} images found, save to file?".format(len(self.data)) title = "Images found" else: message = "No image were found!" title = "No images in folder" dlg = MessageDialog(title, message) if dlg.exec_(): # save csv self.data.save() # start labeling self.startLabeling() else: self.data = None
def on_btnUnmount_clicked(self, widget): unmount_text = _("Unmount") device = self.device["path"] try: self.udisks2.unmount_drive(device) self.on_btnRefresh_clicked() msg = _("You can now safely remove the device.") except Exception as e: msg = _("Could not unmount the device.\n" "Please unmount the device manually.") self.log.write("ERROR: %s" % str(e)) MessageDialog(unmount_text, msg)
def refresh(self): # Refresh server info print((self.umglobal.hasInternet)) self.umglobal.getServerInfo() print((self.umglobal.hasInternet)) # Check of programs locking apt prog = self.apt.getAptCacheLockedProgram( self.umglobal.settings["apt-packages"]) if prog is not None: msg = _("Another program is locking the apt cache\n\n" "Please, close the program before refreshing:\n" "* %s" % prog) MessageDialog(self.btnRefresh.get_label(), msg) self.log.write("%s is locking the apt cache" % prog, "UM.refresh", "warning") elif self.umglobal.hasInternet: if not self.quickUpdate: # Update the apt cache self.btnPreferences.set_sensitive(True) self.btnOutput.set_sensitive(True) self.btnRefresh.set_sensitive(False) self.btnInstall.set_sensitive(False) self.btnMaintenance.set_sensitive(False) self.btnPackages.set_sensitive(True) self.showOutput() cmd = "dpkg --configure -a; %s -f install; apt-get update" % self.umglobal.settings[ 'apt-get-string'] nid = 'umrefresh' self.prepForCommand(nid) if self.quickUpdate: self.ec.run(cmd) else: self.terminal.executeCommand(cmd, nid) self.apt.initAptShowVersions() self.log.write("Execute command: %s (%s)" % (cmd, nid), "UM.refresh", "debug") else: if not self.quickUpdate: # No internet connection self.btnInstall.set_sensitive(True) self.btnRefresh.set_sensitive(True) self.btnPackages.set_sensitive(True) self.btnMaintenance.set_sensitive(True) self.btnInfo.set_sensitive(True) self.btnOutput.set_sensitive(True) self.btnPreferences.set_sensitive(True) self.loadInfo() self.showInfo()
def show_message(self, cmdOutput): try: self.log.write("Command output: {}".format(cmdOutput), 'show_message') ret = int(cmdOutput) if ret > 1 and ret != 255: if ret == 1: ErrorDialog(self.btnSave.get_label(), _("Run as root.")) elif ret == 2: ErrorDialog(self.btnSave.get_label(), _("Wrong arguments passed to ddm.")) elif ret == 3: ErrorDialog(self.btnSave.get_label(), _("There are no driver available.")) elif ret == 4: ErrorDialog(self.btnSave.get_label(), _("The driver cannot be found in repository.")) elif ret == 5: ErrorDialog( self.btnSave.get_label(), _("Download error.\nCheck your internet connection.")) elif ret == 6: ErrorDialog(self.btnSave.get_label(), _("DDM cannot purge the driver.")) elif ret == 7: ErrorDialog(self.btnSave.get_label(), _("This card is not supported.")) else: msg = _( "There was an error during the installation.\n" "Please, run 'sudo apt-get -f install' in a terminal.\n" "Visit our forum for support: http://forums.solydxk.com" ) ErrorDialog(self.btnSave.get_label(), msg) else: msg = _("The software has been successfully installed.") msg_restart = _("You will need to restart your system.") MessageDialog(self.btnSave.get_label(), "{}\n\n{}".format(msg, msg_restart)) except: ErrorDialog(self.btnSave.get_label(), cmdOutput)
def showInfoDlg(self, title, message): MessageDialog(title, message, parent=self.window)
def saveSettings(self): self.log.write("Save settings...", 'conky.saveSettings', 'info') # Reset colors self.dayClockColor = self.dayClockColorDefault self.dateTitleColor = self.dateTitleColorDefault self.systemInfoColor = self.systemInfoColorDefault # Kill Conky, and remove all files self.removeConky() # conkyrc if exists(self.conkyrc_template): if not exists(self.conkyrc): self.log.write("Copy %(template)s to %(conkyrc)s" % {"template": self.conkyrc_template, "conkyrc" :self.conkyrc}, 'conky.saveSettings', 'debug') shutil.copy2(self.conkyrc_template, self.conkyrc) functions.chownCurUsr(self.conkyrc) else: self.log.write("Conkyrc template not found %(template)s" % {"template": self.conkyrc_template}, 'conky.saveSettings', 'error') # lua if exists(self.lua_template): if not exists(self.lua): if not exists(self.luaDir): os.makedirs(self.luaDir) self.log.write("Copy %(template)s to %(lua)s" % {"template": self.lua_template, "lua" :self.lua}, 'conky.saveSettings', 'debug') shutil.copy2(self.lua_template, self.lua) functions.chownCurUsr(self.lua) else: self.log.write("Lua template not found %(template)s" % {"template": self.lua_template}, 'conky.saveSettings', 'error') # start script template = join(self.scriptDir, 'cfg/conky-start') if os.path.exists(template): if not exists(self.conkyStart): self.log.write("Copy %(template)s to %(conkyStart)s" % {"template": template, "conkyStart" :self.conkyStart}, 'conky.saveSettings', 'debug') shutil.copy2(template, self.conkyStart) else: self.log.write("Start script not found %(template)s" % {"template": template}, 'conky.saveSettings', 'error') # Download and upload speed dl = self.txtNetwDownSpeed.get_text() functions.replaceStringInFile('\[DSPEED\]', str(dl), self.lua) self.log.write("Save download speed: %(dl)s" % {'dl': dl}, 'conky.saveSettings', 'debug') ul = self.txtNetwUpSpeed.get_text() functions.replaceStringInFile('\[USPEED\]', str(ul), self.lua) self.log.write("Save upload speed: %(ul)s" % {'ul': ul}, 'conky.saveSettings', 'debug') # Get selecte temperature unit, and get sensor data accordingly tempUnit = self.getActiveComboValue(self.cmbSysTempUnit)[1][0:1].lower() tempUnitStr = '°C' if tempUnit == 'c': # Celsius self.log.write("Temperature unit: Celsius", 'conky.saveSettings', 'debug') sensorsCommand = 'sensors' else: # Fahrenheit self.log.write("Temperature unit: Fahrenheit", 'conky.saveSettings', 'debug') tempUnitStr = '°F' sensorsCommand = 'sensors -f' sensors = self.ec.run(sensorsCommand, False, False) # Localization functions.replaceStringInFile('\[CPU\]', _("CPU"), self.conkyrc) functions.replaceStringInFile('\[RAM\]', _("RAM"), self.conkyrc) functions.replaceStringInFile('\[DISK\]', _("Disk"), self.conkyrc) functions.replaceStringInFile('\[NET\]', _("Net"), self.conkyrc) # Core temperature if self.chkSysCores.get_active(): self.commandCore = self.commandCore.replace('[TEMPUNIT]', tempUnitStr) self.commandCore = self.commandCore.replace("[CORELABEL]", self.corelbl) self.commandCore = self.commandCore.replace("[SENSORSTR]", sensorsCommand) functions.replaceStringInFile('#\s*\[CORE\]', self.commandCore, self.conkyrc) self.log.write("Core command added", 'conky.saveSettings', 'debug') # CPU fan speed if self.chkSysCpuFan.get_active(): cpufan = functions.findRegExpInString('cpu\s{0,}fan.*\:', sensors) self.log.write("Cpu fan value = %(cpufan)s" % {'cpufan' :str(cpufan)}, 'conky.saveSettings', 'debug') if cpufan: self.commandCpu = self.commandCpu.replace("[CPULABEL]", self.cpulbl) self.commandCpu = self.commandCpu.replace('[CPUSTR]', cpufan) functions.replaceStringInFile('#\s*\[CPUFAN\]', self.commandCpu, self.conkyrc) # Chassis fan speed if self.chkSysChassisFan.get_active(): chafan = functions.findRegExpInString('chassis\s{0,}fan.*\:', sensors) self.log.write("Chassis fan value = %(chafan)s" % {'chafan' :str(chafan)}, 'conky.saveSettings', 'debug') if chafan: self.commandChassis = self.commandChassis.replace("[CHASSISLABEL]", self.chassislbl) self.commandChassis = self.commandChassis.replace('[CHASTR]', chafan) functions.replaceStringInFile('#\s*\[CHAFAN\]', self.commandChassis, self.conkyrc) # HD temperature unit if self.chkSysHd.get_active(): self.log.write("Add HDD temperature to .conkyrc", 'conky.saveSettings', 'debug') self.commandHdd = self.commandHdd.replace('[TEMPUNIT]', tempUnitStr) self.commandHdd = self.commandHdd.replace('[HDLABEL]', self.hdlbl) hddCommand = 'hddtemp -n' if tempUnit == 'f': hddCommand = 'hddtemp -n -u f' self.commandHdd = self.commandHdd.replace('[HDDSTR]', hddCommand) functions.replaceStringInFile('#\s*\[HDDTEMP\]', self.commandHdd, self.conkyrc) # LAN IP if self.chkNetwLanIP.get_active(): self.log.write("Add LAN IP to .conkyrc", 'conky.saveSettings', 'debug') self.commandLanIp = self.commandLanIp.replace("[LANLABEL]", self.lanlbl) functions.replaceStringInFile('#\s*\[LANIP\]', self.commandLanIp, self.conkyrc) # IP if self.chkNetwIP.get_active(): self.log.write("Add IP to .conkyrc", 'conky.saveSettings', 'debug') self.commandIp = self.commandIp.replace("[IPLABEL]", self.iplbl) functions.replaceStringInFile('#\s*\[IP\]', self.commandIp, self.conkyrc) # Kernel if self.chkSysKernel.get_active(): self.log.write("Add Kernel to .conkyrc", 'conky.saveSettings', 'debug') self.commandKernel = self.commandKernel.replace("[KERNELLABEL]", self.kernellbl) functions.replaceStringInFile('#\s*\[KERNEL\]', self.commandKernel, self.conkyrc) # Conky desktop alignment alignment = self.getActiveComboValue(self.cmbPrefAlign) self.log.write("Conky alignment = %(alignment)s" % {'alignment': alignment[1]}, 'conky.saveSettings', 'debug') if alignment[0] > 0: functions.replaceStringInFile('alignment\s+tr', 'alignment tl', self.conkyrc) # Write sleep before conky start sleepNr = functions.strToNumber(self.getActiveComboValue(self.cmbPrefSleep)[1], True) self.log.write("Conky sleep before start = %(sleep)d seconds" % {'sleep': sleepNr}, 'conky.saveSettings', 'debug') if sleepNr != 20: functions.replaceStringInFile('20', str(sleepNr), self.conkyStart) # Network interface eth = self.txtNetwInterface.get_text() self.log.write("Save network interface: %(interface)s" % {'interface': eth}, 'conky.saveSettings', 'debug') functions.replaceStringInFile('\[ETH\]', eth, self.conkyrc) functions.replaceStringInFile('\[ETH\]', eth, self.lua) # Write colors if self.dayClockColorNew == self.dayClockColor: self.dayClockColorNew = None if self.dateTitleColorNew == self.dateTitleColor: self.dateTitleColorNew = None if self.systemInfoColorNew == self.systemInfoColor: self.systemInfoColorNew = None if self.dateTitleColorNew is not None: functions.replaceStringInFile(self.dateTitleColor, self.dateTitleColorNew, self.conkyrc) self.log.write("Replace Date and Title color %s with %s" % (self.dateTitleColor, self.dateTitleColorNew), 'conky.saveSettings', 'info') self.dateTitleColor = self.dateTitleColorNew if self.dayClockColorNew is not None: functions.replaceStringInFile(self.dayClockColor, self.dayClockColorNew, self.conkyrc) functions.replaceStringInFile(self.dayClockColor, self.dayClockColorNew, self.lua) self.log.write("Replace Day and Clock color %s with %s" % (self.dayClockColor, self.dayClockColorNew), 'conky.saveSettings', 'info') self.dayClockColor = self.dayClockColorNew if self.systemInfoColorNew is not None: functions.replaceStringInFile(self.systemInfoColor, self.systemInfoColorNew, self.conkyrc) functions.replaceStringInFile(self.systemInfoColor, self.systemInfoColorNew, self.lua) self.log.write("Replace System Info color %s with %s" % (self.systemInfoColor, self.systemInfoColorNew), 'conky.saveSettings', 'info') self.systemInfoColor = self.systemInfoColorNew # Automatically start Conky when the user logs in if self.chkPrefAutostart.get_active() and not exists(self.desktop): self.log.write("Write autostart file: %(desktop)s" % {'desktop': self.desktop}, 'conky.saveSettings', 'debug') if not exists(self.autostartDir): os.makedirs(self.autostartDir) desktopCont = '[Desktop Entry]\nComment=SolydXK Conky\nExec=[CONKYSTART]\nIcon=/usr/share/solydxk/logo.png\nStartupNotify=true\nTerminal=false\nType=Application\nName=SolydXK Conky\nGenericName=SolydXK Conky' f = open(self.desktop, 'w') f.write(desktopCont.replace('[CONKYSTART]', self.conkyStart)) f.close() functions.makeExecutable(self.desktop) msg = "SolydXK Conky configuration has finished.\n\nWill now start Conky with the new configuration." MessageDialog(self.window.get_title(), msg) self.log.write("Save settings done", 'conky.saveSettings', 'info') # Restart Conky functions.makeExecutable(self.conkyStart) self.startConky()
def saveMirrors(self): # Safe mirror settings replaceRepos = [] # Get user selected mirrors model = self.tvMirrors.get_model() itr = model.get_iter_first() while itr is not None: sel = model.get_value(itr, 0) if sel: repo = model.get_value(itr, 2) url = model.get_value(itr, 3) not_changed = '' # Get currently selected data for mirror in self.mirrors: if mirror[0] and mirror[2] == repo: if mirror[3] != url: # Currently selected mirror replaceRepos.append([mirror[3], url]) else: not_changed = url break if url not in replaceRepos and url not in not_changed: # Append the repositoriy to the sources file replaceRepos.append(['', url]) itr = model.iter_next(itr) if not replaceRepos: # Check for dead mirrors model = self.tvMirrors.get_model() itr = model.get_iter_first() while itr is not None: sel = model.get_value(itr, 0) if sel: repo = model.get_value(itr, 2) url = model.get_value(itr, 3) # Get currently selected data for mirror in self.deadMirrors: if mirror[1] == repo and mirror[2] != url: # Currently selected mirror replaceRepos.append([mirror[2], url]) break itr = model.iter_next(itr) if replaceRepos: self.btnSaveMirrors.set_sensitive(False) self.btnCheckMirrorsSpeed.set_sensitive(False) m = Mirror() ret = m.save(replaceRepos, self.excludeMirrors) if ret == '': self.ec.run(cmd="apt-get update", outputTreeView=self.tvMirrors) self.umglobal.getLocalInfo() self.mirrors = self.getMirrors() self.fillTreeViewMirrors() else: self.log.write(ret, "UMPref.saveMirrors", "exception") self.btnSaveMirrors.set_sensitive(True) self.btnCheckMirrorsSpeed.set_sensitive(True) else: msg = _("There are no repositories to save.") MessageDialog(self.lblMirrors.get_label(), msg)
def fillTreeViewMaintenance(self): blnCleanCache = self.radCleanCache.get_active() blnUnneeded = self.radUnneeded.get_active() blnDowngradable = self.radDowngradable.get_active() blnNotavailable = self.radNotavailable.get_active() blnOldKernels = self.radOldKernel.get_active() self.enableMaintenance(False) columnTypesList = ['bool', 'str', 'str', 'str'] packages = [["", _("Package"), _("Installed"), _("Available")]] # Clear the treeview first self.tvMaintenanceHandler.fillTreeview(packages, columnTypesList, 0, 400, True) msg = "" if blnCleanCache: msg = _("Hit the Execute button to clean the cache.") columnTypesList = ['str'] packages.append([msg]) elif blnUnneeded: msg = self.radUnneeded.get_label() self.apt.createPackageLists("apt-get autoremove") for pck in self.apt.removedPackages: packages.append([False, pck[0], pck[1], pck[2]]) self.apt.createPackageLists() # Add orphaned files self.apt.fillOrphanedPackages() for pck in self.apt.orphanedPackages: packages.append([False, pck[0], pck[1], pck[2]]) elif blnNotavailable: msg = self.radNotavailable.get_label() self.apt.fillNotAvailablePackages() for pck in self.apt.notavailablePackages: if pck[0][0:6] != "linux-": packages.append([False, pck[0], pck[1], ""]) elif blnOldKernels: msg = self.radOldKernel.get_label() self.apt.fillKernelPackages() for pck in self.apt.kernelPackages: if "headers-486" not in pck[0] \ and "headers-586" not in pck[0] \ and "headers-686" not in pck[0] \ and "headers-amd64" not in pck[0] \ and "image-486" not in pck[0] \ and "image-586" not in pck[0] \ and "image-686" not in pck[0] \ and "image-amd64" not in pck[0]: checkVersion = self.kernelVersion if "kbuild" in pck[0]: indMinus = self.kernelVersion.index("-") indZero = self.kernelVersion.index("0") if indZero > 0 and indZero < indMinus: ind = indZero - 1 else: ind = indMinus if ind > 0: checkVersion = self.kernelVersion[0:ind] if checkVersion not in pck[0]: packages.append([False, pck[0], pck[1], ""]) elif blnDowngradable: msg = self.radDowngradable.get_label() self.apt.fillDowngradablePackages() for pck in self.apt.downgradablePackages: packages.append([False, pck[0], pck[1], pck[2]]) if len(packages) > 1: self.tvMaintenanceHandler.fillTreeview(packages, columnTypesList, 0, 400, True) else: if not blnCleanCache: msg = _("\"%s\"\n did not return any results.") % msg MessageDialog(self.btnMaintenance.get_label(), msg) self.enableMaintenance(True)
def run_upgrade(self): nid = "" aptHasErrors = self.apt.aptHasErrors() if aptHasErrors is not None: MessageDialog(self.aptErrorText, aptHasErrors) elif self.upgradables: if self.apt.upgradablePackages: self.log.write( "=================== upgradable pacages ====================", "UM.run_upgrade", "debug") self.log.write( self.createLogString(self.apt.upgradablePackages), "UM.run_upgrade", "debug") if self.apt.removedPackages: self.log.write( "==================== removed packages =====================", "UM.run_upgrade", "debug") self.log.write(self.createLogString(self.apt.removedPackages), "UM.run_upgrade", "debug") if self.apt.newPackages: self.log.write( "======================= new packages =======================", "UM.run_upgrade", "debug") self.log.write(self.createLogString(self.apt.newPackages), "UM.run_upgrade", "debug") if self.apt.heldbackPackages: self.log.write( "=================== kept back packages =====================", "UM.run_upgrade", "debug") self.log.write(self.createLogString(self.apt.heldbackPackages), "UM.run_upgrade", "debug") if not self.quickUpdate: self.showOutput() contMsg = _("Continue installation?") if self.upgradableUM: cmd = "%s install updatemanager" % self.umglobal.settings[ 'apt-get-string'] cmd += "; %s install %s" % ( self.umglobal.settings['apt-get-string'], " ".join( self.apt.getPackageDependencies('updatemanager'))) nid = 'uminstallum' self.prepForCommand(nid) if self.quickUpdate: self.ec.run(cmd) else: self.terminal.executeCommand(cmd, nid) self.log.write("Execute command: %s (%s)" % (cmd, nid), "UM.on_btnInstall_clicked", "debug") else: msg = self.getDistUpgradeInfo() answer = True if msg != "": answer = self.showConfirmationDlg(contMsg, msg) if answer: cmd = "%s dist-upgrade" % self.umglobal.settings[ 'apt-get-string'] #if self.umglobal.newUpd: pre = join( self.umglobal.filesDir, self.umglobal.settings['pre-upd'].replace( "[VERSION]", self.umglobal.serverUpdVersion)) post = join( self.umglobal.filesDir, self.umglobal.settings['post-upd'].replace( "[VERSION]", self.umglobal.serverUpdVersion)) if exists(pre): cmd = "/bin/bash %(pre)s; %(cmd)s" % { "pre": pre, "cmd": cmd } if exists(post): cmd = "%(cmd)s; /bin/bash %(post)s" % { "cmd": cmd, "post": post } nid = 'umupd' self.prepForCommand(nid) if self.quickUpdate: self.ec.run(cmd) else: self.terminal.executeCommand(cmd, nid) self.log.write("Execute command: %s (%s)" % (cmd, nid), "UM.on_btnInstall_clicked", "debug") else: if not self.quickUpdate: MessageDialog(self.btnInstall.get_label(), self.uptodateText) return nid
def showInfo(self, title, message, parent): MessageDialog(title, message, parent=parent)
class GUI(QtWidgets.QMainWindow): ''' The class GUI handles the drawing of a RobotWorld and allows user to interact with it. ''' def __init__(self, database): super().__init__() self.screen = QtWidgets.QDesktopWidget().screenGeometry() self.database = database self.setCentralWidget(QtWidgets.QWidget( )) # QMainWindown must have a centralWidget to be able to add layouts self.horizontal = QtWidgets.QHBoxLayout() # Horizontal main layout self.centralWidget().setLayout(self.horizontal) self.init_window() self.init_buttons() self.add_reservation_view() def init_buttons(self): ''' Adds buttons to the window and connects them to their respective functions See: QPushButton at http://doc.qt.io/qt-5/qpushbutton.html ''' self.buttons = QtWidgets.QGroupBox() layout = QtWidgets.QVBoxLayout() self.buttons.setLayout(layout) self.reservation = QtWidgets.QPushButton("Add reservation") self.reservation.clicked.connect(self.add_reservation) layout.addWidget(self.reservation) self.reservation_manage = QtWidgets.QPushButton("Manage reservations") self.reservation_manage.clicked.connect(self.manage_reservations) layout.addWidget(self.reservation_manage) self.resource_manage = QtWidgets.QPushButton("Manage resources") self.resource_manage.clicked.connect(self.manage_resources) layout.addWidget(self.resource_manage) self.service_manage = QtWidgets.QPushButton("Manage services") self.service_manage.clicked.connect(self.manage_services) layout.addWidget(self.service_manage) self.customer_manage = QtWidgets.QPushButton("Manage customers") self.customer_manage.clicked.connect(self.manage_customers) layout.addWidget(self.customer_manage) self.calendar = MyCalendar(self.database) self.calendar.selectionChanged.connect(self.add_reservation_view) layout.addWidget(self.calendar) layout.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignRight) self.buttons.setMaximumWidth(self.screen.width() * 0.2) self.horizontal.addWidget(self.buttons) def init_window(self): ''' Sets up the window. ''' self.setGeometry(self.screen) self.setWindowTitle('Varausjärjestelmä') self.show() # Add a scene for drawing 2d objects self.scene = QtWidgets.QGraphicsScene() # Add a view for showing the scene self.view = MyView(self.scene, self) self.view.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft) self.view.show() self.horizontal.addWidget(self.view) def draw_hour_lines(self, width, height, offset, number_of_lines): for i in range(number_of_lines): line = QtWidgets.QGraphicsLineItem(0, i * height + offset, width, i * height + offset) self.scene.addItem(line) def add_reservation_view(self): self.scene.clear() date = self.calendar.selectedDate() reservations = self.database.get_reservations(date=date) if reservations: self.view.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft) (start, end) = self.database.get_start_and_end(date) number_of_lines = end - start resources = self.database.resources.get_all() offset = 30 width = (self.screen.width() - offset) / 5 height = self.screen.height() / 5 hours = HourRowGraphicsItem(offset - 15, height * number_of_lines, offset, start, end) headers = ColumnHeaderGraphicsItem(width * len(resources), offset - 5, resources, offset) self.draw_hour_lines(width * len(resources) + 30, height, offset, number_of_lines) for reservation in reservations: item = ReservationGraphicsItem(self, self.database, reservation, width, height, offset, date, start) self.scene.addItem(item) self.scene.addItem(hours) self.scene.addItem(headers) else: self.view.setAlignment(QtCore.Qt.AlignCenter) text = QtWidgets.QGraphicsSimpleTextItem( "No reservations for selected date") self.scene.addItem(text) self.scene.setSceneRect(self.scene.itemsBoundingRect()) def add_reservation(self, reservation=None): if not self.database.get_resources(): self.error = MessageDialog("Please add atleast one resource.") self.error.show() elif not self.database.get_services(): self.error = MessageDialog("Please add atleast one service.") self.error.show() else: self.reservation_dialog = ReservationDialog( self, reservation=reservation) self.reservation_dialog.show() def manage_reservations(self): self.reservation_manage_dialog = ReservationManageDialog(self) self.reservation_manage_dialog.show() def manage_resources(self): self.resource_manage_dialog = ResourceManageDialog(self) self.resource_manage_dialog.show() def manage_services(self): self.service_manage_dialog = ServiceManageDialog(self) self.service_manage_dialog.show() def manage_customers(self): self.customer_manage_dialog = CustomerManageDialog(self) self.customer_manage_dialog.show() def update(self): self.add_reservation_view()
def on_release(self): handler.send_message(event=handler.EVENT_MESSAGE, id=self.id) Globals.message_dialog = MessageDialog() Globals.message_dialog.open()
def executeMaintenance(self): blnCleanCache = self.radCleanCache.get_active() blnDowngradable = self.radDowngradable.get_active() blnNotNeeded = self.radUnneeded.get_active() downgradeString = "" deleteString = "" updateGrub = False cmd = "" self.enableMaintenance(False) if blnCleanCache: safe = False msg = _( "Do you want to completely clean the apt cache?\n\n" "When No, only unavailable installation packages are removed.") answer = QuestionDialog(self.radCleanCache.get_label(), msg) if answer: safe = True self.apt.cleanCache(safe) msg = _("Apt cache has been cleaned.") MessageDialog(self.radCleanCache.get_label(), msg) else: # Get user selected packages model = self.tvMaintenance.get_model() itr = model.get_iter_first() while itr is not None: sel = model.get_value(itr, 0) if sel: pck = model.get_value(itr, 1) avVer = model.get_value(itr, 3) if blnDowngradable: downgradeString += " %(pck)s=%(avVer)s" % { "pck": pck, "avVer": avVer } else: deleteString += " %s" % pck if "linux-image" in pck: updateGrub = True itr = model.iter_next(itr) if downgradeString != "": cmd = "%s install %s" % ( self.umglobal.settings['apt-get-string'], downgradeString) elif deleteString != "": cmd = "%s purge %s" % ( self.umglobal.settings['apt-get-string'], deleteString) if cmd != "": self.apt.createPackageLists(cmd) msg = self.getDistUpgradeInfo() answer = True if msg != "": contMsg = _("Execute maintenance changes?") answer = self.showConfirmationDlg(contMsg, msg) if answer: if updateGrub: cmd += "; update-grub" if blnNotNeeded: cmd += "; %s purge $(COLUMNS=132 dpkg -l | grep ^rc | awk '{ print $2 }')" % self.umglobal.settings[ 'apt-get-string'] self.showOutput() nid = 'ummaintenance' self.prepForCommand(nid) self.terminal.executeCommand(cmd, nid) self.log.write("Execute command: %s (%s)" % (cmd, nid), "UM.executeMaintenance", "debug") self.enableMaintenance(True)
def on_command_done(self, terminal, pid, nid): if nid != "init": self.log.write("Command finished (pid=%s, nid=%s)" % (pid, nid), "UM.on_command_done", "info") if nid == "uminstallum": # Reload UM self.log.write( "Updating UM: kill process of updatemanagerpref.py", "UM.on_command_done", "debug") self.umglobal.killScriptProcess("updatemanagerpref.py") # Reload tray as user self.log.write( "Updating UM: kill process of updatemanagertray.py", "UM.on_command_done", "debug") self.umglobal.killScriptProcess("updatemanagertray.py") cmd = "sudo -u {} updatemanager -t -r".format(self.user) os.system(cmd) self.log.write( "UM updated: reload tray as user {}".format(self.user), "UM.on_command_done", "debug") # Reload UM window cmd = join(self.umglobal.scriptDir, "updatemanager.py") if self.quickUpdate: cmd = join(self.umglobal.scriptDir, "updatemanager.py -q") self.umglobal.reloadWindow(cmd, self.user) self.log.write( "UM updated: reload {0} as user {1}".format( cmd, self.user), "UM.on_command_done", "debug") elif nid == "umrefresh": # Build installed packages info list self.apt.createPackagesInfoList() # Run post update when needed self.postUpdate() elif nid == "ummaintenance": self.enableMaintenance(True) self.fillTreeViewMaintenance() self.btnInstall.set_sensitive(True) self.btnRefresh.set_sensitive(True) self.btnPackages.set_sensitive(True) self.btnMaintenance.set_sensitive(True) self.showMaintenance() elif nid == 'umupd': # Save update version in hist file self.umglobal.saveHistVersion("upd", self.umglobal.serverUpdVersion) self.log.write( "Save history upd=%s" % self.umglobal.serverUpdVersion, "UM.on_command_done", "debug") self.deleteScripts() # Refresh data after install or update self.umglobal.collectData() self.apt.createPackageLists() self.fillTreeView() # Enable the buttons and load the info page self.log.write( "Re-initiate window after terminal command: %s" % str(not self.quickUpdate), "UM.on_command_done", "debug") if not self.quickUpdate: self.btnInstall.set_sensitive(True) self.btnRefresh.set_sensitive(True) self.btnPackages.set_sensitive(True) self.btnMaintenance.set_sensitive(True) self.btnInfo.set_sensitive(True) self.loadInfo() if self.umglobal.newUpd: self.showInfo() else: # This throws a lock file error in Plasma5 #aptHasErrors = self.apt.aptHasErrors() #if aptHasErrors is not None: #MessageDialog(self.aptErrorText, aptHasErrors) #el if self.upgradables: self.showPackages() else: self.showInfo() MessageDialog(self.btnInfo.get_label(), self.uptodateText) self.log.write("Re-initiate window complete", "UM.on_command_done", "debug") # Cleanup name file(s) for fle in glob(join(self.umglobal.filesDir, '.um*')): remove(fle)
def showInfoDlg(self, title, message): MessageDialog(title, message)
def isRunningLive(): if force: return False liveDirs = ['/live', '/lib/live/mount', '/rofs'] for ld in liveDirs: if os.path.exists(ld): return True return False # Do not run in live environment if isRunningLive(): msg = _("Device Driver Manager cannot be started in a live environment\n" "You can use the --force argument to start DDM in a live environment") MessageDialog(title, msg, None, None, True, 'ddm') sys.exit() def uncaught_excepthook(*args): sys.__excepthook__(*args) if __debug__: from pprint import pprint from types import BuiltinFunctionType, ClassType, ModuleType, TypeType tb = sys.last_traceback while tb.tb_next: tb = tb.tb_next print(('\nDumping locals() ...')) pprint({k:v for k,v in tb.tb_frame.f_locals.items() if not k.startswith('_') and not isinstance(v, (BuiltinFunctionType, ClassType, ModuleType, TypeType))})