User:Fleeting Frames/UnsuspendSelectedBuilding

From Dwarf Fortress Wiki
Jump to navigation Jump to search

Save as UnsuspendSelectedBuilding.lua into /hack/scripts folder.

--auto-unsuspend selected building.

local bld = dfhack.gui.getSelectedBuilding(true)
if not bld then qerror("Can't find selected in the ui.") end
if not bld.construction_stage then qerror("Building " .. utils.getBuildingName(bld) .. " isn't constructed in stages.") end
utils = require 'utils';


local function repeatfunction(rfunc)
	--repeats a function every 10 frames, until the function returns false or nil
	local myrfunc
	
	myrfunc = function ()
	  timeoutid = dfhack.timeout(10, "ticks", function(options)
		if rfunc() then myrfunc() end
	   end)
	end
	
	myrfunc()
end

function AnnounceStart(bld)
		dfhack.gui.makeAnnouncement(
			df.announcement_type.JOB_OVERWRITTEN,
			{D_DISPLAY = true},
			xyz2pos(bld.centerx,bld.centery, bld.z),
			"Started unsuspending " .. utils.getBuildingName(bld) .. ".",
			COLOR_GREEN,
			true)
end

function AnnounceEnd(bldName)
		dfhack.gui.makeAnnouncement(
			df.announcement_type.QUOTA_FILLED,
			{D_DISPLAY = true},
			xyz2pos(bld.centerx,bld.centery, bld.z),
			"Ended building " .. bldName .. ".",
			COLOR_GREEN,
			true)
end

function getConstructionJob(building)
	for _, attachedjob in ipairs(building.jobs) do
		if attachedjob.job_type == 68 then
			return attachedjob
		end
	end
end

watchedbuildings = watchedbuildings or {}

if (bld and not watchedbuildings[tostring(bld)]) then
	if bld.flags.exists == false then
		local bldjob=getConstructionJob(bld)
		if bldjob then
			local myBldStr=tostring(bld)
			local myBldName = utils.getBuildingName(bld)	--bld is lost on constructions, which means ending the loop would segfault due nil
			if(watchedbuildings[myBldStr] ~= false) then --don't set repeatfunc when there's already one
				repeatfunction(
					function()
						if(watchedbuildings[myBldStr]) then
							local bld = df.building.find(watchedbuildings[myBldStr])
							local bldjob = bld and getConstructionJob(bld)
							if bld and bldjob and bld.flags.exists == false then
								bldjob.flags.suspend=false
								return true
							end
						end
						print("ending..")
						watchedbuildings[myBldStr] = nil --if didn't return, end is at hand
						AnnounceEnd(myBldName) 
					end
				)
			end
			watchedbuildings[tostring(bld)]=bld.id
			AnnounceStart(bld)
		end
	end
elseif (bld and watchedbuildings[tostring(bld)]) then
	watchedbuildings[tostring(bld)] = false
	dfhack.gui.makeAnnouncement(
		df.announcement_type.JOB_OVERWRITTEN,
		{D_DISPLAY = true},
		xyz2pos(bld.centerx,bld.centery, bld.z),
		"Stopped unsuspending " .. utils.getBuildingName(bld) .. ".",
	COLOR_GREEN,
	true)
end