def run(self): # Edit the casper.conf # Strangely enough, casper uses the "quiet" flag if the build system is either Debian or Ubuntu if config.VStatus is False: logger.logI(self.tn, _("Editing casper and LSB configuration files")) logger.logV(self.tn, _("Editing casper.conf")) buildsys = "Ubuntu" if configutils.parseBoolean(configutils.getValue(configs[configutils.casperquiet])) is False: buildsys = "" unionfs = configutils.getValue(configs[configutils.unionfs]) if unionfs == "overlayfs" and aptutil.compVersions(aptutil.getPkgVersion(aptutil.getPkg("casper", aptcache)), "1.272", aptutil.lt): logger.logW(self.tn, _("Using DEFAULT instead of overlayfs")) unionfs = "DEFAULT" self.varEditor(tmpsys + "etc/casper.conf", { "USERNAME": configutils.getValue(configs[configutils.username]), "USERFULLNAME": configutils.getValue(configs[configutils.userfullname]), "HOST": configutils.getValue(configs[configutils.host]), "BUILD_SYSTEM": buildsys, "FLAVOUR": configutils.getValue(configs[configutils.flavour]), "UNIONFS": unionfs}) logger.logV(self.tn, _("Editing lsb-release")) self.varEditor(tmpsys + "etc/lsb-release", { "DISTRIB_ID": configutils.getValue(configs[configutils.sysname]), "DISTRIB_RELEASE": configutils.getValue(configs[configutils.version]), "DISTRIB_CODENAME": configutils.getValue(configs[configutils.codename]), "DISTRIB_DESCRIPTION": configutils.getValue(configs[configutils.description])})
def runthread(self): logger.logV(self.tn, logger.I, _("Copying ISOLINUX to the ISO tree")) copyFile("/usr/lib/syslinux/isolinux.bin", isotreel + "isolinux/", self.tn, True) self.setProgress(self.tn, 20) copyFile("/usr/lib/syslinux/vesamenu.c32", isotreel + "isolinux/", self.tn, True) self.setProgress(self.tn, 40) logger.logVV( self.tn, logger.I, _("Copying isolinux.cfg to the ISO tree")) copyFile(configutils.getValue(configs[configutils.isolinuxfile]), isotreel + "isolinux/isolinux.cfg", self.tn, True) self.setProgress(self.tn, 50) # Edit the isolinux.cfg file to replace the variables logger.logV(self.tn, logger.I, _("Editing isolinux.cfg")) splash = os.path.basename( configutils.getValue(configs[configutils.splash])) shutil.copy2(configutils.getValue(configs[configutils.splash]), isotreel + "isolinux/" + splash) self.setProgress(self.tn, 70) for i in [["LABEL", configutils.getValue(configs[configutils.label])], ["SPLASH", splash], ["TIMEOUT", configutils.getValue(configs[configutils.timeout])]]: fsutil.ife( fsutil.ife_getbuffers(isotreel + "isolinux/isolinux.cfg"), lambda line: [True, re.sub("\$" + i[0], i[1], line)])
def run(self): logger.logI(tn, _("Generating compressed filesystem")) # Generate the SquashFS file # Options: # -b 1M Use a 1M blocksize (maximum) # -no-recovery No recovery files # -always-use-fragments Fragment blocks for files larger than the blocksize (1M) # -comp Compression type logger.logVV(tn, _("Generating options")) opts = "-b 1M -no-recovery -no-duplicates -always-use-fragments" opts = opts + " -comp " + configutils.getValue(configs[configutils.sfscomp]) opts = opts + " " + configutils.getValue(configs[configutils.sfsopts]) sfsex = "dev etc home media mnt proc sys var usr/lib/ubiquity/apt-setup/generators/40cdrom" sfspath = isotreel + "casper/filesystem.squashfs" logger.logI(tn, _("Adding the edited /etc and /var to the filesystem")) os.system("mksquashfs " + tmpsys + " " + sfspath + " " + opts) logger.logI(tn, _("Adding the rest of the system")) os.system("mksquashfs / " + sfspath + " " + opts + " -e " + sfsex) # Make sure the SquashFS file is OK doSFSChecks(sfspath, int(configutils.getValue(configs[configutils.isolevel]))) # Find the size after it is uncompressed logger.logV(tn, _("Writing the size")) files = open(isotreel + "casper/filesystem.size", "w") files.write(fsutil.getSFSInstSize(sfspath) + "\n") files.close()
def runthread(self): # Generate the package manifest logger.logV(self.tn, logger.I, _("Generating package manifests")) logger.logVV(self.tn, logger.I, _( "Generating filesystem.manifest and filesystem.manifest-desktop")) writer = open(isotreel + "casper/filesystem.manifest", "w") writer_desktop = open( isotreel + "casper/filesystem.manifest-desktop", "w") for i in config.AptCache: if i.installedVersion is None or len(i.installedVersion) <= 0: continue name = i.fullname.strip() ver = i.installedVersion.strip() strs = name + " " + ver + "\n" writer.write(strs) if (not name in configutils.getValue(configs[configutils.remafterinst])): writer_desktop.write(strs) writer.close() writer_desktop.close() logger.logVV( self.tn, logger.I, _("Generating filesytem.manifest-remove")) writer = open(isotreel + "casper/filesystem.manifest-remove", "w") for i in configutils.parseMultipleValues(configutils.getValue(configs[configutils.remafterinst])): writer.write(i.strip() + "\n") writer.close()
def runthread(self): # Generate the package manifest logger.logV(self.tn, logger.I, _("Generating package manifests")) logger.logVV(self.tn, logger.I, _( "Generating filesystem.manifest and filesystem.manifest-desktop")) writer = open(isotreel + "casper/filesystem.manifest", "w") writer_desktop = open( isotreel + "casper/filesystem.manifest-desktop", "w") # installedVersion throws an error when it doesn't exist in 'Package' # TODO: figure out why, but for now.. check for attribute as well for i in config.AptCache: if not hasattr(i,'installedVersion') or i.installedVersion is None or len(i.installedVersion) <= 0: continue name = i.fullname.strip() ver = i.installedVersion.strip() strs = name + " " + ver + "\n" writer.write(strs) if (not name in configutils.getValue(configs[configutils.remafterinst])): writer_desktop.write(strs) writer.close() writer_desktop.close() logger.logVV( self.tn, logger.I, _("Generating filesytem.manifest-remove")) writer = open(isotreel + "casper/filesystem.manifest-remove", "w") for i in configutils.parseMultipleValues(configutils.getValue(configs[configutils.remafterinst])): writer.write(i.strip() + "\n") writer.close()
def runthread(self): # Edit the casper.conf # Strangely enough, casper uses the "quiet" flag if the build system is either Debian or Ubuntu if config.VStatus is False: logger.logI(self.tn, logger.I, _("Editing casper and LSB configuration files")) logger.logV(self.tn, logger.I, _("Editing casper.conf")) buildsys = "Ubuntu" if configutils.parseBoolean( configutils.getValue( configs[configutils.casperquiet])) is False: buildsys = "" unionfs = configutils.getValue(configs[configutils.unionfs]) if unionfs == "overlayfs" and aptutil.compVersions( aptutil.getPkgVersion(aptutil.getPkg("casper", aptcache)), "1.272", aptutil.lt): logger.logI(self.tn, logger.W, _("Using DEFAULT instead of overlayfs")) unionfs = "DEFAULT" self.varEditor( tmpsys + "etc/casper.conf", { "USERNAME": configutils.getValue(configs[configutils.username]), "USERFULLNAME": configutils.getValue(configs[configutils.userfullname]), "HOST": configutils.getValue(configs[configutils.host]), "BUILD_SYSTEM": buildsys, "FLAVOUR": configutils.getValue(configs[configutils.flavour]), "UNIONFS": unionfs }) logger.logI(self.tn, logger.I, _("Applying permissions to casper scripts")) # Make sure the casper scripts work cbs = "/usr/share/initramfs-tools/scripts/casper-bottom/" for i in fsutil.listdir(cbs): fsutil.chmod(i, 0o755, self.tn) logger.logV(self.tn, logger.I, _("Editing lsb-release")) self.varEditor( tmpsys + "etc/lsb-release", { "DISTRIB_ID": configutils.getValue(configs[configutils.sysname]), "DISTRIB_RELEASE": configutils.getValue(configs[configutils.sysversion]), "DISTRIB_CODENAME": configutils.getValue(configs[configutils.codename]), "DISTRIB_DESCRIPTION": configutils.getValue(configs[configutils.description]) })
def run(self): if configutils.parseBoolean(configutils.getValue(configs[configutils.enablewubi])) is True: logger.logV(self.tn, _("Generating the windows autorun.inf")) files = open(isotreel + "autorun.inf", "w") files.write("[autorun]\n") files.write("open=wubi.exe\n") files.write("icon=wubi.exe,0\n") files.write("label=Install " + configutils.getValue(configs[configutils.sysname]) + "\n") files.write("\n") files.write("[Content]\n") files.write("MusicFiles=false\n") files.write("PictureFiles=false\n") files.write("VideoFiles=false\n") files.close()
def run(self): logger.logV(self.tn, _("Copying ISOLINUX to the ISO tree")) copyFile("/usr/lib/syslinux/isolinux.bin", isotreel + "isolinux/", True) copyFile("/usr/lib/syslinux/vesamenu.c32", isotreel + "isolinux/", True) logger.logVV(self.tn, _("Copying isolinux.cfg to the ISO tree")) copyFile(configutils.getValue(configs[configutils.isolinuxfile], isotreel + "isolinux/isolinux.cfg", True)) # Edit the isolinux.cfg file to replace the variables logger.logV(_("Editing isolinux.cfg")) for i in [["LABEL", configutils.getValue(configs[configutils.label])], ["SPLASH", configutils.getValue(configs[configutils.splash])], ["TIMEOUT", configutils.getValue(configs[configutils.timeout])]]: fsutil.ife(fsutil.ife_getbuffers(isotreel + "isolinux/isolinux.cfg"), lambda line: re.sub("\$" + i[0], i[1], line))
def runthread(self): if configutils.parseBoolean(configutils.getValue(configs[configutils.enablewubi])) is True: logger.logV(self.tn, logger.I, _("Generating the windows autorun.inf")) files = open(isotreel + "autorun.inf", "w") files.write("[autorun]\n") files.write("open=wubi.exe\n") files.write("icon=wubi.exe,0\n") files.write("label=Install " + configutils.getValue(configs[configutils.sysname]) + "\n") files.write("\n") files.write("[Content]\n") files.write("MusicFiles=false\n") files.write("PictureFiles=false\n") files.write("VideoFiles=false\n") files.close()
def runthread(self): logger.logI(self.tn, logger.I, _( "Making the ISO compatible with a USB burner")) logger.logVV(self.tn, logger.I, _("Writing .disk/info")) files = open(isotreel + ".disk/info", "w") files.write(getDiskName() + "\n") files.close() self.setProgress(self.tn, 20) logger.logV(self.tn, logger.I, _( "Making symlink pointing to the ISO root dir")) if os.path.lexists(isotreel + "ubuntu"): fsutil.rm(isotreel + "ubuntu", False, self.tn) os.symlink(isotreel, isotreel + "ubuntu") self.setProgress(self.tn, 40) logger.logVV(self.tn, logger.I, _("Writing release notes URL")) files = open(isotreel + ".disk/release_notes_url", "w") files.write(configutils.getValue(configs[configutils.url]) + "\n") files.close() self.setProgress(self.tn, 60) logger.logVV(self.tn, logger.I, _("Writing .disk/base_installable")) fsutil.touch(isotreel + ".disk/base_installable") self.setProgress(self.tn, 80) logger.logVV(self.tn, logger.I, _("Writing CD Type")) files = open(isotreel + ".disk/cd_type", "w") files.write("full_cd/single\n") files.close()
def runthread(self): logger.logV( self.tn, logger.I, _("Copying preseed files to the ISO tree")) for i in fsutil.listdir(configutils.getValue(configs[configutils.preseed])): logger.logVV(self.tn, logger.I, _("Copying") + " " + i + " " + _("to the ISO tree")) copyFile(i, isotreel + "preseed/", self.tn)
def runthread(self): # If the user-setup-apply file does not exist, and there is an alternative, we'll copy it over logger.logI(self.tn, logger.I, _("Setting up the installer")) if (os.path.isfile( "/usr/lib/ubiquity/user-setup/user-setup-apply.orig") and not os.path.isfile( "/usr/lib/ubiquity/user-setup/user-setup-apply")): shutil.copy2("/usr/lib/ubiquity/user-setup/user-setup-apply.orig", "/usr/lib/ubiquity/user-setup/user-setup-apply") # If the user requested to make sure that the installer does _not_ change the apt sources, # make sure that relinux obeys this. # However, if the user changed his/her mind, we want to make sure that relinux # work with that too if not configutils.getValue(configs[configutils.aptlistchange]): if not os.path.exists( "/usr/share/ubiquity/apt-setup.relinux-backup"): os.rename("/usr/share/ubiquity/apt-setup", "/usr/share/ubiquity/apt-setup.relinux-backup") aptsetup = open("/usr/share/ubiquity/apt-setup", "w") aptsetup.write("\n") aptsetup.close() fsutil.chmod("/usr/share/ubiquity/apt-setup", 0o755, self.tn) elif os.path.exists("/usr/share/ubiquity/apt-setup.relinux-backup"): # TODO: Fix the 40cdrom bug? fsutil.rm("/usr/share/ubiquity/apt-setup", False, self.tn) os.rename("/usr/share/ubiquity/apt-setup.relinux-backup", "/usr/share/ubiquity/apt-setup")
def onWrite(msg): if not configutils.getValue(config.Configuration["Relinux"]["EXPERIMENTFEATURES"]): return ui.terminal.moveCursor(QtGui.QTextCursor.End, QtGui.QTextCursor.MoveAnchor) QtCore.QMetaObject.invokeMethod( ui.terminal, "insertPlainText", QtCore.Qt.QueuedConnection, QtCore.Q_ARG("QString", msg.rstrip() + "\n") )
def runthread(self): logger.logI(self.tn, logger.I, _("Copying files to the temporary filesystem")) excludes = configutils.parseMultipleValues(configutils.getValue(configs[configutils.excludes])) varexcludes = excludes # Exclude all log files (*.log *.log.*), PID files (to show that no daemons are running), # backup and old files (for obvious reasons), and any .deb files that a person might have downloaded varexcludes.extend(["*.log", "*.log.*", "*.pid", "*/pid", "*.bak", "*.[0-9].gz", "*.deb"]) fsutil.fscopy("/etc", tmpsys + "etc", excludes, self.tn) fsutil.fscopy("/var", tmpsys + "var", varexcludes, self.tn)
def onWrite(msg): if not configutils.getValue( config.Configuration["Relinux"]["EXPERIMENTFEATURES"]): return ui.terminal.moveCursor(QtGui.QTextCursor.End, QtGui.QTextCursor.MoveAnchor) QtCore.QMetaObject.invokeMethod( ui.terminal, "insertPlainText", QtCore.Qt.QueuedConnection, QtCore.Q_ARG("QString", msg.rstrip() + "\n"))
def runthread(self): if configutils.getValue(configs[configutils.enablewubi]) is True: logger.logV( self.tn, logger.I, _("Generating the windows autorun.inf")) files = open(isotreel + "autorun.inf", "w") files.write("[autorun]\n") files.write("open=wubi.exe\n") files.write("icon=wubi.exe,0\n") files.write("label=Install " + configutils.getValue( configs[configutils.sysname]) + "\n") files.write("\n") files.write("[Content]\n") files.write("MusicFiles=false\n") files.write("PictureFiles=false\n") files.write("VideoFiles=false\n") files.close() self.setProgress(self.tn, 50) logger.logV(self.tn, logger.I, _("Copying WUBI to the ISO tree")) copyFile(config.relinuxdir + "/wubi.exe", isotreel + "wubi.exe", self.tn)
def runthread(self): # Edit the casper.conf # Strangely enough, casper uses the "quiet" flag if the build system is either Debian or Ubuntu if config.VStatus is False: logger.logI(self.tn, logger.I, _("Editing casper and LSB configuration files")) logger.logV(self.tn, logger.I, _("Editing casper.conf")) buildsys = "Ubuntu" if configutils.parseBoolean(configutils.getValue(configs[configutils.casperquiet])) is False: buildsys = "" unionfs = configutils.getValue(configs[configutils.unionfs]) if unionfs == "overlayfs" and aptutil.compVersions( aptutil.getPkgVersion(aptutil.getPkg("casper", aptcache)), "1.272", aptutil.lt ): logger.logI(self.tn, logger.W, _("Using DEFAULT instead of overlayfs")) unionfs = "DEFAULT" self.varEditor( tmpsys + "etc/casper.conf", { "USERNAME": configutils.getValue(configs[configutils.username]), "USERFULLNAME": configutils.getValue(configs[configutils.userfullname]), "HOST": configutils.getValue(configs[configutils.host]), "BUILD_SYSTEM": buildsys, "FLAVOUR": configutils.getValue(configs[configutils.flavour]), "UNIONFS": unionfs, }, ) logger.logI(self.tn, logger.I, _("Applying permissions to casper scripts")) # Make sure the casper scripts work cbs = "/usr/share/initramfs-tools/scripts/casper-bottom/" for i in fsutil.listdir(cbs): fsutil.chmod(i, 0o755, self.tn) logger.logV(self.tn, logger.I, _("Editing lsb-release")) self.varEditor( tmpsys + "etc/lsb-release", { "DISTRIB_ID": configutils.getValue(configs[configutils.sysname]), "DISTRIB_RELEASE": configutils.getValue(configs[configutils.sysversion]), "DISTRIB_CODENAME": configutils.getValue(configs[configutils.codename]), "DISTRIB_DESCRIPTION": configutils.getValue(configs[configutils.description]), }, )
def runthread(self): self.event = threading.Event() self.ap = aptutil.AcquireProgress(lambda p: self.percentfunc(p / 2)) self.ip = aptutil.InstallProgress( lambda p: self.percentfunc(50 + p / 2), lambda: self.finishfunc(self.event)) logger.logI(self.tn, logger.I, _("Setting up distro dependencies")) logger.logV(self.tn, logger.I, _("Setting up Ubiquity")) if configutils.getValue(configs[configutils.instfront]).lower() == "kde": self.instPkg("ubiquity-frontend-kde", True) self.remPkg("ubiquity-frontend-gtk") else: self.instPkg("ubiquity-frontend-gtk", True) self.remPkg("ubiquity-frontend-kde") logger.logV(self.tn, logger.I, _("Setting up Popularity Contest")) if configutils.getValue(configs[configutils.popcon]): self.instPkg("popularity-contest") else: self.remPkg("popularity-contest") if configutils.getValue(configs[configutils.memtest]): logger.logV(self.tn, logger.I, _("Setting up memtest86+")) self.instPkg("memtest86+") logger.logV( self.tn, logger.I, _("Setting up other distro dependencies")) self.instPkg("ubuntu-minimal") self.instPkg("syslinux", True) self.instPkg("discover") self.instPkg("coreutils") self.instPkg("bash") self.instPkg("initramfs-tools") self.instPkg("casper") self.instPkg("laptop-detect") logger.logI(self.tn, logger.I, _( "Setting up relinux generation dependencies")) self.instPkg("squashfs-tools", True) self.instPkg("genisoimage", True) configutils.saveBuffer(config.Configuration) aptutil.commitChanges(self.aptcache, self.ap, self.ip) self.exec_()
def runthread(self): logger.logI(self.tn, logger.I, _("Copying files to the temporary filesystem")) excludes = configutils.parseMultipleValues( configutils.getValue(configs[configutils.excludes])) varexcludes = excludes # Exclude all log files (*.log *.log.*), PID files (to show that no daemons are running), # backup and old files (for obvious reasons), and any .deb files that a person might have downloaded varexcludes.extend([ "*.log", "*.log.*", "*.pid", "*/pid", "*.bak", "*.[0-9].gz", "*.deb" ]) fsutil.fscopy("/etc", tmpsys + "etc", excludes, self.tn) fsutil.fscopy("/var", tmpsys + "var", varexcludes, self.tn)
def run(self): logger.logI(self.tn, _("Starting generation of the ISO image")) # Make a last verification on the SquashFS squashfs.doSFSChecks(isotreel + "casper/filesystem.squashfs", configutils.getValue(configs[configutils.isolevel])) # Generate MD5 checksums logger.logV(self.tn, _("Generating MD5 sums")) files = open(isotreel + "md5sum.txt") for x in fsutil.listdir(isotreel, {"recurse": True}): i = re.sub(r"^ *" + isotreel + ".*", ".", x) if i.find("isotree") == -1 and i.find("md5sum") == -1: logger.logVV(self.tn, _("Writing MD5 sum of") + " " + i) files.write(fsutil.genFinalMD5(i)) files.close() logger.logI(self.tn, _("Generating the ISO")) os.system(configutils.getValue(configs[configutils.isogenerator]) + " " + isogenopts + " -V " + configutils.getValue(configs[configutils.label]) + " -o " + configutils.getValue(configs[configutils.isolocation])) # Generate the MD5 sum logger.logV(self.tn, _("Generating MD5 sum for the ISO")) files = open(configs[configutils.isolocation] + ".md5", "w") files.write(fsutil.genFinalMD5(i)) files.close()
def runthread(self): # Generate the package manifest logger.logV(self.tn, logger.I, _("Generating package manifests")) logger.logVV(self.tn, logger.I, _("Generating filesystem.manifest and filesystem.manifest-desktop")) pkglistu = config.AptCache.packages writer = open(isotreel + "casper/filesystem.manifest", "w") writer_desktop = open(isotreel + "casper/filesystem.manifest-desktop", "w") for i in pkglistu: if i.current_ver == None: continue name = i.get_fullname(True).strip() ver = i.current_ver.ver_str.strip() strs = name + " " + ver + "\n" writer.write(strs) if (not name in configutils.parseMultipleValues(configutils.getValue(configs[configutils.remafterinst]))): writer_desktop.write(strs) writer.close() writer_desktop.close() logger.logVV(self.tn, logger.I, _("Generating filesytem.manifest-remove")) writer = open(isotreel + "casper/filesystem.manifest-remove", "w") for i in configutils.parseMultipleValues(configutils.getValue(configs[configutils.remafterinst])): writer.write(i.strip() + "\n") writer.close()
def runthread(self): # If the user-setup-apply file does not exist, and there is an alternative, we'll copy it over logger.logI(self.tn, logger.I, _("Setting up the installer")) if (os.path.isfile("/usr/lib/ubiquity/user-setup/user-setup-apply.orig") and not os.path.isfile("/usr/lib/ubiquity/user-setup/user-setup-apply")): shutil.copy2("/usr/lib/ubiquity/user-setup/user-setup-apply.orig", "/usr/lib/ubiquity/user-setup/user-setup-apply") if (True or configutils.getValue(configs[configutils.aptlistchange])): if not os.path.exists("/usr/share/ubiquity/apt-setup.relinux-backup"): os.rename("/usr/share/ubiquity/apt-setup", "/usr/share/ubiquity/apt-setup.relinux-backup") aptsetup = open("/usr/share/ubiquity/apt-setup", "w") aptsetup.write("#!/bin/sh\n") aptsetup.write("exit\n") aptsetup.close()
def run(adict): global configs, aptcache, page, isotreel, tmpsys configs = adict["config"]["OSWeaver"] isodir = configutils.getValue(configs[configutils.isodir]) isotreel = isodir + "/.ISO_STRUCTURE/" tmpsys = isodir + "/.TMPSYS/" aptcache = adict["aptcache"] ourgui = adict["gui"] pagenum = ourgui.wizard.add_tab() page = gui.Frame(ourgui.wizard.page(pagenum)) ourgui.wizard.add_page_body(pagenum, _("OSWeaver"), page) page.frame = gui.Frame(page, borderwidth=2, relief=Tkinter.GROOVE) page.progress = gui.Progressbar(page) page.progress.pack(fill=Tkinter.X, expand=True, side=Tkinter.BOTTOM, anchor=Tkinter.S) page.frame.pack(fill=Tkinter.BOTH, expand=True, anchor=Tkinter.CENTER) page.button = gui.Button(page.frame, text="Start!", command=runThreads) page.button.pack()
def run(self): # If the user-setup-apply file does not exist, and there is an alternative, we'll copy it over logger.logI(self.tn, _("Setting up the installer")) if os.path.isfile("/usr/lib/ubiquity/user-setup/user-setup-apply.orig") and not os.path.isfile("/usr/lib/ubiquity/user-setup/user-setup-apply"): shutil.copy2("/usr/lib/ubiquity/user-setup/user-setup-apply.orig", "/usr/lib/ubiquity/user-setup/user-setup-apply") if configutils.parseBoolean(configutils.getValue(configs[configutils.aptlistchange])) is True: fsutil.makedir(tmpsys + "usr/share/ubiquity/") aptsetup = open(tmpsys + "usr/share/ubiquity/apt-setup", "w") aptsetup.write("#!/bin/sh\n") aptsetup.write("exit\n") aptsetup.close() else: fsutil.makedir(tmpsys + "usr/lib/ubiquity/apt-setup/generators/") cdrom = open(tmpsys + "usr/lib/ubiquity/apt-setup/generators/40cdrom", "w") cdrom.write("#!/bin/sh\n") cdrom.write("exit\n") cdrom.close()
def run(self): logger.logI(self.tn, _("Making the ISO compatible with a USB burner")) logger.logVV(self.tn, _("Writing .disk/info")) files = open(isotreel + ".disk/info", "w") files.write(getDiskName()) files.close() logger.logV(self.tn, _("Making symlink pointing to the ISO root dir")) os.symlink(isotreel + "ubuntu", isotreel) logger.logVV(self.tn, _("Writing release notes URL")) files = open(isotreel + ".disk/release_notes_url", "w") files.write(configutils.getValue(configs[configutils.url]) + "\n") files.close() logger.logVV(self.tn, _("Writing .disk/base_installable")) fsutil.touch(isotreel + ".disk/base_installable") logger.logVV(self.tn, _("Writing CD Type")) files = open(isotreel + ".disk/cd_type", "w") files.write("full_cd/single\n") files.close()
def runthread(self): # If the user-setup-apply file does not exist, and there is an alternative, we'll copy it over logger.logI(self.tn, logger.I, _("Setting up the installer")) if (os.path.isfile( "/usr/lib/ubiquity/user-setup/user-setup-apply.orig") and not os.path.isfile( "/usr/lib/ubiquity/user-setup/user-setup-apply")): shutil.copy2("/usr/lib/ubiquity/user-setup/user-setup-apply.orig", "/usr/lib/ubiquity/user-setup/user-setup-apply") if (True or configutils.parseBoolean( configutils.getValue(configs[configutils.aptlistchange]))): if not os.path.exists( "/usr/share/ubiquity/apt-setup.relinux-backup"): os.rename("/usr/share/ubiquity/apt-setup", "/usr/share/ubiquity/apt-setup.relinux-backup") aptsetup = open("/usr/share/ubiquity/apt-setup", "w") aptsetup.write("#!/bin/sh\n") aptsetup.write("exit\n") aptsetup.close()
def runthread(self): logger.logI(self.tn, logger.I, _("Starting generation of the ISO image")) # Make a last verification on the SquashFS squashfs.doSFSChecks(isotreel + "casper/filesystem.squashfs", configutils.getValue(configs[configutils.isolevel])) self.setProgress(self.tn, 5) # Generate MD5 checksums logger.logV(self.tn, logger.I, _("Generating MD5 sums")) files = open(isotreel + "md5sum.txt", "w") for x in fsutil.listdir(isotreel, {"recurse": True}): i = re.sub(r"^ *" + isotreel + "/*", "./", x) if not "isolinux" in i and not "md5sum" in i: logger.logVV(self.tn, logger.I, _("Writing MD5 sum of") + " " + i) fmd5 = fsutil.genFinalMD5(i, x) if fmd5 != "" and fmd5 != None: files.write(fmd5) files.close() self.setProgress(self.tn, 15) logger.logI(self.tn, logger.I, _("Generating the ISO")) location = (configutils.getValue(configs[configutils.isodir]) + "/" + configutils.getValue(configs[configutils.isolocation])) patt = re.compile("^ *([0-9]+)\.?[0-9]*%.*$") appnd = "32" if sys.maxsize > 2 ** 32: appnd = "64" os.environ["LD_PRELOAD"] = os.path.split(os.path.realpath(__file__))[0] + "/isatty" + appnd + ".so" isocmd = subprocess.Popen(shlex.split(configutils.getValue(configs[configutils.isogenerator]) + " -o " + location + " " + isogenopts + " -V \"" + configutils.getValue(configs[configutils.label]) + "\" " + isotreel), stderr=subprocess.PIPE, universal_newlines=True) oldprogress = 0 while isocmd.poll() is None: output = isocmd.stderr.readline() match = patt.match(output) if match != None: progress = int(match.group(1)) if progress > oldprogress: # 1.4285714285714286 is just 100 / 70 self.setProgress(self.tn, 15 + int(utilities.floatDivision(progress, 1.4285714285714286))) oldprogress = progress sys.stdout.write(output) sys.stdout.flush() os.environ["LD_PRELOAD"] = "" self.setProgress(self.tn, 85) # Generate the MD5 sum logger.logV(self.tn, logger.I, _("Generating MD5 sum for the ISO")) files = open(location + ".md5", "w") files.write(fsutil.genFinalMD5("./" + configutils.getValue(configs[configutils.isolocation]), location)) files.close()
def writeAll(status, lists, tn, importance, text, **options): if tn == "" or tn is None or not status: return text_ = "[" + tn + "] " if importance == E: text_ += MError elif importance == W: text_ += MWarning elif importance == D: text_ += MDebug from relinux import configutils if not configutils.getValue(config.Configuration["Relinux"]["DEBUG"]): return else: text_ += "" text__ = text_ + text text = text__ for i in lists: if i in config.TermStreams and "noterm" in options and options[ "noterm"]: continue if i == config.GUIStream and "nogui" in options and options["nogui"]: continue text_ = copy.copy(text) if i in config.TermStreams: text__ = "\033[" if importance == E: text__ += str(config.TermRed) elif importance == W: text__ += str(config.TermYellow) elif importance == D: text__ += str(config.TermGreen) '''elif importance == I: text__ += config.TermBlue''' text__ += "m" + text_ + "\033[" + str(config.TermReset) + "m" text_ = text__ i.write(utilities.utf8(text_ + MNewline))
def writeAll(status, lists, tn, importance, text, **options): if tn == "" or tn is None or not status: return text_ = "[" + tn + "] " if importance == E: text_ += MError elif importance == W: text_ += MWarning elif importance == D: text_ += MDebug from relinux import configutils if not configutils.getValue(config.Configuration["Relinux"]["DEBUG"]): return else: text_ += "" text__ = text_ + text text = text__ for i in lists: if i in config.TermStreams and "noterm" in options and options["noterm"]: continue if i == config.GUIStream and "nogui" in options and options["nogui"]: continue text_ = copy.copy(text) if i in config.TermStreams: text__ = "\033[" if importance == E: text__ += str(config.TermRed) elif importance == W: text__ += str(config.TermYellow) elif importance == D: text__ += str(config.TermGreen) '''elif importance == I: text__ += config.TermBlue''' text__ += "m" + text_ + "\033[" + str(config.TermReset) + "m" text_ = text__ i.write(utilities.utf8(text_ + MNewline))
def runthread(self): # If the user-setup-apply file does not exist, and there is an alternative, we'll copy it over logger.logI(self.tn, logger.I, _("Setting up the installer")) if (os.path.isfile("/usr/lib/ubiquity/user-setup/user-setup-apply.orig") and not os.path.isfile("/usr/lib/ubiquity/user-setup/user-setup-apply")): shutil.copy2("/usr/lib/ubiquity/user-setup/user-setup-apply.orig", "/usr/lib/ubiquity/user-setup/user-setup-apply") # If the user requested to make sure that the installer does _not_ change the apt sources, # make sure that relinux obeys this. # However, if the user changed his/her mind, we want to make sure that relinux # work with that too if not configutils.getValue(configs[configutils.aptlistchange]): if not os.path.exists("/usr/share/ubiquity/apt-setup.relinux-backup"): os.rename("/usr/share/ubiquity/apt-setup", "/usr/share/ubiquity/apt-setup.relinux-backup") aptsetup = open("/usr/share/ubiquity/apt-setup", "w") aptsetup.write("\n") aptsetup.close() fsutil.chmod("/usr/share/ubiquity/apt-setup", 0o755, self.tn) elif os.path.exists("/usr/share/ubiquity/apt-setup.relinux-backup"): # TODO: Fix the 40cdrom bug? fsutil.rm("/usr/share/ubiquity/apt-setup", False, self.tn) os.rename("/usr/share/ubiquity/apt-setup.relinux-backup", "/usr/share/ubiquity/apt-setup")
# -V label Label of the ISO # -cache-inodes Enable caching inodes and device numbers # -J Use Joliet specification to let pathnames use 64 characters # -l Allow 31-character filenames (Joliet will replace this of course) # -b bootimage Boot with the specified image # -c bootcatalog Path to generate the boot catalog # -no-emul-boot Shows that the boot image specified is a "no emulation" image # This means that the system will not perform any disk emulation when running it # -boot-load-size 4 Number of virtual sectors to load # -boot-info-table Add a boot information table to the boot image # -o file Output image # -input-charset utf-8 Use the UTF-8 input charset # -iso-level isolevel ISO Level isogenopts = ("-r -cache-inodes -J -l -b isolinux/isolinux.bin -c isolinux/boot.cat -no-emul-boot " + "-boot-load-size 4 -boot-info-table -input-charset utf-8 -iso-level " + configutils.getValue(configs[configutils.isolevel])) # Returns the disk name of the ISO def getDiskName(): return configutils.getValue(configs[configutils.label]) + " - Release " + config.Arch # Shows a file not found error def showFileNotFound(files, dirs, tn): logger.logE(tn, logger.E, files + " " + _("not found") + ". " + _("Copy") + " " + files + " " + _("to") + " " + dirs) # Copy a file def copyFile(src, dst, tn, critical=False):
def getDiskName(): return configutils.getValue(configs[configutils.label]) + " - Release " + config.Arch
def runthread(self): logger.logI(self.tn, logger.I, _("Copying the kernel to the ISO tree")) copyFile( "/boot/vmlinuz-" + configutils.getKernel( configutils.getValue(configs[configutils.kernel])), isotreel + "casper/vmlinuz", self.tn)
def runthread(self): logger.logV(self.tn, logger.I, _("Generating RAMFS")) os.system("mkinitramfs -o " + isotreel + "casper/initrd.gz " + configutils.getKernel(configutils.getValue(configs[configutils.kernel]))) '''copyFile("/boot/initrd.img-" + configutils.getKernel(configutils.getValue(configs[configutils.kernel])),
def runthread(self): if configutils.getValue(configs[configutils.memtest]): logger.logV( self.tn, logger.I, _("Copying memtest to the ISO tree")) copyFile("/boot/memtest86+.bin", isotreel + "isolinux/memtest", self.tn)
def main(): def parsePyHex(string1): string = "%x" % string1 count = 0 result = "" for char in string: if count == 0 or count == 2 or count == 4: result += char if count != 4: result += "." elif count == 5: if char.lower() == "f": break else: result += char.lower() elif count == 6: result += char count += 1 return result if not config.python_ok: print(_("Relinux only supports python ") + parsePyHex(config.min_python_version) + "-" + parsePyHex(config.max_python_version) + ", " + _("but python ") + parsePyHex(sys.hexversion) + " " + _("was used.")) exitprog(1) from argparse import ArgumentParser '''tkname = "Tkinter" if config.python3: tkname = "tkinter" Tkinter = __import__(tkname)''' #import time from relinux import gui, configutils, logger, aptutil, modloader, utilities, fsutil config.Arch = fsutil.getArch() logger.veryverbose() config.GUIStream = utilities.eventStringIO() tn = logger.genTN("Main") parser = ArgumentParser(prog="relinux", usage="%(prog)s [options]") parser.add_argument("-V", "--version", action="store_true", dest="showversion", help="show version information") parser.add_argument("-q", "--quiet", action="store_true", dest="quiet", default=False, help="log as little as possible to stdout") parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="log more to stdout") parser.add_argument("-vv", "--veryverbose", action="store_true", dest="veryverbose", default=False, help="log even more to stdout") parser.add_argument( "--no-stylesheet", action="store_true", dest="nostylesheet", default=False, help="don't use any stylesheets") args = parser.parse_args() config.EFiles.extend([config.GUIStream, sys.stdout]) if args.showversion: version() if not args.quiet: config.IFiles.extend([config.GUIStream, sys.stdout]) if args.verbose: config.VFiles.extend([config.GUIStream, sys.stdout]) if args.veryverbose: config.VVFiles.extend([config.GUIStream, sys.stdout]) #modules = [] #aptcache = [] #cbuffer = {} '''root = Tkinter.Tk() App = None def startProg(splash): global modules, aptcache, cbuffer, App spprogn = 6 spprog = 0 def calcPercent(def2 = (spprog, spprogn)): return utilities.calcPercent(*def2) splash.setProgress( calcPercent((spprog, spprogn)), "Loading modules...") modules = [] modulemetas = modloader.getModules() for i in modulemetas: modules.append(modloader.loadModule(i)) spprog += 1 splash.setProgress( calcPercent((spprog, spprogn)), "Parsing configuration...") #buffer1 = utilities.getBuffer(open(relinuxdir + "/relinux.conf")) #buffer2 = configutils.compress(buffer1) #cbuffer = configutils.parseCompressedBuffer(buffer2, relinuxdir + "/relinux.conf") configfiles = [relinuxdir + "/relinux.conf"] for i in range(len(modulemetas)): for x in modules[i].moduleconfig: configfiles.append( os.path.join(os.path.dirname(modulemetas[i]["path"]), x)) cbuffer = configutils.parseFiles(configfiles) config.Configuration = cbuffer configutils.saveBuffer(config.Configuration) \'''for i in configutils.beautify(buffer1): print(i)\''' spprog += 1 splash.setProgress( calcPercent((spprog, spprogn)), "Reading APT Cache...") def aptupdate(op, percent): global minis if percent != None: minis += utilities.floatDivision(percent, 100) splash.setProgress( calcPercent((utilities.floatDivision( minis + captop, aptops) + spprog, spprogn)), "Reading APT Cache... (" + op + ")") def aptdone(op): global minis, captop minis = 0.0 captop += 1 aptcache = aptutil.getCache(aptutil.OpProgress(aptupdate, aptdone)) config.AptCache = aptcache spprog += 1 splash.setProgress( calcPercent((spprog, spprogn)), "Loading the GUI...") App = gui.GUI(root) spprog += 1 splash.setProgress( calcPercent((spprog, spprogn)), "Filling in configuration...") App.fillConfiguration(cbuffer) spprog += 1 splash.setProgress( calcPercent((spprog, spprogn)), "Running modules...") for i in modules: modloader.runModule(i, {"gui": App, "config": cbuffer, "aptcache": aptcache}) spprog += 1 splash.setProgress(calcPercent((spprog, spprogn)), "Launching relinux") splash = gui.Splash(root, startProg) #root.overrideredirect(Tkinter.TRUE) # Coming soon! root.mainloop()''' App = QtGui.QApplication(sys.argv) splash = QtGui.QSplashScreen( QtGui.QPixmap(relinuxdir + "/splash_light.png")) splash.show() App.processEvents() def showMessage(str_): splash.showMessage( str_ + "...", QtCore.Qt.AlignLeft | QtCore.Qt.AlignBottom) App.processEvents() showMessage(_("Loading modules")) modules = [] modulemetas = modloader.getModules() for i in modulemetas: modules.append(modloader.loadModule(i)) showMessage(_("Loading configuration files")) configfiles = [relinuxdir + "/relinux.conf"] for i in range(len(modulemetas)): for x in modules[i].moduleconfig: if "RELINUXCONFDIR" in os.environ: configfiles.append(os.path.join(relinuxdir, x)) else: configfiles.append( os.path.join(os.path.dirname(modulemetas[i]["path"]), x)) cbuffer = configutils.parseFiles(configfiles) config.Configuration = cbuffer configutils.saveBuffer(config.Configuration) logfilename = configutils.getValue(cbuffer["Relinux"]["LOGFILE"]) logfile = open(logfilename, "a") config.EFiles.append(logfile) config.IFiles.append(logfile) config.VFiles.append(logfile) config.VVFiles.append(logfile) logger.logI(tn, logger.I, "===========================") logger.logI(tn, logger.I, "=== Started new session ===") logger.logI(tn, logger.I, "===========================") showMessage(_("Loading APT cache 0%")) def aptupdate(op, percent): global minis if percent: minis = int(percent) showMessage( _("Loading APT cache") + " (" + op + ") " + str(minis) + "%") aptcache = aptutil.getCache(aptutil.OpProgress(aptupdate, None)) config.AptCache = aptcache if not args.nostylesheet: showMessage(_("Loading stylesheet")) App.setStyleSheet(open(mainsrcdir + "/stylesheet.css", "r").read()) showMessage(_("Loading GUI")) gui_ = gui.GUI(App) config.Gui = gui_ showMessage(_("Running modules")) for i in modules: modloader.runModule(i, {}) gui_.show() splash.finish(gui_) exitcode = App.exec_() config.ThreadStop = True logfile.close() sys.exit(exitcode)
def runthread(self): logger.logI(tn, logger.I, _("Generating compressed filesystem")) # Generate the SquashFS file # Options: # -b 1M Use a 1M blocksize (maximum) # -no-recovery No recovery files # -always-use-fragments Fragment blocks for files larger than the blocksize (1M) # -comp Compression type logger.logVV(tn, logger.I, _("Generating options")) opts = "-b 1M -no-recovery -no-duplicates -always-use-fragments" opts = opts + " -comp " + configutils.getValue( configs[configutils.sfscomp]) opts = opts + " " + configutils.getValue(configs[configutils.sfsopts]) sfsex = "dev etc home media mnt proc sys var run usr/lib/ubiquity/apt-setup/generators/40cdrom tmp" sfspath = isotreel + "casper/filesystem.squashfs" if os.path.exists(sfspath): fsutil.rm(sfspath) # This line would match the pattern below: [==========/ ] 70/300 20% patt = re.compile("^ *\[=*. *\] *[0-9]*/[0-9]* *([0-9]*)% *$") appnd = "32" if sys.maxsize > 2**32: appnd = "64" # Hack to make sure all output is given os.environ["LD_PRELOAD"] = os.path.split( os.path.realpath(__file__))[0] + "/isatty" + appnd + ".so" logger.logI(tn, logger.I, _("Adding the edited /etc and /var to the filesystem")) logger.logI(tn, logger.I, logger.MTab + _("This might take a couple of minutes")) sfscmd = subprocess.Popen(shlex.split("mksquashfs " + tmpsys + " " + sfspath + " " + opts), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) oldprogress = 0 while sfscmd.poll() is None: output = sfscmd.stdout.readline() match = patt.match(output) if match is not None: sys.stdout.write("\r" + match.group(0)) sys.stdout.flush() progress = int(match.group(1)) if progress > oldprogress: self.setProgress(tn, int(utilities.floatDivision(progress, 2))) oldprogress = progress elif len(output.strip()) > 0: logger.logI(tn, logger.I, output.rstrip(), noterm=True, nogui=True) sys.stdout.write("\n") logger.logI(tn, logger.I, _("Adding the rest of the system (this can take a while)")) sfscmd = subprocess.Popen(shlex.split("mksquashfs / " + sfspath + " " + opts + " -e " + sfsex), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) oldprogress = 0 while sfscmd.poll() is None: output = sfscmd.stdout.readline() match = patt.match(output) if match is not None: sys.stdout.write("\r" + match.group(0)) sys.stdout.flush() progress = int(match.group(1)) if progress > oldprogress: self.setProgress( tn, 50 + int(utilities.floatDivision(progress, 2))) oldprogress = progress elif len(output.strip()) > 0: logger.logI(tn, logger.I, output.rstrip(), noterm=True, nogui=True) sys.stdout.write("\n") os.environ["LD_PRELOAD"] = "" # Make sure the SquashFS file is OK doSFSChecks(sfspath, int(configutils.getValue(configs[configutils.isolevel]))) # Find the size after it is uncompressed logger.logV(tn, logger.I, _("Writing the size")) files = open(isotreel + "casper/filesystem.size", "w") files.write(str(fsutil.getSFSInstSize(sfspath)) + "\n") files.close()
def fillConfiguration(self, configs, widget): # TODO: Clean this mess, or at least comment it l = chr(108) v = chr(118) for i in configs.keys(): # If the section is not in the notebook, add it if not i in self.configTab.notebook1.__dict__: self.configTab.notebook1.__dict__[i] = QtGui.QWidget() self.configTab.notebook1.__dict__[ i].vlayout = QtGui.QVBoxLayout( self.configTab.notebook1.__dict__[i]) self.configTab.notebook1.__dict__[i].nbook = QtGui.QTabWidget( self.configTab.notebook1.__dict__[i]) self.configTab.notebook1.__dict__[i].vlayout.addWidget( self.configTab.notebook1.__dict__[i].nbook) self.configTab.notebook1.addTab( self.configTab.notebook1.__dict__[i], i) for x in configs[i].keys(): c = configutils.getValueP(configs[i][x], configutils.category) n = configutils.getValueP(configs[i][x], configutils.name) t = configutils.getValueP(configs[i][x], configutils.types) v_ = configutils.getValue(configs[i][x]) c_ = configutils.getChoices(t) var = (i, x) # If the category is not in the section's notebook, add it if not c in self.configTab.notebook1.__dict__[i].nbook.__dict__: fw = QtGui.QWidget( self.configTab.notebook1.__dict__[i].nbook) vb = QtGui.QVBoxLayout(fw) self.configTab.notebook1.__dict__[i].nbook.__dict__[ c] = QtGui.QScrollArea(fw) vb.addWidget( self.configTab.notebook1.__dict__[i].nbook.__dict__[c]) self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].setWidgetResizable(False) self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].flayout = QtGui.QFormLayout() self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].flayout.setSizeConstraint( QtGui.QLayout.SetFixedSize) self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].flayout.setFieldGrowthPolicy( QtGui.QFormLayout.AllNonFixedFieldsGrow) self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].flayout.setLabelAlignment(QtCore.Qt.AlignLeft) self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].flayoutC = QtGui.QWidget() self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].flayoutC.setLayout( self.configTab.notebook1.__dict__[i].nbook. __dict__[c].flayout) self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].setWidget(self.configTab.notebook1.__dict__[i]. nbook.__dict__[c].flayoutC) self.configTab.notebook1.__dict__[i].nbook.addTab(fw, c) # Add the label self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n] = {} self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][l] = QtGui.QLabel() self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][l].setText(n) # Add the value if t == configutils.yesno: self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][v] = ConfigWidget( QtGui.QCheckBox(), var) if configutils.parseBoolean(v_): self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][v].widget.setChecked(True) elif c_ is not None and len(c_) > 0: self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][v] = ConfigWidget( QtGui.QComboBox(), var) self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][v].widget.clear() c__ = 0 for y in c_: self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][v].widget.addItem(y) if y == v_: self.configTab.notebook1.__dict__[ i].nbook.__dict__[c].__dict__[n][ v].widget.setCurrentIndex(c__) c__ += 1 else: self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][v] = ConfigWidget( QtGui.QLineEdit(), var) self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][v].widget.setText(v_) self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][v].widget.setSizePolicy( QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding)) self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].flayout.addRow( self.configTab.notebook1.__dict__[i].nbook.__dict__[c]. __dict__[n][l], self.configTab.notebook1.__dict__[i]. nbook.__dict__[c].__dict__[n][v].widget)
def fillConfiguration(self, configs, widget): # TODO: Clean this mess, or at least comment it l = "l" v = "v" for i in configs.keys(): # If the section is not in the notebook, add it if not i in self.configTab.notebook1.__dict__: self.configTab.notebook1.__dict__[i] = QtGui.QWidget() self.configTab.notebook1.__dict__[ i].vlayout = QtGui.QVBoxLayout( self.configTab.notebook1.__dict__[i]) self.configTab.notebook1.__dict__[i].nbook = QtGui.QTabWidget( self.configTab.notebook1.__dict__[i]) self.configTab.notebook1.__dict__[i].vlayout.addWidget( self.configTab.notebook1.__dict__[i].nbook) self.configTab.notebook1.addTab( self.configTab.notebook1.__dict__[i], i) for c in configutils.getValue(configs[i][configutils.categories]): self.addCategory(i, c) for x in configs[i].keys(): if x == configutils.categories: continue c = configutils.getValueP(configs[i][x], configutils.category) n = configutils.getValueP(configs[i][x], configutils.name) t = configutils.getValueP(configs[i][x], configutils.types) d = configutils.getValueP(configs[i][x], configutils.desc) v_ = configutils.getValue(configs[i][x]) c_ = configutils.getChoices(t) var = (i, x) uw = True # If the category is not in the section's notebook, add it if not c in self.configTab.notebook1.__dict__[i].nbook.__dict__: self.addCategory(i, c) # Add the dictionary self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n] = {} # Add the label self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][l] = QtGui.QLabel() self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][l].setText(n) self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][l].setToolTip(d) # Add the value if t == configutils.yesno: self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][v] = ConfigWidget( QtGui.QCheckBox(), var) if v_: self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][v].widget.setChecked(True) elif c_ is not None and len(c_) > 0: self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][v] = ConfigWidget( QtGui.QComboBox(), var) self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][v].widget.clear() c__ = 0 for y in c_: self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][v].widget.addItem(y) if y == v_: self.configTab.notebook1.__dict__[ i].nbook.__dict__[c].__dict__[n][ v].widget.setCurrentIndex(c__) c__ += 1 elif t == configutils.multiple: if not isinstance(v_, list): # Wut? logger.logE(self.tn, logger.E, _("Something went wrong")) self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][v] = MultipleValues(var) self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][v].set(v_) uw = False elif t == configutils.filename: self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][v] = FileName(var) self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][v].set(v_) uw = False else: self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][v] = ConfigWidget( QtGui.QLineEdit(), var) self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][v].widget.setText(v_) #self.configTab.notebook1.__dict__[i].nbook.__dict__[c].__dict__[n][v].widget.setSizePolicy( # QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding)) if uw: p = self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][v].widget else: p = self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].__dict__[n][v] p.setToolTip(d) self.configTab.notebook1.__dict__[i].nbook.__dict__[ c].flayout.addRow( self.configTab.notebook1.__dict__[i].nbook.__dict__[c]. __dict__[n][l], p)
def run(adict): global aptcache, page configs = adict["config"]["OSWeaver"] isodir = configutils.getValue(configs[configutils.isodir]) config.ISOTree = isodir + "/.ISO_STRUCTURE/" print(config.ISOTree) config.TempSys = isodir + "/.TMPSYS/" aptcache = adict["aptcache"] ourgui = adict["gui"] from relinux.modules.osweaver import isoutil, squashfs, tempsys, ui_osweaver threads = [] threads.extend(tempsys.threads) threads.extend(squashfs.threads) threads.extend(isoutil.threads) threads_ = utilities.remDuplicates(threads) threads = threads_ '''pagenum = ourgui.wizard.add_tab() page = gui.Frame(ourgui.wizard.page(pagenum)) ourgui.wizard.add_page_body(pagenum, _("OSWeaver"), page) page.frame = gui.Frame(page) page.details = gui.VerticalScrolledFrame(page, borderwidth = 1, relief = Tkinter.SOLID) page.details.output = gui.Label(page.details.interior, text = config.GUIStream.getvalue(), anchor = Tkinter.NW, justify = Tkinter.LEFT) def onWrite(): page.details.output.config(text = config.GUIStream.getvalue()) page.details.canvas.yview_moveto(1.0) config.GUIStream.writefunc.append(onWrite) page.details.output.pack(fill = Tkinter.BOTH, expand = True, anchor = Tkinter.NW, side = Tkinter.LEFT) page.details.pack(fill = Tkinter.BOTH, expand = True, side = Tkinter.BOTTOM, anchor = Tkinter.SW) \'''page.details.buttonstate = True def showDetails(): if page.details.buttonstate: page.details.output.pack(fill=Tkinter.BOTH, expand=True, anchor=Tkinter.NW, side=Tkinter.LEFT) page.showdetails.config(text="<< Hide details") page.details.buttonstate = False else: page.details.output.pack_forget() page.showdetails.config(text="Show details >>") page.details.buttonstate = True page.showdetails = gui.Button(page, text="Show details >>", command=showDetails) page.showdetails.pack(side=Tkinter.BOTTOM, anchor=Tkinter.SW)\''' page.progress = gui.Progressbar(page) page.progress.pack(fill = Tkinter.X, expand = True, side = Tkinter.BOTTOM, anchor = Tkinter.S) page.frame.pack(fill = Tkinter.BOTH, expand = True, anchor = Tkinter.CENTER) page.chframe = gui.VerticalScrolledFrame(page.frame) page.chframe.pack(fill = Tkinter.BOTH, expand = True, anchor = Tkinter.N) page.chframe.boxes = [] page.chframe.dispthreads = [] x = 0 y = 0 usedeps = gui.Checkbutton(page.chframe.interior, text = "Ignore dependencies") usedeps.grid(row = y, column = x) y += 1 label = gui.Label(page.chframe.interior, text = "Select threads to run:") label.grid(row = y, column = x) y += 1 class customCheck(gui.Checkbutton): def __init__(self, parent, *args, **kw): gui.Checkbutton.__init__(self, parent, *args, **kw) self.id = len(page.chframe.boxes) self.ignoreauto = True self.value.trace("w", self.autoSelect) def autoSelect(self, *args): id_ = self.id if self.ignoreauto: self.ignoreauto = False return if self.value.get() < 1: return if len(threads[id_]["deps"]) <= 0 or usedeps.value.get() > 0: return tns = [] for i in threads[id_]["deps"]: tns.append(i["tn"]) for i in range(len(threads)): if threads[i]["tn"] in tns: page.chframe.boxes[i].value.set(1) for i in threads: temp = customCheck(page.chframe.interior, text = i["tn"]) temp.value.set(1) temp.grid(row = y, column = x, sticky = Tkinter.NW) page.chframe.boxes.append(temp) x += 1 if x >= 3: x = 0 y += 1 if x != 0: y += 1 def selBoxes(all_): val = 0 if all_ == None: for i in range(len(threads)): page.chframe.boxes[i].ignoreauto = True if page.chframe.boxes[i].value.get() < 1: page.chframe.boxes[i].value.set(1) else: page.chframe.boxes[i].value.set(0) return if all_: val = 1 for i in range(len(threads)): page.chframe.boxes[i].ignoreauto = True page.chframe.boxes[i].value.set(val) selall = gui.Button(page.chframe.interior, text = "Select all", command = lambda: selBoxes(True)) selall.grid(row = y, column = x) x += 1 selnone = gui.Button(page.chframe.interior, text = "Select none", command = lambda: selBoxes(False)) selnone.grid(row = y, column = x) x += 1 togglesel = gui.Button(page.chframe.interior, text = "Toggle", command = lambda: selBoxes(None)) togglesel.grid(row = y, column = x) y += 1 x = 0 threadsrunninglabel = gui.Label(page.chframe.interior, text = "Threads running:") threadsrunninglabel.grid(row = y, column = x, columnspan = 3) y += 1 page.progress.threads = {} def startThreads(): if os.getuid() != 0: page.isnotroot.pack_forget() page.isnotroot.pack(fill = Tkinter.X) return numthreads = 0 for i in range(len(page.chframe.boxes)): if page.chframe.boxes[i].value.get() < 1: threads[i]["enabled"] = False else: threads[i]["enabled"] = True numthreads += 1 tfdeps = False if usedeps.value.get() > 0: tfdeps = True def postStart(threadid, threadsrunning, threads): txt = "" for i in range(len(threadsrunning)): tn = threadmanager.getThread(threadsrunning[i], threads)["tn"] if i == len(threadsrunning) - 1: if len(threadsrunning) == 1: txt = tn elif len(threadsrunning) == 2: txt += " and " + tn else: txt += ", and " + tn elif i == 0: txt = tn else: txt += ", " + tn threadsrunninglabel.config(text = "Threads running: " + txt) def setProgress(tn, progress): page.progress.threads[tn] = progress totprogress = 0 for i in page.progress.threads.keys(): totprogress += utilities.floatDivision(float(page.progress.threads[i]), 100) page.progress.setProgress(utilities.calcPercent(totprogress, numthreads)) def postEnd(threadid, threadsrunning, threads): tn = threadmanager.getThread(threadid, threads)["tn"] setProgress(tn, 100) postStart(threadid, threadsrunning, threads) runThreads(threads, deps = tfdeps, poststart = postStart, postend = postEnd, threadargs = {"setProgress": setProgress}) # lambda: runThreads(threads) page.button = gui.Button(page.frame, text = "Start!", command = startThreads) page.button.pack() page.isnotroot = gui.Label(page.frame, text = "You are not root!")''' page = {} page["boxes"] = [] page["progress"] = {} page_container = QtGui.QWidget() ui = ui_osweaver.Ui_OSWeaver() ui.setupUi(page_container) ui.notroot.hide() #ui.terminal.hide() class customCheck(QtGui.QCheckBox): def __init__(self, *args): QtGui.QCheckBox.__init__(self, *args) self.ignoreauto = False self.id = len(page["boxes"]) self.value = utilities.eventVar(value = False) self.value.trace("w", self.set) self.clicked.connect(self.toggled_) def toggled_(self, *args): self.setChecked(not self.get()) # Toggle checked state self.value.set(not self.get()) # Set the state that was wanted (not not) def set(self, newvalue): if newvalue == self.get(): return self.setChecked(newvalue) if self.ignoreauto: self.ignoreauto = False elif newvalue: self.autoSelect() def get(self): return self.isChecked() def autoSelect(self): if len(threads[self.id]["deps"]) < 0 or ui.nodepends.isChecked(): return tns = [i["tn"] for i in threads[self.id]["deps"]] for i in range(len(threads)): if threads[i]["tn"] in tns: page["boxes"][i].set(True) x = 0 y = 0 for i in threads: ch = customCheck(i["tn"], ui.threadstorun) ui.gridLayout_2.addWidget(ch, y, x) # No idea why Qt wants Y before X page["boxes"].append(ch) x += 1 if x >= 3: x = 0 y += 1 # Terrible name, but it's just a function that selects/deselects values from "threevalues" # Possible values of "threevalues": # True - Select All # False - Select None # None - Toggle Selected def tripleSel(threevalues): val = False tog = False if threevalues: # Select All val = True elif threevalues is None: tog = True for i in range(len(page["boxes"])): page["boxes"][i].ignoreauto = True if tog: page["boxes"][i].set(not page["boxes"][i].get()) else: page["boxes"][i].set(val) # Run when ui.nodepends is unchecked def ignoreDepends(): for i in range(len(page["boxes"])): if page["boxes"][i].get(): page["boxes"][i].autoSelect() # Start running def startThreads(*args): if os.getuid() != 0: ui.notroot.show() return numthreads = 0 numthreads2 = 0 threadmanager.addOptional(threads) for i in range(len(page["boxes"])): threads[i]["enabled"] = page["boxes"][i].get() if threads[i]["enabled"]: numthreads += 1 if threads[i]["threadspan"] < 0: numthreads2 += threadmanager.cpumax else: numthreads2 += threads[i]["threadspan"] tfdeps = False if ui.nodepends.isChecked(): tfdeps = True def onThreadAdded(threadid, threadsrunning, threads): rt = "Threads running: " c = 0 for i in range(len(threadsrunning)): tn = threadmanager.getThread(threadsrunning[i], threads)["tn"] rt += tn if c + 1 < len(threadsrunning) and len(threadsrunning) > 2: rt += ", " if c + 2 == len(threadsrunning): rt += "and " c += 1 QtCore.QMetaObject.invokeMethod(ui.notroot, "setText", QtCore.Qt.QueuedConnection, QtCore.Q_ARG("QString", rt)) if ui.notroot.isHidden(): QtCore.QMetaObject.invokeMethod(ui.notroot, "show", QtCore.Qt.QueuedConnection ) def setProgress(tn, progress): logger.logVV(tn, logger.D, "Setting progress to " + str(progress) + " (from thread " + threading.current_thread().name + ")") #return # Do something here if progress > 100: progress = 100 elif progress < 0: progress = 0 page["progress"][tn] = progress totprogress = 0 for i in page["progress"]: totprogress += utilities.floatDivision(float(page["progress"][i]), 100) QtCore.QMetaObject.invokeMethod(ui.progress, "setValue", QtCore.Qt.QueuedConnection, QtCore.Q_ARG("int", utilities.calcPercent(totprogress, numthreads2))) def onThreadRemoved(threadid, threadsrunning, threads): tn = threadmanager.getThread(threadid, threads)["tn"] setProgress(tn, 100) onThreadAdded(threadid, threadsrunning, threads) for i in page["progress"]: page["progress"][i] = 0 runThreads(threads, deps = tfdeps, poststart = onThreadAdded, postend = onThreadRemoved, threadargs = {"setProgress": setProgress}) def onWrite(msg): logger.logVV(tn, logger.D, "Updating terminal (from thread " + threading.current_thread().name + ")") #return ui.terminal.moveCursor(QtGui.QTextCursor.End, QtGui.QTextCursor.MoveAnchor) QtCore.QMetaObject.invokeMethod(ui.terminal, "insertPlainText", QtCore.Qt.QueuedConnection, QtCore.Q_ARG("QString", msg.rstrip() + "\n")) #ui.terminal.setText(config.GUIStream.getvalue()) tripleSel(True) config.GUIStream.writefunc.append(onWrite) ui.selall.clicked.connect(lambda *args: tripleSel(True)) ui.selnone.clicked.connect(lambda *args: tripleSel(False)) ui.togsel.clicked.connect(lambda *args: tripleSel(None)) ui.nodepends.clicked.connect(lambda *args: ignoreDepends() if not ui.nodepends.isChecked() else None) ui.startbutton.clicked.connect(startThreads) ourgui.addTab(page_container, "OSWeaver")
def main(): def parsePyHex(string1): string = "%x" % string1 count = 0 result = "" for char in string: if count == 0 or count == 2 or count == 4: result += char if count != 4: result += "." elif count == 5: if char.lower() == "f": break else: result += char.lower() elif count == 6: result += char count += 1 return result if not config.python_ok: print( _("Relinux only supports python ") + parsePyHex(config.min_python_version) + "-" + parsePyHex(config.max_python_version) + ", " + _("but python ") + parsePyHex(sys.hexversion) + " " + _("was used.")) exitprog(1) from argparse import ArgumentParser '''tkname = "Tkinter" if config.python3: tkname = "tkinter" Tkinter = __import__(tkname)''' #import time from relinux import gui, configutils, logger, aptutil, modloader, utilities, fsutil config.Arch = fsutil.getArch() logger.veryverbose() config.GUIStream = utilities.eventStringIO() tn = logger.genTN("Main") parser = ArgumentParser(prog="relinux", usage="%(prog)s [options]") parser.add_argument("-V", "--version", action="store_true", dest="showversion", help="show version information") parser.add_argument("-q", "--quiet", action="store_true", dest="quiet", default=False, help="log as little as possible to stdout") parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="log more to stdout") parser.add_argument("-vv", "--veryverbose", action="store_true", dest="veryverbose", default=False, help="log even more to stdout") parser.add_argument("--no-stylesheet", action="store_true", dest="nostylesheet", default=False, help="don't use any stylesheets") args = parser.parse_args() config.EFiles.extend([config.GUIStream, sys.stdout]) if args.showversion: version() if not args.quiet: config.IFiles.extend([config.GUIStream, sys.stdout]) if args.verbose: config.VFiles.extend([config.GUIStream, sys.stdout]) if args.veryverbose: config.VVFiles.extend([config.GUIStream, sys.stdout]) #modules = [] #aptcache = [] #cbuffer = {} '''root = Tkinter.Tk() App = None def startProg(splash): global modules, aptcache, cbuffer, App spprogn = 6 spprog = 0 def calcPercent(def2 = (spprog, spprogn)): return utilities.calcPercent(*def2) splash.setProgress( calcPercent((spprog, spprogn)), "Loading modules...") modules = [] modulemetas = modloader.getModules() for i in modulemetas: modules.append(modloader.loadModule(i)) spprog += 1 splash.setProgress( calcPercent((spprog, spprogn)), "Parsing configuration...") #buffer1 = utilities.getBuffer(open(relinuxdir + "/relinux.conf")) #buffer2 = configutils.compress(buffer1) #cbuffer = configutils.parseCompressedBuffer(buffer2, relinuxdir + "/relinux.conf") configfiles = [relinuxdir + "/relinux.conf"] for i in range(len(modulemetas)): for x in modules[i].moduleconfig: configfiles.append( os.path.join(os.path.dirname(modulemetas[i]["path"]), x)) cbuffer = configutils.parseFiles(configfiles) config.Configuration = cbuffer configutils.saveBuffer(config.Configuration) \'''for i in configutils.beautify(buffer1): print(i)\''' spprog += 1 splash.setProgress( calcPercent((spprog, spprogn)), "Reading APT Cache...") def aptupdate(op, percent): global minis if percent != None: minis += utilities.floatDivision(percent, 100) splash.setProgress( calcPercent((utilities.floatDivision( minis + captop, aptops) + spprog, spprogn)), "Reading APT Cache... (" + op + ")") def aptdone(op): global minis, captop minis = 0.0 captop += 1 aptcache = aptutil.getCache(aptutil.OpProgress(aptupdate, aptdone)) config.AptCache = aptcache spprog += 1 splash.setProgress( calcPercent((spprog, spprogn)), "Loading the GUI...") App = gui.GUI(root) spprog += 1 splash.setProgress( calcPercent((spprog, spprogn)), "Filling in configuration...") App.fillConfiguration(cbuffer) spprog += 1 splash.setProgress( calcPercent((spprog, spprogn)), "Running modules...") for i in modules: modloader.runModule(i, {"gui": App, "config": cbuffer, "aptcache": aptcache}) spprog += 1 splash.setProgress(calcPercent((spprog, spprogn)), "Launching relinux") splash = gui.Splash(root, startProg) #root.overrideredirect(Tkinter.TRUE) # Coming soon! root.mainloop()''' App = QtGui.QApplication(sys.argv) splash = QtGui.QSplashScreen( QtGui.QPixmap(relinuxdir + "/splash_light.png")) splash.show() App.processEvents() def showMessage(str_): splash.showMessage(str_ + "...", QtCore.Qt.AlignLeft | QtCore.Qt.AlignBottom) App.processEvents() showMessage(_("Loading modules")) modules = [] modulemetas = modloader.getModules() for i in modulemetas: modules.append(modloader.loadModule(i)) showMessage(_("Loading configuration files")) configfiles = [relinuxdir + "/relinux.conf"] for i in range(len(modulemetas)): for x in modules[i].moduleconfig: if "RELINUXCONFDIR" in os.environ: configfiles.append(os.path.join(relinuxdir, x)) else: configfiles.append( os.path.join(os.path.dirname(modulemetas[i]["path"]), x)) cbuffer = configutils.parseFiles(configfiles) config.Configuration = cbuffer configutils.saveBuffer(config.Configuration) logfilename = configutils.getValue(cbuffer["Relinux"]["LOGFILE"]) logfile = open(logfilename, "a") config.EFiles.append(logfile) config.IFiles.append(logfile) config.VFiles.append(logfile) config.VVFiles.append(logfile) logger.logI(tn, logger.I, "===========================") logger.logI(tn, logger.I, "=== Started new session ===") logger.logI(tn, logger.I, "===========================") showMessage(_("Loading APT cache 0%")) def aptupdate(op, percent): global minis if percent: minis = int(percent) showMessage( _("Loading APT cache") + " (" + op + ") " + str(minis) + "%") aptcache = aptutil.getCache(aptutil.OpProgress(aptupdate, None)) config.AptCache = aptcache if not args.nostylesheet: showMessage(_("Loading stylesheet")) App.setStyleSheet(open(mainsrcdir + "/stylesheet.css", "r").read()) showMessage(_("Loading GUI")) gui_ = gui.GUI(App) config.Gui = gui_ showMessage(_("Running modules")) for i in modules: modloader.runModule(i, {}) gui_.show() splash.finish(gui_) exitcode = App.exec_() config.ThreadStop = True logfile.close() sys.exit(exitcode)
def run(adict): global aptcache, page configs = adict["config"]["OSWeaver"] isodir = configutils.getValue(configs[configutils.isodir]) config.ISOTree = isodir + "/.ISO_STRUCTURE/" print(config.ISOTree) config.TempSys = isodir + "/.TMPSYS/" aptcache = adict["aptcache"] ourgui = adict["gui"] from relinux.modules.osweaver import isoutil, squashfs, tempsys, ui_osweaver threads = [] threads.extend(tempsys.threads) threads.extend(squashfs.threads) threads.extend(isoutil.threads) threads_ = utilities.remDuplicates(threads) threads = threads_ '''pagenum = ourgui.wizard.add_tab() page = gui.Frame(ourgui.wizard.page(pagenum)) ourgui.wizard.add_page_body(pagenum, _("OSWeaver"), page) page.frame = gui.Frame(page) page.details = gui.VerticalScrolledFrame(page, borderwidth = 1, relief = Tkinter.SOLID) page.details.output = gui.Label(page.details.interior, text = config.GUIStream.getvalue(), anchor = Tkinter.NW, justify = Tkinter.LEFT) def onWrite(): page.details.output.config(text = config.GUIStream.getvalue()) page.details.canvas.yview_moveto(1.0) config.GUIStream.writefunc.append(onWrite) page.details.output.pack(fill = Tkinter.BOTH, expand = True, anchor = Tkinter.NW, side = Tkinter.LEFT) page.details.pack(fill = Tkinter.BOTH, expand = True, side = Tkinter.BOTTOM, anchor = Tkinter.SW) \'''page.details.buttonstate = True def showDetails(): if page.details.buttonstate: page.details.output.pack(fill=Tkinter.BOTH, expand=True, anchor=Tkinter.NW, side=Tkinter.LEFT) page.showdetails.config(text="<< Hide details") page.details.buttonstate = False else: page.details.output.pack_forget() page.showdetails.config(text="Show details >>") page.details.buttonstate = True page.showdetails = gui.Button(page, text="Show details >>", command=showDetails) page.showdetails.pack(side=Tkinter.BOTTOM, anchor=Tkinter.SW)\''' page.progress = gui.Progressbar(page) page.progress.pack(fill = Tkinter.X, expand = True, side = Tkinter.BOTTOM, anchor = Tkinter.S) page.frame.pack(fill = Tkinter.BOTH, expand = True, anchor = Tkinter.CENTER) page.chframe = gui.VerticalScrolledFrame(page.frame) page.chframe.pack(fill = Tkinter.BOTH, expand = True, anchor = Tkinter.N) page.chframe.boxes = [] page.chframe.dispthreads = [] x = 0 y = 0 usedeps = gui.Checkbutton(page.chframe.interior, text = "Ignore dependencies") usedeps.grid(row = y, column = x) y += 1 label = gui.Label(page.chframe.interior, text = "Select threads to run:") label.grid(row = y, column = x) y += 1 class customCheck(gui.Checkbutton): def __init__(self, parent, *args, **kw): gui.Checkbutton.__init__(self, parent, *args, **kw) self.id = len(page.chframe.boxes) self.ignoreauto = True self.value.trace("w", self.autoSelect) def autoSelect(self, *args): id_ = self.id if self.ignoreauto: self.ignoreauto = False return if self.value.get() < 1: return if len(threads[id_]["deps"]) <= 0 or usedeps.value.get() > 0: return tns = [] for i in threads[id_]["deps"]: tns.append(i["tn"]) for i in range(len(threads)): if threads[i]["tn"] in tns: page.chframe.boxes[i].value.set(1) for i in threads: temp = customCheck(page.chframe.interior, text = i["tn"]) temp.value.set(1) temp.grid(row = y, column = x, sticky = Tkinter.NW) page.chframe.boxes.append(temp) x += 1 if x >= 3: x = 0 y += 1 if x != 0: y += 1 def selBoxes(all_): val = 0 if all_ == None: for i in range(len(threads)): page.chframe.boxes[i].ignoreauto = True if page.chframe.boxes[i].value.get() < 1: page.chframe.boxes[i].value.set(1) else: page.chframe.boxes[i].value.set(0) return if all_: val = 1 for i in range(len(threads)): page.chframe.boxes[i].ignoreauto = True page.chframe.boxes[i].value.set(val) selall = gui.Button(page.chframe.interior, text = "Select all", command = lambda: selBoxes(True)) selall.grid(row = y, column = x) x += 1 selnone = gui.Button(page.chframe.interior, text = "Select none", command = lambda: selBoxes(False)) selnone.grid(row = y, column = x) x += 1 togglesel = gui.Button(page.chframe.interior, text = "Toggle", command = lambda: selBoxes(None)) togglesel.grid(row = y, column = x) y += 1 x = 0 threadsrunninglabel = gui.Label(page.chframe.interior, text = "Threads running:") threadsrunninglabel.grid(row = y, column = x, columnspan = 3) y += 1 page.progress.threads = {} def startThreads(): if os.getuid() != 0: page.isnotroot.pack_forget() page.isnotroot.pack(fill = Tkinter.X) return numthreads = 0 for i in range(len(page.chframe.boxes)): if page.chframe.boxes[i].value.get() < 1: threads[i]["enabled"] = False else: threads[i]["enabled"] = True numthreads += 1 tfdeps = False if usedeps.value.get() > 0: tfdeps = True def postStart(threadid, threadsrunning, threads): txt = "" for i in range(len(threadsrunning)): tn = threadmanager.getThread(threadsrunning[i], threads)["tn"] if i == len(threadsrunning) - 1: if len(threadsrunning) == 1: txt = tn elif len(threadsrunning) == 2: txt += " and " + tn else: txt += ", and " + tn elif i == 0: txt = tn else: txt += ", " + tn threadsrunninglabel.config(text = "Threads running: " + txt) def setProgress(tn, progress): page.progress.threads[tn] = progress totprogress = 0 for i in page.progress.threads.keys(): totprogress += utilities.floatDivision(float(page.progress.threads[i]), 100) page.progress.setProgress(utilities.calcPercent(totprogress, numthreads)) def postEnd(threadid, threadsrunning, threads): tn = threadmanager.getThread(threadid, threads)["tn"] setProgress(tn, 100) postStart(threadid, threadsrunning, threads) runThreads(threads, deps = tfdeps, poststart = postStart, postend = postEnd, threadargs = {"setProgress": setProgress}) # lambda: runThreads(threads) page.button = gui.Button(page.frame, text = "Start!", command = startThreads) page.button.pack() page.isnotroot = gui.Label(page.frame, text = "You are not root!")''' page = {} page["boxes"] = [] page["progress"] = {} page_container = QtGui.QWidget() ui = ui_osweaver.Ui_OSWeaver() ui.setupUi(page_container) ui.notroot.hide() #ui.terminal.hide() class customCheck(QtGui.QCheckBox): def __init__(self, *args): QtGui.QCheckBox.__init__(self, *args) self.ignoreauto = False self.id = len(page["boxes"]) self.value = utilities.eventVar(value=False) self.value.trace("w", self.set) self.clicked.connect(self.toggled_) def toggled_(self, *args): self.setChecked(not self.get()) # Toggle checked state self.value.set( not self.get()) # Set the state that was wanted (not not) def set(self, newvalue): if newvalue == self.get(): return self.setChecked(newvalue) if self.ignoreauto: self.ignoreauto = False elif newvalue: self.autoSelect() def get(self): return self.isChecked() def autoSelect(self): if len(threads[self.id]["deps"]) < 0 or ui.nodepends.isChecked(): return tns = [i["tn"] for i in threads[self.id]["deps"]] for i in range(len(threads)): if threads[i]["tn"] in tns: page["boxes"][i].set(True) x = 0 y = 0 for i in threads: ch = customCheck(i["tn"], ui.threadstorun) ui.gridLayout_2.addWidget(ch, y, x) # No idea why Qt wants Y before X page["boxes"].append(ch) x += 1 if x >= 3: x = 0 y += 1 # Terrible name, but it's just a function that selects/deselects values from "threevalues" # Possible values of "threevalues": # True - Select All # False - Select None # None - Toggle Selected def tripleSel(threevalues): val = False tog = False if threevalues: # Select All val = True elif threevalues is None: tog = True for i in range(len(page["boxes"])): page["boxes"][i].ignoreauto = True if tog: page["boxes"][i].set(not page["boxes"][i].get()) else: page["boxes"][i].set(val) # Run when ui.nodepends is unchecked def ignoreDepends(): for i in range(len(page["boxes"])): if page["boxes"][i].get(): page["boxes"][i].autoSelect() # Start running def startThreads(*args): if os.getuid() != 0: ui.notroot.show() return numthreads = 0 numthreads2 = 0 threadmanager.addOptional(threads) for i in range(len(page["boxes"])): threads[i]["enabled"] = page["boxes"][i].get() if threads[i]["enabled"]: numthreads += 1 if threads[i]["threadspan"] < 0: numthreads2 += threadmanager.cpumax else: numthreads2 += threads[i]["threadspan"] tfdeps = False if ui.nodepends.isChecked(): tfdeps = True def onThreadAdded(threadid, threadsrunning, threads): rt = "Threads running: " c = 0 for i in range(len(threadsrunning)): tn = threadmanager.getThread(threadsrunning[i], threads)["tn"] rt += tn if c + 1 < len(threadsrunning) and len(threadsrunning) > 2: rt += ", " if c + 2 == len(threadsrunning): rt += "and " c += 1 QtCore.QMetaObject.invokeMethod(ui.notroot, "setText", QtCore.Qt.QueuedConnection, QtCore.Q_ARG("QString", rt)) if ui.notroot.isHidden(): QtCore.QMetaObject.invokeMethod(ui.notroot, "show", QtCore.Qt.QueuedConnection) def setProgress(tn, progress): logger.logVV( tn, logger.D, "Setting progress to " + str(progress) + " (from thread " + threading.current_thread().name + ")") #return # Do something here if progress > 100: progress = 100 elif progress < 0: progress = 0 page["progress"][tn] = progress totprogress = 0 for i in page["progress"]: totprogress += utilities.floatDivision( float(page["progress"][i]), 100) QtCore.QMetaObject.invokeMethod( ui.progress, "setValue", QtCore.Qt.QueuedConnection, QtCore.Q_ARG("int", utilities.calcPercent(totprogress, numthreads2))) def onThreadRemoved(threadid, threadsrunning, threads): tn = threadmanager.getThread(threadid, threads)["tn"] setProgress(tn, 100) onThreadAdded(threadid, threadsrunning, threads) for i in page["progress"]: page["progress"][i] = 0 runThreads(threads, deps=tfdeps, poststart=onThreadAdded, postend=onThreadRemoved, threadargs={"setProgress": setProgress}) def onWrite(msg): logger.logVV( tn, logger.D, "Updating terminal (from thread " + threading.current_thread().name + ")") #return ui.terminal.moveCursor(QtGui.QTextCursor.End, QtGui.QTextCursor.MoveAnchor) QtCore.QMetaObject.invokeMethod( ui.terminal, "insertPlainText", QtCore.Qt.QueuedConnection, QtCore.Q_ARG("QString", msg.rstrip() + "\n")) #ui.terminal.setText(config.GUIStream.getvalue()) tripleSel(True) config.GUIStream.writefunc.append(onWrite) ui.selall.clicked.connect(lambda *args: tripleSel(True)) ui.selnone.clicked.connect(lambda *args: tripleSel(False)) ui.togsel.clicked.connect(lambda *args: tripleSel(None)) ui.nodepends.clicked.connect(lambda *args: ignoreDepends() if not ui.nodepends.isChecked() else None) ui.startbutton.clicked.connect(startThreads) ourgui.addTab(page_container, "OSWeaver")