# generated by flconvert
# Don't edit by hand.

from fltk import *

# global object names


class stxinstall:

    def make_window(self):
        global txtHelp
        global btnNext
        global btnPrev
        global btnCancel
        global grpLogo
        global wzdMain
        global grpWelcome
        global grpType
        global btnPartition
        global radCustom
        global radFull
        global radFree
        global grpSelParts
        global chcRoot
        global chcHome
        global chcSwap
        global scrPart
        global pckPart
        global chcFormat
        global grpInstall
        global progress
        global btnInstall
        global grpStatus
        global grpUsers
        global grpFinished

        o_1_0 = Fl_Window(373, 138, 630, 480, """STX Installer""")

        txtHelp = Fl_Text_Display(5, 100, 145, 340)
        txtHelp.box(FL_THIN_DOWN_BOX)

        btnNext = Fl_Button(550, 450, 75, 25, """Next""")
        btnNext.box(FL_THIN_UP_BOX)
        btnNext.label('''Next''')
        btnNext.callback(self.next)   # extra code

        btnPrev = Fl_Button(470, 450, 75, 25, """Previous""")
        btnPrev.box(FL_THIN_UP_BOX)
        btnPrev.label('''Previous''')
        btnPrev.callback(self.prev)   # extra code

        btnCancel = Fl_Button(5, 450, 75, 25, """Cancel""")
        btnCancel.box(FL_THIN_UP_BOX)
        btnCancel.label('''Cancel''')
        btnCancel.callback(self.quit)   # extra code

        grpLogo = Fl_Group(0, -1, 630, 92)
        grpLogo.align(17)
        grpLogo.box(FL_BORDER_BOX)
        grpLogo.end()

        wzdMain = Fl_Wizard(160, 100, 480, 345)

        grpWelcome = Fl_Group(160, 100, 465, 345, """Welcome to the STX Installer! This program will install STX to your computer's hard drive. Throughout the installation process help will be displayed in the box on the left of this window.""")

        grpType = Fl_Group(160, 170, 465, 190, """Please select the type of installation you wish to perform:""")

        btnPartition = Fl_Button(160, 265, 180, 25, """Launch Partitioning Tool""")
        btnPartition.callback(self.launch_partitioner)
        btnPartition.box(FL_THIN_UP_BOX)
        btnPartition.label('''Launch Partitioning Tool''')

        radCustom = Fl_Round_Button(175, 195, 145, 20, """Custom install""")
        radCustom.down_box(FL_ROUND_DOWN_BOX)
        radCustom.callback(self.enable_partitioner)
        radCustom.label('''Custom install''')
        radCustom.setonly()   # extra code
        radCustom.type(FL_RADIO_BUTTON)   # extra code

        radFull = Fl_Round_Button(175, 215, 145, 20, """Full disk install""")
        radFull.down_box(FL_ROUND_DOWN_BOX)
        radFull.callback(self.disable_partitioner)
        radFull.label('''Full disk install''')
        radFull.type(FL_RADIO_BUTTON)   # extra code

        radFree = Fl_Round_Button(175, 235, 145, 20, """Free space install""")
        radFree.down_box(FL_ROUND_DOWN_BOX)
        radFree.callback(self.enable_partitioner)
        radFree.label('''Free space install''')
        radFree.type(FL_RADIO_BUTTON)   # extra code
        grpType.align(21)
        grpType.label('''Please select the type of installation you wish to perform:''')
        self.pagedict["type"] = grpType   # extra code
        grpType.end()
        grpWelcome.align(149)
        grpWelcome.label('''Welcome to the STX Installer! This program will install STX to your computer's hard drive. Throughout the installation process help will be displayed in the box on the left of this window.''')
        self.pagedict["welcome"] = grpWelcome   # extra code
        grpWelcome.end()

        grpSelParts = Fl_Group(160, 100, 466, 345, """Select the partitions you would like STX to use. You can change your partitions by launching the partitioning tool on the previous page.""")
        chcRoot = Fl_Choice(275, 315, 350, 20, "Root partition: ")
        chcHome = Fl_Choice(275, 340, 350, 20, "Home partition: ")
        chcSwap = Fl_Choice(275, 365, 350, 20, "Swap partition: ")

        o_4_3 = Fl_Check_Button(165, 420, 190, 20, """Preserve home partition""")
        o_4_3.deactivate()
        o_4_3.down_box(FL_DOWN_BOX)
        o_4_3.align(24)
        o_4_3.label('''Preserve home partition''')

        o_4_4 = Fl_Group(165, 185, 460, 125, """Partitions:""")

        scrPart = Fl_Scroll(165, 185, 460, 110)

        pckPart = Fl_Pack(167, 187, 455, 106)
        pckPart.resizable(pckPart.this)
        pckPart.spacing(2)   # extra code
        pckPart.end()
        scrPart.box(FL_THIN_DOWN_FRAME)
        scrPart.type(FL_VERTICAL)   # extra code
        scrPart.end()
        o_4_4.align(5)
        o_4_4.box(FL_FLAT_BOX)
        o_4_4.label('''Partitions:''')
        o_4_4.end()
        chcFormat = Fl_Choice(275, 390, 350, 20, "Format: ")
        grpSelParts.align(149)
        grpSelParts.label('''Select the partitions you would like STX to use. You can change your partitions by launching the partitioning tool on the previous page.''')
        grpSelParts.end()

        grpInstall = Fl_Group(160, 100, 470, 345, """This is your last chance to change your options. If you do wish to change them press the "Previous" button. When you are certain that they are correct press the "Begin Installation" button.""")

        progress = Fl_Progress(165, 255, 450, 25)
        progress.deactivate()
        progress.selection_color(136)
        progress.box(FL_PLASTIC_UP_BOX)

        btnInstall = Fl_Button(165, 170, 200, 25, """Begin Installation""")
        btnInstall.down_box(FL_THIN_DOWN_BOX)
        btnInstall.box(FL_THIN_UP_BOX)
        btnInstall.label('''Begin Installation''')
        btnInstall.callback(self.install)   # extra code

        grpStatus = Fl_Group(160, 215, 430, 35, """Status: Waiting for the installation to begin.""")
        grpStatus.deactivate()
        grpStatus.align(21)
        grpStatus.label('''Status: Waiting for the installation to begin.''')
        grpStatus.end()
        grpInstall.align(149)
        grpInstall.label('''This is your last chance to change your options. If you do wish to change them press the "Previous" button. When you are certain that they are correct press the "Begin Installation" button.''')
        grpInstall.end()

        grpUsers = Fl_Group(160, 100, 470, 345, """STX is now installed on your computer. As the last stage in the installation you need to create a user account and set the root password (root is the administration account).""")

        o_4_0 = Fl_Input(295, 175, 150, 25, """Username:""")
        o_4_0.label('''Username:''')

        o_4_1 = Fl_Input(295, 235, 150, 25, """Password:""")
        o_4_1.label('''Password:''')

        o_4_2 = Fl_Input(295, 265, 150, 25, """Confirm Password:""")
        o_4_2.label('''Confirm Password:''')

        o_4_3 = Fl_Input(295, 205, 150, 25, """Full Name:""")
        o_4_3.label('''Full Name:''')

        o_4_4 = Fl_Input(295, 315, 150, 25, """Root Password:""")
        o_4_4.label('''Root Password:''')

        o_4_5 = Fl_Input(295, 345, 150, 25, """Confirm Password:""")
        o_4_5.label('''Confirm Password:''')
        grpUsers.align(145)
        grpUsers.label('''STX is now installed on your computer. As the last stage in the installation you need to create a user account and set the root password (root is the administration account).''')
        grpUsers.end()

        grpFinished = Fl_Group(160, 150, 470, 295, """The installation is now complete! Restart your computer to enter your new STX system.""")
        grpFinished.align(177)
        grpFinished.labelsize(18)
        grpFinished.label('''The installation is now complete! Restart your computer to enter your new STX system.''')
        grpFinished.end()
        wzdMain.box(FL_FLAT_BOX)
        o_1_0.label('''STX Installer''')
        o_1_0.end()

        return o_1_0

    def next(self, button):
        global currentPage
        wzdMain.next()
        if currentPage == 0:
        	self.populate_partitions()
        	btnPrev.activate()
        	print radFull.value()
        	if radFull.value() == 1 or radFree.value() == 1:
        		#Go forward 2 pages
        		wzdMain.next()
        		currentPage += 1
        elif currentPage == 1:
        	btnNext.deactivate()
        elif currentPage == 3:
        	btnNext.label("Finish")
        elif currentPage == 4:
        	self.quit(button)
        currentPage += 1
        self.load_help()


    def prev(self, button):
        global currentPage
        wzdMain.prev()
        if currentPage == 1:
        	btnPrev.deactivate()
        elif currentPage == 2:
        	btnNext.activate()
        currentPage -= 1
        self.load_help()


    def quit(self, button):
        if self.parser:
        	self.parser.stop()
        	self.parser.join()
        sys.exit(0)


    def __init__(self):
        global sys, os, re, currentPage
        import sys, os, re
        self.parser = None
        from ConfigParser import SafeConfigParser
        self.basedir = "./"
        self.pagedict = dict()
        
        if os.geteuid()!=0:
        	fl_message("Sorry, you need root permissions to use this program.")
        	return
        
        self.winMain = self.make_window()
        imgLogo = Fl_PNG_Image(self.basedir + "stx.png")
        grpLogo.image(imgLogo)
        imgSmiley = Fl_PNG_Image(self.basedir + "smiley.png")
        grpFinished.image(imgSmiley)
        
        self.help = SafeConfigParser()
        self.help.read(self.basedir + "help.conf")
        bufHelp = Fl_Text_Buffer(1000)
        txtHelp.buffer(bufHelp)
        txtHelp.wrap_mode(1, 0)
        
        currentPage = 0
        btnPrev.deactivate()
        self.load_help()
        
        self.winMain.show(sys.argv)


    def load_help(self):
        global currentPage
        try:	
        	helppage = self.help.get(str(currentPage), "text")
        except:
        	helppage = "Sorry, no help is available for this page."
        bufHelp = txtHelp.buffer()
        bufHelp.replace(0, 1000, helppage)


    def launch_partitioner(self, button):
        os.popen("partitionmorpher")


    def enable_partitioner(self, button):
        btnPartition.activate()


    def disable_partitioner(self, button):
        btnPartition.deactivate()


    def populate_partitions(self):
        self.rootlookup = []
        self.homelookup = ["Root"]
        self.swaplookup = ["None"]
        self.formatlookup = ["ext3", "ext2", "reiserfs"]
        self.partbuttons = []
        tooltips = []
        
        pckPart.clear()
        
        chcRoot.callback(self.chcPart_selected, "Root")
        chcHome.callback(self.chcPart_selected, "Home")
        chcSwap.callback(self.chcPart_selected, "Swap")
        
        chcHome.add("Root")
        chcSwap.add("None")
        for format in self.formatlookup:
        	chcFormat.add(format)
        
        disklist = os.popen("cat /proc/diskstats")
        partitions = disklist.readlines()
        diskPattern = re.compile("[hs]d.[0-9]+")
        prevDisk = None
        
        rootSet = False
        swapSet = False
        
        for partition in partitions:
        	partition = diskPattern.findall(partition)
        	if len(partition) == 0:
        		continue
        	partition = partition[0]
        	partSize = os.popen("sfdisk -sn /dev/" + partition).readline()
        	partSize = (int(partSize) / 1024.0) / 1024
        	partSizestr = str(round(partSize, 2))
        	#Incase of screwed up partition tables
        	if partSizestr == "0.0":
        		continue
        	partFormat = os.popen("sfdisk -cn /dev/" + partition[:3] + " " + partition[3:]).readline()
        	partFormat = int(partFormat, 16)
        	if partition[:2] == "sd":
        		partitionName = "External Disk "
        	else:   
        		partitionName = "Disk "
        	partitionName += str(ord(partition[2:3]) - 96) + "; Partition " + partition[3:] + " (" + partition + ", size: " + partSizestr + "GiB)"
        	if partFormat == 131:
        		self.rootlookup.append(partition)
        		chcRoot.add(partitionName)
        		chcHome.add(partitionName)
        	elif partFormat == 130:
        		self.swaplookup.append(partition)
        		chcSwap.add(partitionName)
        
        	#Handle pretty partition display
        	if prevDisk != partition[:3]:
        		prevDisk = partition[:3]
        		diskSize = os.popen("sfdisk -sn /dev/" + partition[:3]).readline()
        		diskSize = (int(diskSize) / 1024.0) / 1024
        		diskSize = round(diskSize, 2)
        		pack = Fl_Pack(0, 0, -1, 25)
        		pack.type(FL_HORIZONTAL)
        		pack.spacing(2)
        		pckPart.add(pack)
        	width = partSize / diskSize * pckPart.w() * 0.50
        	width = int(width)
        	if width < 85:
        		width = 85
        
        	if partFormat == 130 or partFormat == 131:
        		btnPart = Fl_Menu_Button(0, 0, width, 25, partition)
        		btnPart.textsize(10)
        	else:
        		#Non linux partition, no menu
        		btnPart = Fl_Button(0, 0, width, 25, partition)
        	btnPart.box(FL_PLASTIC_UP_BOX)
        	btnPart.labelsize(10)
        	btnPart.callback(self.btnPart_selected, partition)
        	if partFormat == 130:
        		btnPart.color(fl_rgb_color(0, 200, 0))
        		btnPart.selection_color(fl_rgb_color(0, 255, 0))
        		btnPart.add("Use As Swap")
        		format = "Linux Swap"
        		if not swapSet:
        			#Select first Linux-Swap partition as swap
        			btnPart.copy_label(partition + " (Swap)")
        			swapSet = True
        	elif partFormat == 131:
        		btnPart.color(fl_rgb_color(0, 0, 200))
        		btnPart.selection_color(fl_rgb_color(0, 0, 255))
        		format = "Linux"
        		btnPart.add("Use As Root")
        		btnPart.add("Use As Home")
        		btnPart.add("Use As Both")
        		if not rootSet:
        			#Select first Linux partition as root+home
        			btnPart.copy_label(partition + " (Root+Home)")
        			rootSet = True
        
        	else:
        		btnPart.color(fl_rgb_color(100, 0, 0))
        		btnPart.selection_color(fl_rgb_color(126, 0, 0))
        		format = "Non-Linux"
        	tooltips.append("Size: " + partSizestr + "GB | Type: " + format)
        	btnPart.tooltip(tooltips[-1])
        	self.partbuttons.append(btnPart)
        	pack.add(self.partbuttons[-1])
        
        #Set sensible defaults
        chcRoot.value(0)
        chcHome.value(0)
        chcSwap.value(len(self.swaplookup) - 1)
        chcFormat.value(0)


    def btnPart_selected(self, button, partition):
        if button.color() == fl_rgb_color(0, 0, 200) or button.color() == fl_rgb_color(0, 0, 255): # Linux
        
        	if button.value() == 0:
        		button.label(partition + " (Root)")
        		#Set chcRoot to match
        		for i in range(0, len(self.rootlookup)):
        			if self.rootlookup[i] == partition:
        				chcRoot.value(i)
        				break;
        
        	if button.value() == 1:
        		button.label(partition + " (Home)")
        		#Set chcHome to match
        		for i in range(0, len(self.homelookup)):
        			if self.homelookup[i] == partition:
        				chcHome.value(i)
        				break;
        
        	if button.value() == 2:
        		button.label(partition + " (Root+Home)")
        		#Set chcRoot and chcHome to match
        		for i in range(0, len(self.rootlookup)):
        			if self.rootlookup[i] == partition:
        				chcRoot.value(i)
        				chcHome.value(0)
        				break;
        
        elif button.color() == fl_rgb_color(0, 200, 0) or button.color() == fl_rgb_color(0, 255, 0): # Swap
        	if button.value() == 0:
        		button.label(partition + " (Swap)")
        		#Set chcSwap to match
        		for i in range(0, len(self.swaplookup)):
        			if self.swaplookup[i] == partition:
        				chcSwap.value(i)
        				break;


    def install(self, button):
        btnInstall.deactivate()
        btnPrev.deactivate()
        btnNext.deactivate()
        #btnCancel.deactivate()
        grpStatus.activate()
        progress.activate()
        grpStatus.label("Status: Beginning installation...")
        
        from shlexinstall import Parser
        self.parser = Parser("install.sh", self.update_display)
        self.parser.variables["$ROOT"] = self.rootlookup[chcRoot.value()]
        self.parser.variables["$HOME"] = self.homelookup[chcHome.value()]
        self.parser.variables["$SWAP"] = self.swaplookup[chcSwap.value()]
        self.parser.variables["$FORMAT"] = self.formatlookup[chcFormat.value()]
        self.parser.start()


    def update_display(self, text):
        import re
        progCheck = re.compile("\\(\\d+\\%\\)$")
        progMatch = progCheck.search(text)
        if progMatch:
        	prog = progMatch.group()
        	#Get integer from progress string
        	prog = int(prog[1:-2])
        	progress.value(prog)
        	grpStatus.label("Status: " + text)
        	if prog == 100:
        		btnNext.activate()


    def chcPart_selected(self, choice, type):
        if type == "Root":
        	partition = self.rootlookup[choice.value()]
        elif type == "Home":
        	partition = self.homelookup[choice.value()]
        elif type == "Swap":
        	partition = self.swaplookup[choice.value()]
        
        for button in self.partbuttons:
        	if button.label()[:len(partition)] == partition:
        		if (type == "Root" and (chcHome == "Root" or chcHome.value() == chcRoot.value() + 1)):
        			type = "Root+Home"
        		button.label(partition + " (" + type + ")")


# end of class stxinstall


