local function newPointLight()
	scene_newEntity(ctx.viewport.room, {
		position = editor.lastIntersect + editor.intersectNormal * 50,
		light = {
			isLight = true,
			enabled = true,
			strength = 0.5,
			range = 300,
			color = { r = 1, g = 1, b = 1 },
		},
	})
end

local function newPlayerSpawn()
	editor_newEntity(lume.concat(editor.mouseLocalDrop, { spawn = "player" }))
end

local function newSymbolContext()
	return {
		{
			name = "New",
			func = function()
				editor_drawNewImage("camera")
			end,
			col = { a = 0.5 },
			-- size = -1,
			sub = "Drawing",
      subHeight = 180,
			items = lume.concat({
				{
					{
						name = "Other",
						align = "center",
						subitems = {
							{ name = "Player spawn", func = newPlayerSpawn },
							{ name = "Actor spawn", func = nothing },
							{ name = "Point of interest", func = newPlayerSpawn },
							{ name = "Point light", func = newPointLight },
							{ name = "Spot light", func = nothing },
							{ name = "Directional light", func = nothing },
						},
					},
					{
						name = "Symbol",
						align = "center",
						subitems = {
							{
								name = "Resolution: ",
								slider = {
									target = editor,
									style = "pct",
									prop = "drawingResolution",
									min = 1,
									max = 0.2,
									round = 0.1,
									noval = true,
								},
								update = function(x)
									x.name = "Resolution: " .. round(1.2 - editor.drawingResolution, 2)
								end,
							},
							{
								name = "No Transform",
								func = function()
									editor_drawNewImage()
								end,
							},
							{
								name = "Facing Camera",
								func = function()
									editor_drawNewImage("camera")
								end,
							},
							{
								name = "Facing Camera (XZ only)",
								func = function()
									editor_drawNewImage("camera x")
								end,
							},
							editor.modelHovered and {
								name = "Facing Surface ",
								func = function()
									editor_drawNewImage("surface")
								end,
							} or {},
						},
					},
					{
						name = "Shape",
						align = "center",
						subitems = {
							{
								name = "Cube",
								func = function()
									editor_createNewModel("Cube")
								end,
							},
							{
								name = "Cyclinder",
								func = function()
									editor_createNewModel("Cyclinder")
								end,
							},
							{
								name = "Sphere",
								func = function()
									editor_createNewModel("Sphere")
								end,
							},
							editor.debug.draw_tests and {
								name = "test",
								func = function()
									editor_createNewModel("test")
								end,
							} or nil,
						},
					},
				},
			}),
		},
	}
end

local function printGlobals()
	local t = {}
	for k, v in pairs(_G) do
		if type(v) == "function" then
			table.insert(t, k)
		end
	end
	table.sort(t)
	for k, v in ipairs(t) do
		print(k, v)
	end
	print("global functions:", #t)

	local i = 0
	for k, v in pairs(_G) do
		if type(v) ~= "function" and not stdLib[k] then
			i = i + 1
			print(i, k, v)
		end
	end

	if _ASSIGNS then
		for k, info in pairs(_ASSIGNS) do
			print(
				ansicolors(
					"%{redbg} "
						.. string.format(
							"strict: %s:%s: write to undeclared variable: %s",
							tostring(info.short_src),
							tostring(info.currentline),
							k
						)
						.. " %{reset}"
				)
			)
		end
	end
end

local function debugOptions()
	return {
		editor_makeToggle(editor, "show_help"),
		editor_makeToggle(editor, "autoSaveEnabled"),
		editor_makeToggle(editor.debug, "no_scripts"),
		editor_makeToggle(editor.debug, "wireframe"),
		editor_makeToggle(editor.debug, "no_lights"),
		editor_makeSlider(
			editor.debug,
			{ "num_test_lights", "test_lights", "test_lights" },
			{ mim = 1, max = 16, round = 1 }
		),
		editor_makeToggle(editor.debug, "move_testlights"),
		editor_makeToggle(editor.debug, "soft_lights"),
		editor_makeToggle(editor.debug, "single_channel_lights"),
		editor_makeToggle(editor.debug, "draw_shadow_maps"),
		editor_makeToggle(editor.debug, "no_icons"),
		editor_makeToggle(editor.debug, "no_links"),
		editor_makeToggle(editor.debug, "draw_tests"),
		editor_makeToggle(editor.debug, "trace_camera"),
		editor_makeToggle(editor.debug, "trace_mouse_intersect"),
		editor_makeToggle(editor.debug, "trace_mesh_times"),
		editor_makeToggle(editor.debug, "draw_ground_planes"),
		editor_makeToggle(editor.debug, "draw_frame_bounds"),
		editor_makeToggle(editor.debug, "hide_terrain"),
		editor_makeToggle(editor.debug, "bounding_boxes"),
		editor_makeToggle(editor.debug, "force_build"),
		editor_makeToggle(editor.debug, "rebuild_on_focus"),
		editor_makeToggle(editor.debug, "trace_active_rooms"),
		editor_makeToggle(editor.debug, "trace_loaded_images"),
		editor_makeToggle(editor.debug, "feet"),
		editor_makeToggle(editor.debug, "show_patterns"),
		editor_makeToggle(editor.debug, "dither_lights"),
		editor_makeToggle(editor.debug, "anti_alias"),
		editor_makeToggle(editor.debug, "bench"),
		editor_makeToggle(editor.debug, "print_globals", { click = printGlobals }),
	}
end

local function projectOptions()
	local projects = {}

	for f, project in pairs(config.projects) do
		if engine.project ~= project.id then
			table.insert(projects, {
				{
					name = project.name,
					func = function()
						engine_loadProject(project.id)
					end,
				},
				{
					name = "",
					size = 0.15,
					tip = "rename",
				},
			})
		end
	end
	
  -- table.insert(projects, {
	-- 	name = "Exit to start screen",
	-- 	func = engine_exit,
	-- 	warning = "open",
	-- })
  table.insert(projects, {
    name = "Open New File",
    func = function()engine.callNew = true end
  })
	-- table.insert(projects,{
	--  {name="New Game",func=function() newProject("Untitled Game")      end,col=colors.green},
	--  {name="New Anim",func=function() newProject("Untitled Anim",true) end,col=colors.green}
	-- })
	return projects
end

local function moreContextOptions()
	return {
		{ name = "More",
			size = 0.01,
			subWidth = 180,
      subHeight = 200,
			sub = "Projects",
			items = lume.concat({
				{
					{ name = "Projects", size = 1, subitems = projectOptions() },
					{ name = "Debug", size = 1, subitems = debugOptions() },
				},
			}),
		},
	}
end

local function newSymbol(props)
	editor.mouseLocalDrop.dropped = false
	return editor_newEntity(load_newSymbol().key, editor.mouseLocalDrop)
end

local function startDrawing()
	if not altDown and not mouse_in(animatePanel) and editor.stageHovered then
		mouse_pushClick(function()
			game.levelClicked = true
			animatePanel.drawn = 0
		end)
	end
end

local function startSelect()
	if (altDown==false) and editor.stageHovered and editor.hoveredEntity == nil and editor.state == "Normal" then
		mouse_pushClick(function()
			editor_pushUndoState("Start Selection")
			editor.forceProject = true
			game.levelClicked = true
			lume.clear(shiftDown and editor.selectedEntities or {})
			editor.numSelected = #editor.selectedEntities
			editor.selectBounds = {
				x = mouse.x,
				y = mouse.y,
				x1 = mouse.x / game.resolution,
				y1 = mouse.y / game.resolution,
				x2 = mouse.x,
				y2 = mouse.y,
				h = 2,
				w = 2,
			}
		end)
	end
end

local function startPan(b)
	local cam = editor.viewport.camera
	editor.panStarted = true
	cam.stored = { x = cam.pos.x, y = cam.pos.y, z = cam.pos.z, b = b or 1 }
	cam.storedOffset = { x = cam.offset.x, y = cam.offset.y, z = cam.offset.z, b = b or 1 }
	editor.state = "Panning"
end



function editor_drawNewImage(mode)
	local entity = newSymbol()
	scene_orientEntity(entity, mode)
	editor_openAnimatePanel(entity, true)
	animatePanel.newImage = true
	animatePanel.blankAnim = true
	animatePanel.f.blank = true
	return entity
end

function editor_clickStage()
	if input_keyDown("space") then
		mouse_pushClick(function()
			startPan()
		end)
	else
		if editor.currentTool == "Select" then
			startSelect()
		elseif editor.currentTool == "Brush" then
			startDrawing()
		end
	end
end

function editor_startDrag(entity, setpos)
	lume.clear(editor.selectedEntities)
	editor.selectedEntities[1] = entity
	editor.state = "Transforming"
	editor.gizmo.dragging = true
  editor.gizmo.cmdDown = false
	entity.selected = true
	editor.gizmo.name = "move"
	return entity
end

function editor_releaseMouse()

	if editor.transforming then
		editor_applyTransforms()
		editor.gizmo.translation = vec3(0, 0, 0)
	end

	animatePanel.brushPrev = nil

	game.levelClicked = false
	game.draggingPlayer = false

	editor.gizmo.dragging = false
	editor.gizmo.rotating = false
	editor.gizmo.scaling = false
	editor.gizmo.sorting = false
  editor.gizmo.current = nil 

	editor.gizmo.draggings = {}
	editor.forceProject = false

	-- REVERT EDIT MODE
	if multicheckOR(editor.state, { "Dragging", "Panning", "Resizing Panel", "Transforming", "Viewport" }) then
		editor.state = "Normal"
	end
	if editor.state == "Normal" and not animatePanel.tool == "brush" then
		mouse_setCursor(defaultCursor)
	end

	-- DROP IN NEW ITEM
	for i, item in ipairs(galleryPanel.selected) do
		if editor.stageHovered and editor.droppingItem and load_getSymbol(item.key) ~= nil then
			if not mouse_in(sidebar) then
				editor_newEntity(item.key, editor.mouseLocalDrop)
			end
		end
	end
	editor.droppingItem = false
end

function editor_click()
	if editor.preTransform or mouse.locked or not editor.stageHovered then
		return
	end

	mouse_set(function()
		editor.clickedModel = editor.modelHovered
		if ctx.viewport.room and not (editor.state == "Panning" or input_keyDown("space")) then
      local selected = #editor.selectedEntities
      if altDown then

			elseif cmdDown then
				if editor.hoveredEntity ~= nil then
					if scene_entitySelected(editor.hoveredEntity) then
						editor_deleteFromSelectedEntities(editor.hoveredEntity)
					else
						table.insert(editor.selectedEntities, editor.hoveredEntity)
					end
				end
      elseif shiftDown then 
        if not scene_entitySelected(editor.hoveredEntity) then
          table.insert(editor.selectedEntities, editor.hoveredEntity)
        end
			else
				lume.clear(editor.selectedEntities)
				if editor.hoveredEntity ~= nil then
					editor_pushUndoState("Start Drag")
					editor_startDrag(editor.hoveredEntity)
				end
			end
      
		end
	end)

	mouse_setR(function()
		if mouse.down.L then
			return
		end
		editor.clickedModel = editor.modelHovered
		local props = {}
		editor_checkForSimples()
		local items = {}
		if not ((editor.state == "Normal" or not editor.transforming) and not input_keyDown("space")) then
			return
		end

		local room = editor.viewport.room

		if (editor.viewHovered or not ctx.pageView) and not animatePanel.open then
      local item = editor_contextRooms()
			if ctx.pageView then
        item.name = "Enter Room"
        item.func =  function() game_enterRoom(editor.viewport.room) end
			else
				item.name = "Exit Room"
        item.func = game_exitRoom
			end
      table.insert(items,item)
		end
    print("mouseR")
		if editor.state == "Transforming" then
			editor.hoveredEntity = editor.selectedEntities[1]
		end

		if editor.hoveredEntity ~= nil then
			local entity = editor.hoveredEntity

			if not anySelectedSimple then
				if #editor.selectedEntities == 0 then
					table.insert(editor.selectedEntities, entity)
				end

				if
					(scene_entitySelected(entity) and #editor.selectedEntities == 1)
					or #editor.selectedEntities == 0
				then
					table.insert(items, {
						name = "Properties",
						items = {
							{
								{
									name = "Name: " .. entity.name,
									tip = "Instance of: " .. entity.symbol.name,
									func = function()
										editor_renameInstance(entity)
									end,
								},
								editor_colorSquare(entity, "color"),
							},
							{
								name = "Reset Transform",
								func = function()
									editor_resetTransform()
								end,
							},
							editor_makeToggle(entity, "gravity"),
							editor_makeToggle(entity, "visible"),
							editor_makeToggle(entity, "static"),
							editor_makeToggle(
								entity.light,
								{ "strength", "enabled" },
								{ name = "light", colors = { "color" }, parent = entity },
								entity.light.isLight
										and {
											editor_makeModes(
												entity.light,
												"type",
												{ "point", "spot", "direction" },
												{ align = "left" }
											),
											editor_makeSlider(entity.light, "range", { min = 25, max = 2500, pow = 2 }),
											editor_makeToggle(entity.light, "shadow", nil, {
												editor_makeToggle(
													entity.light,
													{ "softness", "soft" },
													{ name = "softness" }
												),
												--[[editor_makeToggle(entity.light,"cache"),]]
											}),
											editor_makeToggle(entity.light, "lock", { name = "lock target" }),
											editor_makeSlider(
												entity.light,
												"falloff",
												{ name = "Spotlight Falloff", min = 0.001 }
											),
											editor_makeSlider(
												entity.light,
												"aperture",
												{ name = "Spotlight Aperture", min = 5, max = 90 }
											),
										}
									or {}
							),
						},
					})

					if not (load_isLoading(entity.key) or entity.light.isLight) then
						table.insert(items, {
							{
								name = animatePanel.instance and "Resume Drawing" or "Graphics",
								func = animatePanel.instance and function()
									animatePanel.open = true
								end or function()
									editor_openAnimatePanel(entity, true, entity.default)
								end,
							},
							{
								name = "···",
								col = { a = 0.5 },
								size = -1,
								items = not animatePanel.instance and editor_contextAnims(entity) or nil,
							},
						})
					end
					table.insert(items, editor_contextScripts(entity))
				end
			end

			if pathsPanel.open and (#editor.selectedEntities == 0 or #editor.selectedEntities == 1) then
				editor.selectedEntities = { entity }
				if
					pathsPanel.mode == "ramps" and (entity.pointIndex == #pathsPanel.points or entity.pointIndex == 1)
				then
					editor.selectedEntities = { entity }

					if #pathsPanel.points > (pathsPanel.mode == "floors" and 3 or 2) then
						table.insert(items, {
							name = "Delete",
							func = function()
								editor_deleteSelected()
							end,
							col = { r = 0.8, g = 0.2, b = 0.2, a = 0.4 },
						})
					end
				elseif #pathsPanel.points > (pathsPanel.mode == "floors" and 3 or 2) then
					editor_deleteSelected()
				end
			elseif scene_entitySelected(entity) then
				--table.insert(items, 2,{ name="Copy",  func = function()   editor_copyEntities()   end } )
				table.insert(items, {
					name = "Delete",
					func = function()
						editor_deleteSelected()
					end,
					col = { r = 0.8, g = 0.2, b = 0.2, a = 0.4 },
				})
			end
		-- SET PARENT SOMEWHERE HERE
		else
			local clickPage = ctx.pageView and editor.viewHovered == nil and not animatePanel.open

			if clickPage then
				
        table.insert(items, editor_contextRooms(ctx.page))

				-- local litems = {}
				-- for l,level in pairs(ctx.levels) do
				--   table.insert(litems,{
				--     {
				--       size=8,
				--       name=ctx.levels[level.key].name ,
				--       update=function(x)
				--         x.name = ctx.levels[level.key].name
				--         x.col  = game.level.key==level.key and {r=0.4,g=0.4,b=0.4,a=0.5} or {a=0}
				--       end,
				--       func=function() game_enterGame(level.key) return "" end
				--     },
				--     {
				--       size=1,
				--       col = {a=120},
				--       name  = "···",
				--       func  = function() namer_typeString("Rename Level",ctx.levels[level.key].name,getMouse(),function(x) ctx.levels[level.key].name=x end) return "rename" end
				--     }
				--   })
				-- end
				-- table.insert(litems,{name="New Level", col = {r=0.2,g=0.7,b=0.3,a=0.3}, func=function()
				--   namer_typeString("New Level","",{x=mouse.x,y=mouse.y},function(x)
				--     engine_addLevel(x,w)
				--     local selected = contextMenu.selected
				--     editor.openContextLevels()
				--     contextMenu.selected = selected
				--   end)
				--   return "new"
				-- end})
				-- table.insert(items, { name="Levels…",items=litems})

				table.insert(items, {
					name = "New Room",
					func = function()
						editor_newRoom(ctx.views, true)
					end,
				})
			else
				lume.clear(editor.selectedEntities)
				if #editor.selectedEntities == 0 and not (pathsPanel.open or animatePanel.open) then
					if editor.modelHovered then
						if editor.modelHovered.mode then
							table.insert(items, {
								{
									name = "Edit " .. capFirst(editor.modelHovered.mode:sub(1, -2)),
									func = function()
										paths_openPanel(room, editor.modelHovered.id, editor.modelHovered.mode, room)
									end,
									subWidth = 220,
                  subHeight = 250,
									items = paths_contextPath(room, editor.modelHovered.mode, editor.modelHovered.id),
								},
							})
						end

						if
							editor.modelHovered.mode
							and not (
								editor.modelHovered.isFloor
								or editor.modelHovered.isRoof
								or editor.modelHovered.isRamp
							)
						then
							local sub = {}
							table.insert(
								sub,
								editor_makeToggle(
									room[editor.modelHovered.mode][editor.modelHovered.id].points[editor.modelHovered.index],
									"walled",
									{
										click = function()
											print("REFRESH")
											pathsPanel.changed = { "floors", editor.modelHovered.id }
										end,
									}
								)
							)

							if editor.roomLink then
								table.insert(sub, {
									name = "Stop Link",
									func = function()
										plan_stopLink({
											room = ctx.viewport.key,
											type = "edge",
											mode = editor.modelHovered.mode,
											id = editor.modelHovered.id,
											index = editor.modelHovered.index,
										})
									end,
								})
							else
								table.insert(sub, {
									name = "Start Link",
									func = function()
										plan_startLink({
											room = ctx.viewport.key,
											type = "edge",
											mode = editor.modelHovered.mode,
											id = editor.modelHovered.id,
											index = editor.modelHovered.index,
										})
									end,
								})
							end
							if editor.modelHovered.isWall then
								table.insert(sub, {
									{
										name = "Cut Rect",
										func = function()
											floors_startWallCut(
												room[editor.modelHovered.mode][editor.modelHovered.id],
												editor.modelHovered.index,
												"rect"
											)
										end,
									},
									{
										name = "Cut Circle",
										func = function()
											floors_startWallCut(
												room[editor.modelHovered.mode][editor.modelHovered.id],
												editor.modelHovered.index,
												"circ"
											)
										end,
									},
								})
								table.insert(sub, {
									name = "Cut Out Multi",
									func = function()
										floors_startWallCut(
											room[editor.modelHovered.mode][editor.modelHovered.id],
											editor.modelHovered.index,
											"rect",
											true
										)
									end,
								})

								local wallCuts = 0

								for c, cut in ipairs(room[editor.modelHovered.mode][editor.modelHovered.id].cuts) do
									if cut.index == editor.modelHovered.index then
										wallCuts = wallCuts + 1
									end
								end

								if wallCuts > 0 then
									table.insert(sub, {
										name = "Remove Cuts On Wall (" .. wallCuts .. ")",
										func = function()
											floors_removeWallCuts(
												room[editor.modelHovered.mode][editor.modelHovered.id],
												editor.modelHovered.index
											)
										end,
									})
								end
								if #room[editor.modelHovered.mode][editor.modelHovered.id].cuts > 0 then
									table.insert(sub, {
										name = "Remove All Cuts On Floor ("
											.. #room[editor.modelHovered.mode][editor.modelHovered.id].cuts
											.. ")",
										func = function()
											floors_removeWallCuts(
												room[editor.modelHovered.mode][editor.modelHovered.id]
											)
										end,
									})
								end
							else
								table.insert(sub, {
									name = "New Ramp",
									func = function()
										paths_openPanel(room, nil, "ramps", room)
										paths_newPath(
											room[editor.modelHovered.mode][editor.modelHovered.id],
											editor.modelHovered.index
										)
									end,
								})
							end
							if #sub > 1 then
								table.insert(items, {
									{
										name = "Edit " .. (editor.modelHovered.isWall and "Wall" or "Edge"),
										func = function()
											floors_startWallCut(
												room[editor.modelHovered.mode][editor.modelHovered.id],
												editor.modelHovered.index,
												"rect"
											)
										end,
										items = sub,
									},
								})
							end
						end
					end
					local numItems = #items
					table.insert(items, newSymbolContext())
					--table.insert(items,       paths_contextBuild(room))
					table.insert(items, editor_contextScripts(room))
					if not sidebar.visible then
						table.insert(items, {
							name = "Gallery",
							func = function()
								galleryPanel.width = 350
								editor_floatPanel(galleryPanel, contextMenu)
							end,
						})
					end

					table.insert(items, moreContextOptions())
				else
					if pathsPanel.open then
						if room[pathsPanel.mode][pathsPanel.current] then
							--  table.insert(items, { name="New Point",   func = function() editor_updateEntityTransform(editor_startDrag(paths_newPathPoint(),true)) end })
							items = paths_contextPath(room, pathsPanel.mode, pathsPanel.current)
							table.insert(items, {
								name = "Done",
								func = function()
									paths_closePanel()
								end,
								col = { r = 0.2, g = 0.7, b = 0.3, a = 0.3 },
							})
							props.width = 180
						end
					elseif animatePanel.open then
						--table.insert(items, editor_contextHSV(animatePanel.color))
						--table.insert(items, editor_contextRGB(animatePanel.color))
						--TOOLS

						local toolNames = {
							{ "Move (V)", "move" },
							{ "Lasso (L)", "select" },
							{ "Eraser (E)", "erase" },
							{ "Pen (P)", "pen" },
							{ "Brush (B)", "brush" },
							{ "Fill (F)", "fill" },
						}
						local tools = {}

						for i, t in ipairs(toolNames) do
							table.insert(tools, {
								size = -1,
								tip = t[1],
								img = "tools_" .. t[2],
								tool = t[2],
								col = { a = 1 },
                box = true,
								func = function()
									editor_switchDrawingTool(animatePanel, t[2])
								end,
								update = function(item)
									item.col = { a = 0.6 }
									if animatePanel.tool == "brush" then
										if item.tool == "pen" and not animatePanel.brush.paint then
											item.col = { a = 1 }
										elseif item.tool == "brush" and animatePanel.brush.paint then
											item.col = { a = 1 }
										end
									elseif animatePanel.tool == item.tool then
										item.col = { a = 1 }
									end
								end,
							})
						end
						-- table.insert(tools,{size=1,static=true})
						table.insert(
							tools,
							editor_colorSquare(animatePanel.brush, { name = "color", tip = "line color" })
						)
						table.insert(
							tools,
							editor_colorSquare(animatePanel, { name = "fillColor", tip = "fill color" })
						)

						local file, view, debug =
							{ name = "File", subitems = {} },
							{ name = "View", subitems = {} },
							{ name = "Debug", subitems = {} }
						local empty = {}

						file.subitems = {
							{
								name = "Save",
								func = function()
									save_animation(animatePanel)
								end,
							},
							editor_makeSlider(animatePanel, "maxUndos", {
								name = "Max Undos",
								max = 500,
								min = 10,
								round = 5,
								tip = "Careful with this, might just crash if you're low on memory",
							}),
							editor_makeToggle(editor, { "autoSaveTime", "autoSaveEnabled" }, {
								min = 1,
								max = 120,
								round = 1,
								name = "",
								update = function(item)
									local hours, minutes = math.modf(editor.autoSaveTime / 60)
									hours = hours > 0 and tostring(hours) .. " hour" .. (hours > 1 and "s " or " ")
										or ""
									minutes = minutes > 0 and tostring(minutes * 60) .. " minutes" or ""
									item.name = "Auto Save every " .. hours .. minutes
								end,
								noval = true,
							}, "slideToggle"),
							-- {
							--  name="Default Format",
							--  func= function(item)
							--    animatePanel.defaultFormat = cycleTable(animatePanel.formats)
							--  end,
							--  update = function(item)
							--    item.name = "Default Format: "..capFirst(animatePanel.defaultFormat=="r8" and "limited" or animatePanel.defaultFormat)
							--  end
							-- },
						}
						if ctx.isAnim then
							classicConcat(file.subitems, {
								editor_makeToggle(animatePanel, "limitToStageSize", {
									name = "Limit raster to stage by default",
									tip = "If left unchecked, the texture will automatically resize past the canvas border",
								}),
								{
									{ name = "Background Color", static = true },
									editor_colorSquare(animatePanel.animation, "color"),
								},
								{
									{
										name = "Stage Size" .. (animatePanel.atRoot and "" or " (Symbol)"),
										size = 3,
										static = true,
									},
									{
										name = tostring(animatePanel.symbol.stageWidth),
										align = "center",
										func = function(item)
											namer_typeString("width", tostring(animatePanel.symbol.stageWidth), {
												x = item.x + item.width / 2 + 2,
												y = item.y + item.height / 2 + 2,
												width = item.width,
												notri = true,
												limit = 5,
											}, function(x)
												if tonumber(x) ~= nil then
													x = math.max(32, math.abs(x))
													if animatePanel.lockAspect then
														animatePanel.symbol.stageHeight = animatePanel.symbol.stageHeight
															/ (animatePanel.symbol.stageWidth / x)
													end
													animatePanel.symbol.stageWidth = x
												end
											end, nil, true)
											return true
										end,
										update = function(item)
											item.text = tostring(animatePanel.symbol.stageWidth)
										end,
									},
									{
										name = tostring(animatePanel.symbol.stageHeight),
										align = "center",
										func = function(item)
											namer_typeString("width", tostring(animatePanel.symbol.stageHeight), {
												x = item.x + item.width / 2 + 2,
												y = item.y + item.height / 2 + 2,
												width = item.width,
												notri = true,
												limit = 5,
											}, function(x)
												if tonumber(x) ~= nil then
													x = math.max(32, math.abs(x))
													if animatePanel.lockAspect then
														animatePanel.symbol.stageWidth = animatePanel.symbol.stageWidth
															/ (animatePanel.symbol.stageHeight / x)
													end
													animatePanel.symbol.stageHeight = x
												end
											end, nil, true)
											return true
										end,
										update = function(item)
											item.text = tostring(animatePanel.symbol.stageHeight)
										end,
									},
									editor_makeCheckbox(animatePanel, "lockAspect", "Maintain Aspect"),
								},
								{
									lume.merge(
										editor_makeSlider(animatePanel, "exportScale", {
											col = { r = 1, g = 1, b = 1, a = 1 },
											name = "File Export Size",
											noval = true,
										})[1],
										{ size = 3 }
									),
									{
										name = "",
										static = true,
										align = "center",
										update = function(item)
											item.text = tostring(
												roundToNearest(
													animatePanel.root.stageWidth * animatePanel.exportScale,
													2
												)
											)
										end,
									},
									{
										name = "",
										static = true,
										align = "center",
										update = function(item)
											item.text = tostring(
												roundToNearest(
													animatePanel.root.stageHeight * animatePanel.exportScale,
													2
												)
											)
										end,
									},
									editor_makeCheckbox(animatePanel, "scaleExport", "Resize Export"),
								},
								editor_makeToggle(animatePanel.exportFormats, "transparent", {
									name = "Export With Transparency",
									tip = "If video export is enabled, there will have to be a second pass to include the background color in the video",
								}),
								editor_makeToggle(
									animatePanel.exportFormats,
									"noRoughNotes",
									{ name = "Hide Rough/Note on Export" }
								),
								editor_makeToggle(
									animatePanel.exportFormats,
									"separateLayers",
									{ name = "Export Layers Separately" },
									{
										editor_makeToggle(animatePanel.exportFormats, "separateFills", {
											name = "Separate Lines and Fills (disabled)",
											{ devonly = true },
										}),
									}
								),
								editor_makeToggle(animatePanel.exportFormats, "mp4", { name = "Export MP4" }),
								editor_makeToggle(animatePanel.exportFormats, "gif", { name = "Export GIF" }),
								classicConcat(
									{ { name = "Export Sequence: ", static = true, size = 2 } },
									editor_makeModes(animatePanel.exportFormats, "sequence", animatePanel.imageFormats)
								),
								-- editor_makeSlider(animatePanel,"exportBufferCount",
								--  {name="Number of Export Buffers",tip="more buffers = faster export + more vram usage during export, should be set to whatever your max fps is /60, eg if hit 180fps during export, 3 buffers might be worthwhile, ",round=1,min=1,max=4}),
								{
									name = "Export",
									func = function()
										animatePanel.triggerExport = true
									end,
								},
								-- {
								-- 	name = "Exit to start screen",
								-- 	func = engine_exit,
								-- 	warning = "open",
								-- },
							})
						end

						------------------------------------------------------------------------------------

						view.subitems = {
							{
								name = "Show Shortcuts and Help",
								func = function()
									if not (engine.trace.enabled and editor.helpEnabled) then
										engine.trace.enabled = true
										editor.helpEnabled = true
									else
										engine.trace.enabled = false
										editor.helpEnabled = false
									end
									return true
								end,
							},
							-- editor_makeToggle(animatePanel.onion,{"amount","enabled"},{name="Onion Skin"},{
							--  editor_makeToggle(animatePanel.onion.before,{"amount","enabled"},{name="before",colors={"tint"}}),
							--  editor_makeToggle(animatePanel.onion.after,{"amount","enabled"},{name="after",colors={"tint"}})
							-- }),
							editor_makeToggle(animatePanel, "showPasteboard", { name = "Show Pasteboard" }),
							editor_makeToggle(animatePanel, "timelineTracking", {
								name = "Timeline Tracking",
								tip = "Auto scroll timeline to current frame (when mouse is not inside it)",
							}),
							gfx.disableMSAA and { name = "Anti-Aliasing Unsupported :(" } or editor_makeToggle(
								animatePanel,
								{ "antiAliasing", "antiAlias" },
								{ name = "Antialiasing", min = 1, max = 8, round = 1 },
								"slideToggle"
							),

							-- editor_makeToggle(config,"flatUI",{name="Flat UI"}),
							editor_makeToggle(
								animatePanel,
								"frameShift",
								{ name = "Swap move/extend frame shortcuts", tip = "" }
							),
							editor_makeToggle(animatePanel, "phaseClear", {
								name = "2 Phase Vector Clear",
								tip = "clears the current line/fill group first, then everything else",
							}),

							editor_makeToggle(config, "tempTips", {
								name = "Enable Action Indicator",
								tip = "The little black box that pops up in the top right of the screen when you do something",
							}),
							-- editor_makeSlider(animatePanel,"fillDivs",{name="fill divisions",min=1,max=8,round=1}),
							-- editor_makeSlider(animatePanel,"fillDivs",{name="fill Divisions",min=1,max=8,round=1}),

							-- editor_makeToggle(animatePanel,"threadFill",{name="thread fill"}),
							editor_makeSlider(config, { "catmull", "fixedDetail" }, {
								name = "Curve Detail",
								min = 0,
								max = 4,
								round = 1,
								toggleTip = "disable automatically adjusting curve detail based on zoom",
							}),
							-- editor_makeToggle(config,"flashFrames",{name="oppa flash frame style"}),
							-- editor_makeToggle(config,"showLoaded",{name="show loaded frames"}),
							editor_makeToggle(config, "unlockDrawing", {
								name = "disable V-Sync while drawing",
								tip = 'might make drawing feel "snappier" at the risk of visual tearing (will also have a higher FPS when timeline is hidden)',
							}, {
								-- editor_makeToggle(config,"fullyUnlockDrawing",{name="Open the 8th gate",tip="*might* make drawing feel more responsive, at great risk of death"})
								-- editor_makeToggle(config,"hideTimelineWhileDrawing",{name="hide timeline while drawing",tip="fps is higher when the timeline is not being updated and drawn"})
								editor_makeToggle(config, "unlockMouse", {
									name = "disable V-sync for all mouse actions",
									tip = "does the same as above but for all other mouse related things (selection,transform etc) as well",
								}),
							}),
							-- editor_makeToggle(config,"fixedDetail",{name="Fixed Curve Detail", tip="disable automatically adjusting curve detail based on zoom"}),
							editor_makeToggle(
								config.highlightOutline,
								{ "size", "enabled" },
								{ name = "Selection Outline" }
							),
							editor_makeToggle(
								config.polkaDots,
								{ "amount", "enabled" },
								{ name = "Selection Polka Dots", min = 0.1, round = 0.1 },
								{
									editor_makeSlider(config.polkaDots, "speed", { name = "Crawl" }),
								}
							),
							editor_makeToggle(
								config,
								"hideFrameGaps",
								{ name = "hide frame gaps", click = timeline_refresh }
							),
							editor_makeToggle(config, "compactLayers", {
								name = "compact unselected layers (experimental)",
								click = timeline_refresh,
							}),
							editor_makeSlider(
								animatePanel,
								"row",
								{ name = "row size", min = 16, max = 32, round = 1 }
							),
							editor_makeToggle(
								config,
								"traceUndoHistory",
								{ name = "trace undo history", click = timeline_refresh }
							),
						}

						------------------------------------------------------------------------------------
						debug.subitems = {
							editor_makeToggle(animatePanel, "debugView", {
								name = "Debug View",
								tip = "do NOT enable if you don't know what you're doing, you will probably fuck up your file",
								click = editor_refreshStrokes,
                },
  							{
    							editor_makeToggle(
    								animatePanel,
    								"debugThin",
    								{ name = "Thin Lines", click = editor_refreshStrokes }
    							)
                }
              ),
							editor_makeToggle(animatePanel, "debugZoom", { name = "Zoom In" }),
							editor_makeToggle(
								animatePanel,
								"debugSelect",
								{ name = "Debug Selection Tool", click = editor_refreshStrokes }
							),
							editor_makeToggle(animatePanel, "debugBrush", { name = "Debug Vector Paint Brush" }),
							editor_makeToggle(animatePanel, "debugBoolean", { name = "Debug Vector Bool" }),
							editor_makeToggle(animatePanel, "debugRandomColor", { name = "Debug Random Color" }),
							editor_makeToggle(animatePanel, "debugPrintVector", { name = "Debug Vector Timing" }),
							editor_makeToggle(
								animatePanel,
								"debugSmooth",
								{ name = "Smooth Lines", click = editor_refreshStrokes }
							),
							editor_makeToggle(
								animatePanel,
								"debugTris",
								{ name = "Show Fill Tris", click = editor_refreshStrokes }
							),
							editor_makeToggle(animatePanel, "debugReleasedFrames", { name = "Show Released Frames" }),
							editor_makeToggle(animatePanel, "debugCompaction", { name = "Debug Canvas Compaction" }),
							editor_makeToggle(animatePanel, "liveTransformPreview", {
								name = "inline transform preview",
								tip = "Don't use seperate mesh for selection contents, might lag on very high detail frames",
							}),
							editor_makeToggle(animatePanel, "forceRefill", { name = "force refill" }),
							editor_makeToggle(config, "debugTriangulation", { name = "debug triangulation" }),
							editor_makeSlider(
								game,
								"frameTimePeriod",
								{ name = "frame time period", min = 1, max = 60, round = 1 }
							),
							editor_makeToggle(config, "triggerBreakpoint", { name = "Trigger Breakpoint" }),
						}

						table.insert(tools, {
							size = -1,
							name = "···",
							align = "center",
							col = { r = 0, g = 0, b = 0, a = settings and 0.5 or 0 },
							subWidth = 220,
							subHeight = 360,
							sameY = true,
							hoverOnly = true,
							sub = "File",
							rollOn = function(item)
								item.expand = true
							end,
							items = lfs.isFused() and { { file, view } } or { { file, view, debug } },
						})

						table.insert(items, tools)

						table.insert(items, editor_showRecentColors(animatePanel))

						if animatePanel.tool == "brush" then
							if animatePanel.l.format == "vector" then
								-- table.insert(items,editor_makeSlider(animatePanel.brush,"opacity"))
								table.insert(
									items,
									editor_makeSlider(
										animatePanel.brush.paint and animatePanel.brush or animatePanel.pen,
										"size",
										{
											round = 1,
											min = animatePanel.brush.paint and 4 or 1,
											max = animatePanel.brush.paint and animatePanel.sliders.size.max
												or animatePanel.sliders.size.max / 8,
										}
									)
								)
								table.insert(
									items,
									editor_makeSlider(animatePanel.pen, "stabilizer", { percent = true })
								)
								table.insert(
									items,
									editor_makeSlider(animatePanel.pen, "smoothing", { percent = true })
								)
								if animatePanel.brush.paint then
									table.insert(
										items,
										editor_makeModes(animatePanel, "brushMode", animatePanel.brushModesVector)
									)
								else
									table.insert(items, editor_makeModes(animatePanel.pen, "ends", { "round", "flat" }))
									-- table.insert(items,editor_makeModes(animatePanel.pen,"group",animatePanel.penGroups))
								end
							else
								local brushSettings = {}
								for s, name in ipairs({
									"size",
									"flatness",
									"spacing",
									"scatter",
									"angle",
								}) do
									local slider = animatePanel.sliders[name]
									local setting = {
										editor_makeSlider(animatePanel.brush, slider.name, {
											percent = slider.percent,
											min = slider.min,
											max = slider.max,
											round = slider.round,
											name = slider.name,
											nocap = true,
											col = { r = 1, g = 1, b = 1, a = 1 },
										})[1],
										-- ,editor_makeSlider(slider,"jitter",{name="",tip=slider.name.." jitter"})[1]
									}
									setting[1].size = 3
									if setting[2] then
										setting[2].size = 1
									end
									table.insert(brushSettings, setting)
									if slider.name == "angle" then
										table.insert(
											brushSettings,
											editor_makeToggle(
												animatePanel.brush,
												"followDirection",
												{ name = "Follow stroke direction" }
											)
										)
									end
								end
								table.insert(
									brushSettings,
									editor_makeSlider(animatePanel.pen, "stabilizer", { percent = true })
								)
								table.insert(brushSettings, editor_makeToggle(animatePanel.brush, "antialias"))
								classicConcat(items, brushSettings)
							end
							-- table.insert(items,editor_makeToggle(animatePanel.brush,"texture",{name="pressure sensitivity"})
							if animatePanel.brush.paint then
								table.insert(
									items,
									editor_makeToggle(
										animatePanel.brush,
										"pressureSensitivity",
										{ name = "pressure sensitivity" },
										{
											editor_makeToggle(
												animatePanel.brush,
												{ "pressureSizeAmount", "pressureSizeEnabled" },
												{ name = "Size", percent = true }
											),
											-- editor_makeToggle(animatePanel.brush,
											--  {"pressureOpacityAmount","pressureOpacityEnabled"},{name="Opacity",percent=true}),
										}
									)
								)
							else
								table.insert(
									items,
									editor_makeToggle(
										animatePanel.pen,
										"pressureSensitivity",
										{ name = "pressure sensitivity" },
										{
											editor_makeToggle(
												animatePanel.pen,
												{ "pressureSizeAmount", "pressureSizeEnabled" },
												{ name = "Size", percent = true }
											),
											editor_makeToggle(
												animatePanel.pen,
												{ "pressureOpacityAmount", "pressureOpacityEnabled" },
												{ name = "Opacity", percent = true }
											),
										}
									)
								)
							end
						end

						if animatePanel.tool == "fill" then
							-- table.insert(items,editor_makeModes(animatePanel,"fillMode",animatePanel.fillModes))
							if animatePanel.l.format == "vector" then
								table.insert(
									items,
									editor_makeSlider(animatePanel, "fillGap", {
										name = "fill gap",
										max = 16,
										round = 1,
										tip = "still experimental, set this to 0 if you're experiencing glitches or slow fill performance",
									})
								)
								table.insert(
									items,
									editor_makeSlider(
										animatePanel,
										"fillRadius",
										{ name = "fill radius", max = 100, round = 1 }
									)
								)
								table.insert(
									items,
									editor_makeToggle(animatePanel, "fillDrag", { name = "fill while dragging" })
								)
								table.insert(
									items,
									editor_makeToggle(animatePanel, "fillAll", {
										name = "fill all",
										tip = "requires all fill shapes be precalculated",
									})
								)
							end
							if animatePanel.l.format == "raster" then
								table.insert(
									items,
									editor_makeSlider(
										animatePanel,
										"fillTolerance",
										{ name = "tolerance", percent = true }
									)
								)
								table.insert(
									items,
									editor_makeToggle(animatePanel, "fillBehind", { name = "fill behind" })
								)
								table.insert(
									items,
									editor_makeSlider(
										animatePanel,
										"fillExpand",
										{ name = "expand fill", round = 1, max = 8 }
									)
								)
							end

							table.insert(
								items,
								editor_makeModes(animatePanel, "fillLayer", animatePanel.selectLayers, {
									after = function()
										fill_prepareFill(animatePanel)
									end,
									suffix = " layers",
								})
							)
						end

						if animatePanel.tool == "erase" then
							table.insert(
								items,
								editor_makeSlider(animatePanel.eraser, "size", { round = 1, min = 2, max = 64 })
							)
							if animatePanel.l.format == "vector" then
								table.insert(
									items,
									editor_makeModes(
										animatePanel,
										"eraseMode",
										animatePanel.l.format == "vector" and animatePanel.eraseModesVector
											or animatePanel.eraseModesRaster
									)
								)
								-- table.insert(items,editor_makeModes(animatePanel,"eraseGroup",animatePanel.eraseGroups,{
								--  after=function() editor_prepareSegments(animatePanel) end
								-- }))
								table.insert(
									items,
									editor_makeModes(animatePanel, "selectLayer", animatePanel.selectLayers, {
										after = function()
											fill_prepareSegments(animatePanel)
										end,
										suffix = " layers",
									})
								)
								table.insert(
									items,
									editor_makeToggle(animatePanel, "eraseArea", { name = "erase area" })
								)
							end
						end

						if animatePanel.tool == "select" then
							if animatePanel.l.format == "vector" then
								-- table.insert(items,editor_makeModes(animatePanel,"selectGroup",animatePanel.eraseGroups))
								table.insert(
									items,
									editor_makeModes(
										animatePanel,
										"selectLayer",
										animatePanel.selectLayers,
										{ suffix = " layers" }
									)
								)
								table.insert(
									items,
									editor_makeToggle(animatePanel, "cropSelect", { name = "Crop Selection Shape" })
								)
							end
						end

						if animatePanel.tool == "move" then
							if animatePanel.l.format == "vector" then
								-- table.insert(items,editor_makeModes(animatePanel,"selectGroup",animatePanel.eraseGroups))
								table.insert(
									items,
									editor_makeModes(
										animatePanel,
										"selectLayer",
										animatePanel.selectLayers,
										{ suffix = " layers" }
									)
								)
								table.insert(
									items,
									editor_makeModes(animatePanel, "strokeSelectMode", animatePanel.strokeSelectModes)
								)
								table.insert(
									items,
									editor_makeSlider(
										animatePanel,
										"strokeSelectFalloff",
										{ name = "range of influence" }
									)
								)
								table.insert(
									items,
									editor_makeToggle(animatePanel, "cropSelect", { name = "Crop Selection Shape" })
								)
							end
						end

						if animatePanel.selection.mesh then
							if animatePanel.selection.canvas then
								table.insert(items, {
									name = "Flip Horizontal",
									func = function()
										animatePanel.selection.scale.x = animatePanel.selection.scale.x * -1
										return true
									end,
								})
								table.insert(items, {
									name = "Flip Vertical",
									func = function()
										animatePanel.selection.scale.y = animatePanel.selection.scale.y * -1
										return true
									end,
								})
								table.insert(items, {
									name = "Move to New Layer",
									func = function()
										editor_moveToNewLayer(animatePanel)
									end,
								})
							end
						end

						if not lfs.isFused() then
							table.insert(items, {
								name = "Gallery",
								func = function()
									galleryPanel.width = 350
									editor_floatPanel(galleryPanel, contextMenu)
								end,
							})
						end

						props.width = 180
					else
						if #editor.pasteboard > 0 then
							table.insert(items, { name = "Paste", func = editor_pasteEntities })
						end
					end
				end
			end
		end
		editor_openContextMenu(items, props)
	end, true)
end
