code:
package net.minetest.minetest;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;

public class MinetestTextEntry extends Activity {
	public AlertDialog mTextInputDialog;
	public EditText mTextInputWidget;

	private final int MultiLineTextInput              = 1;
	private final int SingleLineTextInput             = 2;
	private final int SingleLinePasswordInput         = 3;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Bundle b = getIntent().getExtras();
		String acceptButton = b.getString("EnterButton");
		String hint         = b.getString("hint");
		String current      = b.getString("current");
		int    editType     = b.getInt("editType");

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		mTextInputWidget = new EditText(this);
		mTextInputWidget.setHint(hint);
		mTextInputWidget.setText(current);
		mTextInputWidget.setMinWidth(300);
		if (editType == SingleLinePasswordInput) {
			mTextInputWidget.setInputType(InputType.TYPE_CLASS_TEXT |
					InputType.TYPE_TEXT_VARIATION_PASSWORD);
		}
		else {
			mTextInputWidget.setInputType(InputType.TYPE_CLASS_TEXT);
		}

		builder.setView(mTextInputWidget);

		if (editType == MultiLineTextInput) {
			builder.setPositiveButton(acceptButton, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton)
				{ pushResult(mTextInputWidget.getText().toString()); }
				});
		}

		builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
			public void onCancel(DialogInterface dialog) {
				cancelDialog();
			}
		});

		mTextInputWidget.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View view, int KeyCode, KeyEvent event) {
				if ( KeyCode == KeyEvent.KEYCODE_ENTER){

					pushResult(mTextInputWidget.getText().toString());
					return true;
				}
				return false;
			}
		});

		mTextInputDialog = builder.create();
		mTextInputDialog.show();
	}

	public void pushResult(String text) {
		Intent resultData = new Intent();
		resultData.putExtra("text", text);
		setResult(Activity.RESULT_OK,resultData);
		mTextInputDialog.dismiss();
		finish();
	}

	public void cancelDialog() {
		setResult(Activity.RESULT_CANCELED);
		mTextInputDialog.dismiss();
		finish();
	}
}


code:
package net.minetest.minetest;

import android.app.NativeActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;

public class MtNativeActivity extends NativeActivity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		m_MessagReturnCode = -1;
		m_MessageReturnValue = "";

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	public void copyAssets() {
		Intent intent = new Intent(this, MinetestAssetCopy.class);
		startActivity(intent);
	}

	public void showDialog(String acceptButton, String hint, String current,
			int editType) {

		Intent intent = new Intent(this, MinetestTextEntry.class);
		Bundle params = new Bundle();
		params.putString("acceptButton", acceptButton);
		params.putString("hint", hint);
		params.putString("current", current);
		params.putInt("editType", editType);
		intent.putExtras(params);
		startActivityForResult(intent, 101);
		m_MessageReturnValue = "";
		m_MessagReturnCode   = -1;
	}

	public static native void putMessageBoxResult(String text);

	/* ugly code to workaround putMessageBoxResult not beeing found */
	public int getDialogState() {
		return m_MessagReturnCode;
	}

	public String getDialogValue() {
		m_MessagReturnCode = -1;
		return m_MessageReturnValue;
	}

	public float getDensity() {
		return getResources().getDisplayMetrics().density;
	}

	public int getDisplayWidth() {
		return getResources().getDisplayMetrics().widthPixels;
	}

	public int getDisplayHeight() {
		return getResources().getDisplayMetrics().heightPixels;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent data) {
		if (requestCode == 101) {
			if (resultCode == RESULT_OK) {
				String text = data.getStringExtra("text");
				m_MessagReturnCode = 0;
				m_MessageReturnValue = text;
			}
			else {
				m_MessagReturnCode = 1;
			}
		}
	}

	static {
		System.loadLibrary("openal");
		System.loadLibrary("ogg");
		System.loadLibrary("vorbis");
		System.loadLibrary("ssl");
		System.loadLibrary("crypto");
		System.loadLibrary("gmp");
		System.loadLibrary("iconv");

		// We don't have to load libminetest.so ourselves,
		// but if we do, we get nicer logcat errors when
		// loading fails.
		System.loadLibrary("minetest");
	}

	private int m_MessagReturnCode;
	private String m_MessageReturnValue;
}

repo_name: pgimeno/minetest

license: unknown


code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ellipsize="middle"
        android:singleLine="true"
        android:layout_gravity="center_horizontal"
        android:text="@string/preparing_media"
        android:textAppearance="?android:attr/textAppearanceSmall" />

</LinearLayout>


code:
<?xml version="1.0" encoding="utf-8"?>
<resources>
	<string name="preparing_media">Preparing media...</string>
</resources>


code:
<?xml version="1.0" encoding="utf-8"?>
<resources>
	<style name="Theme.Transparent" parent="android:Theme">
		<item name="android:windowIsTranslucent">true</item>
		<item name="android:windowBackground">@android:color/transparent</item>
		<item name="android:windowContentOverlay">@null</item>
		<item name="android:windowNoTitle">true</item>
		<item name="android:windowIsFloating">true</item>
		<item name="android:backgroundDimEnabled">false</item>
	</style>
</resources>


code:
core.log("info", "Initializing Asynchronous environment")

function core.job_processor(serialized_func, serialized_param)
	local func = loadstring(serialized_func)
	local param = core.deserialize(serialized_param)
	local retval = nil

	if type(func) == "function" then
		retval = core.serialize(func(param))
	else
		core.log("error", "ASYNC WORKER: Unable to deserialize function")
	end

	return retval or core.serialize(nil)
end


code:
-- Minetest: builtin/client/chatcommands.lua

core.register_on_sending_chat_messages(function(message)
	if message:sub(1,2) == ".." then
		return false
	end

	local first_char = message:sub(1,1)
	if first_char == "/" or first_char == "." then
		core.display_chat_message(core.gettext("issued command: ") .. message)
	end

	if first_char ~= "." then
		return false
	end

	local cmd, param = string.match(message, "^%.([^ ]+) *(.*)")
 	param = param or ""

	if not cmd then
		core.display_chat_message(core.gettext("-!- Empty command"))
		return true
	end

	local cmd_def = core.registered_chatcommands[cmd]
	if cmd_def then
		core.set_last_run_mod(cmd_def.mod_origin)
		local _, message = cmd_def.func(param)
		if message then
			core.display_chat_message(message)
		end
	else
		core.display_chat_message(core.gettext("-!- Invalid command: ") .. cmd)
	end

	return true
end)

core.register_chatcommand("list_players", {
	description = core.gettext("List online players"),
	func = function(param)
		local players = table.concat(core.get_player_names(), ", ")
		core.display_chat_message(core.gettext("Online players: ") .. players)
	end
})

core.register_chatcommand("disconnect", {
	description = core.gettext("Exit to main menu"),
	func = function(param)
		core.disconnect()
	end,
})

core.register_chatcommand("clear_chat_queue", {
	description = core.gettext("Clear the out chat queue"),
	func = function(param)
		core.clear_out_chat_queue()
		return true, core.gettext("The out chat queue is now empty")
	end,
})

function core.run_server_chatcommand(cmd, param)
	core.send_chat_message("/" .. cmd .. " " .. param)
end


code:
-- Minetest: builtin/client/init.lua
local scriptpath = core.get_builtin_path()..DIR_DELIM
local clientpath = scriptpath.."client"..DIR_DELIM
local commonpath = scriptpath.."common"..DIR_DELIM

dofile(clientpath .. "register.lua")
dofile(commonpath .. "after.lua")
dofile(commonpath .. "chatcommands.lua")
dofile(clientpath .. "chatcommands.lua")
dofile(commonpath .. "vector.lua")

core.register_on_death(function()
	core.display_chat_message("You died.")
	local formspec = "size[11,5.5]bgcolor[#320000b4;true]" ..
	"label[4.85,1.35;" .. fgettext("You died.") .. "]button_exit[4,3;3,0.5;btn_respawn;".. fgettext("Respawn") .."]"
	core.show_formspec("bultin:death", formspec)
end)

core.register_on_formspec_input(function(formname, fields)
	if formname == "bultin:death" then
		core.send_respawn()
	end
end)


code:
core.callback_origins = {}

local getinfo = debug.getinfo
debug.getinfo = nil

function core.run_callbacks(callbacks, mode, ...)
	assert(type(callbacks) == "table")
	local cb_len = #callbacks
	if cb_len == 0 then
		if mode == 2 or mode == 3 then
			return true
		elseif mode == 4 or mode == 5 then
			return false
		end
	end
	local ret
	for i = 1, cb_len do
		local cb_ret = callbacks[i](...)

		if mode == 0 and i == 1 or mode == 1 and i == cb_len then
			ret = cb_ret
		elseif mode == 2 then
			if not cb_ret or i == 1 then
				ret = cb_ret
			end
		elseif mode == 3 then
			if cb_ret then
				return cb_ret
			end
			ret = cb_ret
		elseif mode == 4 then
			if (cb_ret and not ret) or i == 1 then
				ret = cb_ret
			end
		elseif mode == 5 and cb_ret then
			return cb_ret
		end
	end
	return ret
end

--
-- Callback registration
--

local function make_registration()
	local t = {}
	local registerfunc = function(func)
		t[#t + 1] = func
		core.callback_origins[func] = {
			mod = core.get_current_modname() or "??",
			name = getinfo(1, "n").name or "??"
		}
		--local origin = core.callback_origins[func]
		--print(origin.name .. ": " .. origin.mod .. " registering cbk " .. tostring(func))
	end
	return t, registerfunc
end

core.registered_globalsteps, core.register_globalstep = make_registration()
core.registered_on_shutdown, core.register_on_shutdown = make_registration()
core.registered_on_connect, core.register_on_connect = make_registration()
core.registered_on_receiving_chat_messages, core.register_on_receiving_chat_messages = make_registration()
core.registered_on_sending_chat_messages, core.register_on_sending_chat_messages = make_registration()
core.registered_on_death, core.register_on_death = make_registration()
core.registered_on_hp_modification, core.register_on_hp_modification = make_registration()
core.registered_on_damage_taken, core.register_on_damage_taken = make_registration()
core.registered_on_formspec_input, core.register_on_formspec_input = make_registration()
core.registered_on_dignode, core.register_on_dignode = make_registration()
core.registered_on_punchnode, core.register_on_punchnode = make_registration()
core.registered_on_placenode, core.register_on_placenode = make_registration()
core.registered_on_item_use, core.register_on_item_use = make_registration()


code:
local jobs = {}
local time = 0.0

core.register_globalstep(function(dtime)
	time = time + dtime

	if #jobs < 1 then
		return
	end

	-- Iterate backwards so that we miss any new timers added by
	-- a timer callback, and so that we don't skip the next timer
	-- in the list if we remove one.
	for i = #jobs, 1, -1 do
		local job = jobs[i]
		if time >= job.expire then
			core.set_last_run_mod(job.mod_origin)
			job.func(unpack(job.arg))
			table.remove(jobs, i)
		end
	end
end)

function core.after(after, func, ...)
	assert(tonumber(after) and type(func) == "function",
		"Invalid core.after invocation")
	jobs[#jobs + 1] = {
		func = func,
		expire = time + after,
		arg = {...},
		mod_origin = core.get_last_run_mod()
	}
end


code:
core.async_jobs = {}

local function handle_job(jobid, serialized_retval)
	local retval = core.deserialize(serialized_retval)
	assert(type(core.async_jobs[jobid]) == "function")
	core.async_jobs[jobid](retval)
	core.async_jobs[jobid] = nil
end

if core.register_globalstep then
	core.register_globalstep(function(dtime)
		for i, job in ipairs(core.get_finished_jobs()) do
			handle_job(job.jobid, job.retval)
		end
	end)
else
	core.async_event_handler = handle_job
end

function core.handle_async(func, parameter, callback)
	-- Serialize function
	local serialized_func = string.dump(func)

	assert(serialized_func ~= nil)

	-- Serialize parameters
	local serialized_param = core.serialize(parameter)

	if serialized_param == nil then
		return false
	end

	local jobid = core.do_async_callback(serialized_func, serialized_param)

	core.async_jobs[jobid] = callback

	return true
end


code:
-- Minetest: builtin/common/chatcommands.lua

core.registered_chatcommands = {}

function core.register_chatcommand(cmd, def)
	def = def or {}
	def.params = def.params or ""
	def.description = def.description or ""
	def.privs = def.privs or {}
	def.mod_origin = core.get_current_modname() or "??"
	core.registered_chatcommands[cmd] = def
end

function core.unregister_chatcommand(name)
	if core.registered_chatcommands[name] then
		core.registered_chatcommands[name] = nil
	else
		core.log("warning", "Not unregistering chatcommand " ..name..
			" because it doesn't exist.")
	end
end

function core.override_chatcommand(name, redefinition)
	local chatcommand = core.registered_chatcommands[name]
	assert(chatcommand, "Attempt to override non-existent chatcommand "..name)
	for k, v in pairs(redefinition) do
		rawset(chatcommand, k, v)
	end
	core.registered_chatcommands[name] = chatcommand
end

local cmd_marker = "/"

local function gettext(...)
	return ...
end

local function gettext_replace(text, replace)
	return text:gsub("$1", replace)
end

if INIT == "client" then
	cmd_marker = "."
	gettext = core.gettext
	gettext_replace = fgettext_ne
end

local function do_help_cmd(name, param)
	local function format_help_line(cmd, def)
		local msg = core.colorize("#00ffff", cmd_marker .. cmd)
		if def.params and def.params ~= "" then
			msg = msg .. " " .. def.params
		end
		if def.description and def.description ~= "" then
			msg = msg .. ": " .. def.description
		end
		return msg
	end
	if param == "" then
		local cmds = {}
		for cmd, def in pairs(core.registered_chatcommands) do
			if INIT == "client" or core.check_player_privs(name, def.privs) then
				cmds[#cmds + 1] = cmd
			end
		end
		table.sort(cmds)
		return true, gettext("Available commands: ") .. table.concat(cmds, " ") .. "\n"
				.. gettext_replace("Use '$1help <cmd>' to get more information,"
				.. " or '$1help all' to list everything.", cmd_marker)
	elseif param == "all" then
		local cmds = {}
		for cmd, def in pairs(core.registered_chatcommands) do
			if INIT == "client" or core.check_player_privs(name, def.privs) then
				cmds[#cmds + 1] = format_help_line(cmd, def)
			end
		end
		table.sort(cmds)
		return true, gettext("Available commands:").."\n"..table.concat(cmds, "\n")
	elseif INIT == "game" and param == "privs" then
		local privs = {}
		for priv, def in pairs(core.registered_privileges) do
			privs[#privs + 1] = priv .. ": " .. def.description
		end
		table.sort(privs)
		return true, "Available privileges:\n"..table.concat(privs, "\n")
	else
		local cmd = param
		local def = core.registered_chatcommands[cmd]
		if not def then
			return false, gettext("Command not available: ")..cmd
		else
			return true, format_help_line(cmd, def)
		end
	end
end

if INIT == "client" then
	core.register_chatcommand("help", {
		params = gettext("[all/<cmd>]"),
		description = gettext("Get help for commands"),
		func = function(param)
			return do_help_cmd(nil, param)
		end,
	})
else
	core.register_chatcommand("help", {
		params = "[all/privs/<cmd>]",
		description = "Get help for commands or list privileges",
		func = do_help_cmd,
	})
end


code:
--Minetest
--Copyright (C) 2013 sapier
--
--This program is free software; you can redistribute it and/or modify
--it under the terms of the GNU Lesser General Public License as published by
--the Free Software Foundation; either version 2.1 of the License, or
--(at your option) any later version.
--
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
--GNU Lesser General Public License for more details.
--
--You should have received a copy of the GNU Lesser General Public License along
--with this program; if not, write to the Free Software Foundation, Inc.,
--51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

--------------------------------------------------------------------------------
-- TODO improve doc                                                           --
-- TODO code cleanup                                                          --
-- Generic implementation of a filter/sortable list                           --
-- Usage:                                                                     --
-- Filterlist needs to be initialized on creation. To achieve this you need to --
-- pass following functions:                                                  --
-- raw_fct() (mandatory):                                                     --
--     function returning a table containing the elements to be filtered      --
-- compare_fct(element1,element2) (mandatory):                                --
--     function returning true/false if element1 is same element as element2  --
-- uid_match_fct(element1,uid) (optional)                                     --
--     function telling if uid is attached to element1                        --
-- filter_fct(element,filtercriteria) (optional)                              --
--     function returning true/false if filtercriteria met to element         --
-- fetch_param (optional)                                                     --
--     parameter passed to raw_fct to aquire correct raw data                 --
--                                                                            --
--------------------------------------------------------------------------------
filterlist = {}

--------------------------------------------------------------------------------
function filterlist.refresh(self)
	self.m_raw_list = self.m_raw_list_fct(self.m_fetch_param)
	filterlist.process(self)
end

--------------------------------------------------------------------------------
function filterlist.create(raw_fct,compare_fct,uid_match_fct,filter_fct,fetch_param)

	assert((raw_fct ~= nil) and (type(raw_fct) == "function"))
	assert((compare_fct ~= nil) and (type(compare_fct) == "function"))

	local self = {}

	self.m_raw_list_fct  = raw_fct
	self.m_compare_fct   = compare_fct
	self.m_filter_fct    = filter_fct
	self.m_uid_match_fct = uid_match_fct

	self.m_filtercriteria = nil
	self.m_fetch_param = fetch_param

	self.m_sortmode = "none"
	self.m_sort_list = {}

	self.m_processed_list = nil
	self.m_raw_list = self.m_raw_list_fct(self.m_fetch_param)

	self.add_sort_mechanism = filterlist.add_sort_mechanism
	self.set_filtercriteria = filterlist.set_filtercriteria
	self.get_filtercriteria = filterlist.get_filtercriteria
	self.set_sortmode       = filterlist.set_sortmode
	self.get_list           = filterlist.get_list
	self.get_raw_list       = filterlist.get_raw_list
	self.get_raw_element    = filterlist.get_raw_element
	self.get_raw_index      = filterlist.get_raw_index
	self.get_current_index  = filterlist.get_current_index
	self.size               = filterlist.size
	self.uid_exists_raw     = filterlist.uid_exists_raw
	self.raw_index_by_uid   = filterlist.raw_index_by_uid
	self.refresh            = filterlist.refresh

	filterlist.process(self)

	return self
end

--------------------------------------------------------------------------------
function filterlist.add_sort_mechanism(self,name,fct)
	self.m_sort_list[name] = fct
end

--------------------------------------------------------------------------------
function filterlist.set_filtercriteria(self,criteria)
	if criteria == self.m_filtercriteria and
		type(criteria) ~= "table" then
		return
	end
	self.m_filtercriteria = criteria
	filterlist.process(self)
end

--------------------------------------------------------------------------------
function filterlist.get_filtercriteria(self)
	return self.m_filtercriteria
end

--------------------------------------------------------------------------------
--supported sort mode "alphabetic|none"
function filterlist.set_sortmode(self,mode)
	if (mode == self.m_sortmode) then
		return
	end
	self.m_sortmode = mode
	filterlist.process(self)
end

--------------------------------------------------------------------------------
function filterlist.get_list(self)
	return self.m_processed_list
end

--------------------------------------------------------------------------------
function filterlist.get_raw_list(self)
	return self.m_raw_list
end

--------------------------------------------------------------------------------
function filterlist.get_raw_element(self,idx)
	if type(idx) ~= "number" then
		idx = tonumber(idx)
	end

	if idx ~= nil and idx > 0 and idx <= #self.m_raw_list then
		return self.m_raw_list[idx]
	end

	return nil
end

--------------------------------------------------------------------------------
function filterlist.get_raw_index(self,listindex)
	assert(self.m_processed_list ~= nil)

	if listindex ~= nil and listindex > 0 and
		listindex <= #self.m_processed_list then
		local entry = self.m_processed_list[listindex]

		for i,v in ipairs(self.m_raw_list) do

			if self.m_compare_fct(v,entry) then
				return i
			end
		end
	end

	return 0
end

--------------------------------------------------------------------------------
function filterlist.get_current_index(self,listindex)
	assert(self.m_processed_list ~= nil)

	if listindex ~= nil and listindex > 0 and
		listindex <= #self.m_raw_list then
		local entry = self.m_raw_list[listindex]

		for i,v in ipairs(self.m_processed_list) do

			if self.m_compare_fct(v,entry) then
				return i
			end
		end
	end

	return 0
end

--------------------------------------------------------------------------------
function filterlist.process(self)
	assert(self.m_raw_list ~= nil)

	if self.m_sortmode == "none" and
		self.m_filtercriteria == nil then
		self.m_processed_list = self.m_raw_list
		return
	end

	self.m_processed_list = {}

	for k,v in pairs(self.m_raw_list) do
		if self.m_filtercriteria == nil or
			self.m_filter_fct(v,self.m_filtercriteria) then
			self.m_processed_list[#self.m_processed_list + 1] = v
		end
	end

	if self.m_sortmode == "none" then
		return
	end

	if self.m_sort_list[self.m_sortmode] ~= nil and
		type(self.m_sort_list[self.m_sortmode]) == "function" then

		self.m_sort_list[self.m_sortmode](self)
	end
end

--------------------------------------------------------------------------------
function filterlist.size(self)
	if self.m_processed_list == nil then
		return 0
	end

	return #self.m_processed_list
end

--------------------------------------------------------------------------------
function filterlist.uid_exists_raw(self,uid)
	for i,v in ipairs(self.m_raw_list) do
		if self.m_uid_match_fct(v,uid) then
			return true
		end
	end
	return false
end

--------------------------------------------------------------------------------
function filterlist.raw_index_by_uid(self, uid)
	local elementcount = 0
	local elementidx = 0
	for i,v in ipairs(self.m_raw_list) do
		if self.m_uid_match_fct(v,uid) then
			elementcount = elementcount +1
			elementidx = i
		end
	end

	-- If there are more elements than one with same name uid can't decide which
	-- one is meant. self shouldn't be possible but just for sure.
	if elementcount > 1 then
		elementidx=0
	end

	return elementidx
end

--------------------------------------------------------------------------------
-- COMMON helper functions                                                    --
--------------------------------------------------------------------------------

--------------------------------------------------------------------------------
function compare_worlds(world1,world2)

	if world1.path ~= world2.path then
		return false
	end

	if world1.name ~= world2.name then
		return false
	end

	if world1.gameid ~= world2.gameid then
		return false
	end

	return true
end

--------------------------------------------------------------------------------
function sort_worlds_alphabetic(self)

	table.sort(self.m_processed_list, function(a, b)
		--fixes issue #857 (crash due to sorting nil in worldlist)
		if a == nil or b == nil then
			if a == nil and b ~= nil then return false end
			if b == nil and a ~= nil then return true end
			return false
		end
		if a.name:lower() == b.name:lower() then
			return a.name < b.name
		end
		return a.name:lower() < b.name:lower()
	end)
end

--------------------------------------------------------------------------------
function sort_mod_list(self)

	table.sort(self.m_processed_list, function(a, b)
		-- Show game mods at bottom
		if a.typ ~= b.typ then
			if b.typ == "game" then
				return a.typ ~= "game_mod"
			end
			return b.typ == "game_mod"
		end
		-- If in same or no modpack, sort by name
		if a.modpack == b.modpack then
			if a.name:lower() == b.name:lower() then
				return a.name < b.name
			end
			return a.name:lower() < b.name:lower()
		-- Else compare name to modpack name
		else
			-- Always show modpack pseudo-mod on top of modpack mod list
			if a.name == b.modpack then
				return true
			elseif b.name == a.modpack then
				return false
			end

			local name_a = a.modpack or a.name
			local name_b = b.modpack or b.name
			if name_a:lower() == name_b:lower() then
				return  name_a < name_b
			end
			return name_a:lower() < name_b:lower()
		end
	end)
end


code:
-- Minetest: builtin/misc_helpers.lua

--------------------------------------------------------------------------------
-- Localize functions to avoid table lookups (better performance).
local string_sub, string_find = string.sub, string.find

--------------------------------------------------------------------------------
function basic_dump(o)
	local tp = type(o)
	if tp == "number" then
		return tostring(o)
	elseif tp == "string" then
		return string.format("%q", o)
	elseif tp == "boolean" then
		return tostring(o)
	elseif tp == "nil" then
		return "nil"
	-- Uncomment for full function dumping support.
	-- Not currently enabled because bytecode isn't very human-readable and
	-- dump's output is intended for humans.
	--elseif tp == "function" then
	--	return string.format("loadstring(%q)", string.dump(o))
	else
		return string.format("<%s>", tp)
	end
end

local keywords = {
	["and"] = true,
	["break"] = true,
	["do"] = true,
	["else"] = true,
	["elseif"] = true,
	["end"] = true,
	["false"] = true,
	["for"] = true,
	["function"] = true,
	["goto"] = true,  -- Lua 5.2
	["if"] = true,
	["in"] = true,
	["local"] = true,
	["nil"] = true,
	["not"] = true,
	["or"] = true,
	["repeat"] = true,
	["return"] = true,
	["then"] = true,
	["true"] = true,
	["until"] = true,
	["while"] = true,
}
local function is_valid_identifier(str)
	if not str:find("^[a-zA-Z_][a-zA-Z0-9_]*$") or keywords[str] then
		return false
	end
	return true
end

--------------------------------------------------------------------------------
-- Dumps values in a line-per-value format.
-- For example, {test = {"Testing..."}} becomes:
--   _["test"] = {}
--   _["test"][1] = "Testing..."
-- This handles tables as keys and circular references properly.
-- It also handles multiple references well, writing the table only once.
-- The dumped argument is internal-only.

function dump2(o, name, dumped)
	name = name or "_"
	-- "dumped" is used to keep track of serialized tables to handle
	-- multiple references and circular tables properly.
	-- It only contains tables as keys.  The value is the name that
	-- the table has in the dump, eg:
	-- {x = {"y"}} -> dumped[{"y"}] = '_["x"]'
	dumped = dumped or {}
	if type(o) ~= "table" then
		return string.format("%s = %s\n", name, basic_dump(o))
	end
	if dumped[o] then
		return string.format("%s = %s\n", name, dumped[o])
	end
	dumped[o] = name
	-- This contains a list of strings to be concatenated later (because
	-- Lua is slow at individual concatenation).
	local t = {}
	for k, v in pairs(o) do
		local keyStr
		if type(k) == "table" then
			if dumped[k] then
				keyStr = dumped[k]
			else
				-- Key tables don't have a name, so use one of
				-- the form _G["table: 0xFFFFFFF"]
				keyStr = string.format("_G[%q]", tostring(k))
				-- Dump key table
				t[#t + 1] = dump2(k, keyStr, dumped)
			end
		else
			keyStr = basic_dump(k)
		end
		local vname = string.format("%s[%s]", name, keyStr)
		t[#t + 1] = dump2(v, vname, dumped)
	end
	return string.format("%s = {}\n%s", name, table.concat(t))
end

--------------------------------------------------------------------------------
-- This dumps values in a one-statement format.
-- For example, {test = {"Testing..."}} becomes:
-- [[{
-- 	test = {
-- 		"Testing..."
-- 	}
-- }]]
-- This supports tables as keys, but not circular references.
-- It performs poorly with multiple references as it writes out the full
-- table each time.
-- The indent field specifies a indentation string, it defaults to a tab.
-- Use the empty string to disable indentation.
-- The dumped and level arguments are internal-only.

function dump(o, indent, nested, level)
	if type(o) ~= "table" then
		return basic_dump(o)
	end
	-- Contains table -> true/nil of currently nested tables
	nested = nested or {}
	if nested[o] then
		return "<circular reference>"
	end
	nested[o] = true
	indent = indent or "\t"
	level = level or 1
	local t = {}
	local dumped_indexes = {}
	for i, v in ipairs(o) do
		t[#t + 1] = dump(v, indent, nested, level + 1)
		dumped_indexes[i] = true
	end
	for k, v in pairs(o) do
		if not dumped_indexes[k] then
			if type(k) ~= "string" or not is_valid_identifier(k) then
				k = "["..dump(k, indent, nested, level + 1).."]"
			end
			v = dump(v, indent, nested, level + 1)
			t[#t + 1] = k.." = "..v
		end
	end
	nested[o] = nil
	if indent ~= "" then
		local indent_str = "\n"..string.rep(indent, level)
		local end_indent_str = "\n"..string.rep(indent, level - 1)
		return string.format("{%s%s%s}",
				indent_str,
				table.concat(t, ","..indent_str),
				end_indent_str)
	end
	return "{"..table.concat(t, ", ").."}"
end

--------------------------------------------------------------------------------
function string.split(str, delim, include_empty, max_splits, sep_is_pattern)
	delim = delim or ","
	max_splits = max_splits or -1
	local items = {}
	local pos, len, seplen = 1, #str, #delim
	local plain = not sep_is_pattern
	max_splits = max_splits + 1
	repeat
		local np, npe = string_find(str, delim, pos, plain)
		np, npe = (np or (len+1)), (npe or (len+1))
		if (not np) or (max_splits == 1) then
			np = len + 1
			npe = np
		end
		local s = string_sub(str, pos, np - 1)
		if include_empty or (s ~= "") then
			max_splits = max_splits - 1
			items[#items + 1] = s
		end
		pos = npe + 1
	until (max_splits == 0) or (pos > (len + 1))
	return items
end

--------------------------------------------------------------------------------
function table.indexof(list, val)
	for i, v in ipairs(list) do
		if v == val then
			return i
		end
	end
	return -1
end

assert(table.indexof({"foo", "bar"}, "foo") == 1)
assert(table.indexof({"foo", "bar"}, "baz") == -1)

--------------------------------------------------------------------------------
if INIT ~= "client" then
	function file_exists(filename)
		local f = io.open(filename, "r")
		if f == nil then
			return false
		else
			f:close()
			return true
		end
	end
end
--------------------------------------------------------------------------------
function string:trim()
	return (self:gsub("^%s*(.-)%s*$", "%1"))
end

assert(string.trim("\n \t\tfoo bar\t ") == "foo bar")

--------------------------------------------------------------------------------
function math.hypot(x, y)
	local t
	x = math.abs(x)
	y = math.abs(y)
	t = math.min(x, y)
	x = math.max(x, y)
	if x == 0 then return 0 end
	t = t / x
	return x * math.sqrt(1 + t * t)
end

--------------------------------------------------------------------------------
function math.sign(x, tolerance)
	tolerance = tolerance or 0
	if x > tolerance then
		return 1
	elseif x < -tolerance then
		return -1
	end
	return 0
end

--------------------------------------------------------------------------------
function get_last_folder(text,count)
	local parts = text:split(DIR_DELIM)

	if count == nil then
		return parts[#parts]
	end

	local retval = ""
	for i=1,count,1 do
		retval = retval .. parts[#parts - (count-i)] .. DIR_DELIM
	end

	return retval
end

--------------------------------------------------------------------------------
function cleanup_path(temppath)

	local parts = temppath:split("-")
	temppath = ""
	for i=1,#parts,1 do
		if temppath ~= "" then
			temppath = temppath .. "_"
		end
		temppath = temppath .. parts[i]
	end

	parts = temppath:split(".")
	temppath = ""
	for i=1,#parts,1 do
		if temppath ~= "" then
			temppath = temppath .. "_"
		end
		temppath = temppath .. parts[i]
	end

	parts = temppath:split("'")
	temppath = ""
	for i=1,#parts,1 do
		if temppath ~= "" then
			temppath = temppath .. ""
		end
		temppath = temppath .. parts[i]
	end

	parts = temppath:split(" ")
	temppath = ""
	for i=1,#parts,1 do
		if temppath ~= "" then
			temppath = temppath
		end
		temppath = temppath .. parts[i]
	end

	return temppath
end

function core.formspec_escape(text)
	if text ~= nil then
		text = string.gsub(text,"\\","\\\\")
		text = string.gsub(text,"%]","\\]")
		text = string.gsub(text,"%[","\\[")
		text = string.gsub(text,";","\\;")
		text = string.gsub(text,",","\\,")
	end
	return text
end

function core.wrap_text(text, max_length, as_table)
	local result = {}
	local line = {}
	if #text <= max_length then
		return as_table and {text} or text
	end

	for word in text:gmatch('%S+') do
		local cur_length = #table.concat(line, ' ')
		if cur_length > 0 and cur_length + #word + 1 >= max_length then
			-- word wouldn't fit on current line, move to next line
			table.insert(result, table.concat(line, ' '))
			line = {}
		end
		table.insert(line, word)
	end

	table.insert(result, table.concat(line, ' '))
	return as_table and result or table.concat(result, '\n')
end

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

if INIT == "game" then
	local dirs1 = {9, 18, 7, 12}
	local dirs2 = {20, 23, 22, 21}

	function core.rotate_and_place(itemstack, placer, pointed_thing,
				infinitestacks, orient_flags)
		orient_flags = orient_flags or {}

		local unode = core.get_node_or_nil(pointed_thing.under)
		if not unode then
			return
		end
		local undef = core.registered_nodes[unode.name]
		if undef and undef.on_rightclick then
			return undef.on_rightclick(pointed_thing.under, unode, placer,
					itemstack, pointed_thing)
		end
		local fdir = placer and core.dir_to_facedir(placer:get_look_dir()) or 0

		local above = pointed_thing.above
		local under = pointed_thing.under
		local iswall = (above.y == under.y)
		local isceiling = not iswall and (above.y < under.y)

		if undef and undef.buildable_to then
			iswall = false
		end

		if orient_flags.force_floor then
			iswall = false
			isceiling = false
		elseif orient_flags.force_ceiling then
			iswall = false
			isceiling = true
		elseif orient_flags.force_wall then
			iswall = true
			isceiling = false
		elseif orient_flags.invert_wall then
			iswall = not iswall
		end

		local param2 = fdir
		if iswall then
			param2 = dirs1[fdir + 1]
		elseif isceiling then
			if orient_flags.force_facedir then
				cparam2 = 20
			else
				param2 = dirs2[fdir + 1]
			end
		else -- place right side up
			if orient_flags.force_facedir then
				param2 = 0
			end
		end

		local old_itemstack = ItemStack(itemstack)
		local new_itemstack, removed = core.item_place_node(
			itemstack, placer, pointed_thing, param2
		)
		return infinitestacks and old_itemstack or new_itemstack
	end

--------------------------------------------------------------------------------
--Wrapper for rotate_and_place() to check for sneak and assume Creative mode
--implies infinite stacks when performing a 6d rotation.
--------------------------------------------------------------------------------
	local creative_mode_cache = core.settings:get_bool("creative_mode")
	local function is_creative(name)
		return creative_mode_cache or
				core.check_player_privs(name, {creative = true})
	end

	core.rotate_node = function(itemstack, placer, pointed_thing)
		local name = placer and placer:get_player_name() or ""
		local invert_wall = placer and placer:get_player_control().sneak or false
		core.rotate_and_place(itemstack, placer, pointed_thing,
				is_creative(name),
				{invert_wall = invert_wall})
		return itemstack
	end
end

--------------------------------------------------------------------------------
function core.explode_table_event(evt)
	if evt ~= nil then
		local parts = evt:split(":")
		if #parts == 3 then
			local t = parts[1]:trim()
			local r = tonumber(parts[2]:trim())
			local c = tonumber(parts[3]:trim())
			if type(r) == "number" and type(c) == "number"
					and t ~= "INV" then
				return {type=t, row=r, column=c}
			end
		end
	end
	return {type="INV", row=0, column=0}
end

--------------------------------------------------------------------------------
function core.explode_textlist_event(evt)
	if evt ~= nil then
		local parts = evt:split(":")
		if #parts == 2 then
			local t = parts[1]:trim()
			local r = tonumber(parts[2]:trim())
			if type(r) == "number" and t ~= "INV" then
				return {type=t, index=r}
			end
		end
	end
	return {type="INV", index=0}
end

--------------------------------------------------------------------------------
function core.explode_scrollbar_event(evt)
	local retval = core.explode_textlist_event(evt)

	retval.value = retval.index
	retval.index = nil

	return retval
end

--------------------------------------------------------------------------------
function core.pos_to_string(pos, decimal_places)
	local x = pos.x
	local y = pos.y
	local z = pos.z
	if decimal_places ~= nil then
		x = string.format("%." .. decimal_places .. "f", x)
		y = string.format("%." .. decimal_places .. "f", y)
		z = string.format("%." .. decimal_places .. "f", z)
	end
	return "(" .. x .. "," .. y .. "," .. z .. ")"
end

--------------------------------------------------------------------------------
function core.string_to_pos(value)
	if value == nil then
		return nil
	end

	local p = {}
	p.x, p.y, p.z = string.match(value, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
	if p.x and p.y and p.z then
		p.x = tonumber(p.x)
		p.y = tonumber(p.y)
		p.z = tonumber(p.z)
		return p
	end
	local p = {}
	p.x, p.y, p.z = string.match(value, "^%( *([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+) *%)$")
	if p.x and p.y and p.z then
		p.x = tonumber(p.x)
		p.y = tonumber(p.y)
		p.z = tonumber(p.z)
		return p
	end
	return nil
end

assert(core.string_to_pos("10.0, 5, -2").x == 10)
assert(core.string_to_pos("( 10.0, 5, -2)").z == -2)
assert(core.string_to_pos("asd, 5, -2)") == nil)

--------------------------------------------------------------------------------
function core.string_to_area(value)
	local p1, p2 = unpack(value:split(") ("))
	if p1 == nil or p2 == nil then
		return nil
	end

	p1 = core.string_to_pos(p1 .. ")")
	p2 = core.string_to_pos("(" .. p2)
	if p1 == nil or p2 == nil then
		return nil
	end

	return p1, p2
end

local function test_string_to_area()
	local p1, p2 = core.string_to_area("(10.0, 5, -2) (  30.2,   4, -12.53)")
	assert(p1.x == 10.0 and p1.y == 5 and p1.z == -2)
	assert(p2.x == 30.2 and p2.y == 4 and p2.z == -12.53)

	p1, p2 = core.string_to_area("(10.0, 5, -2  30.2,   4, -12.53")
	assert(p1 == nil and p2 == nil)

	p1, p2 = core.string_to_area("(10.0, 5,) -2  fgdf2,   4, -12.53")
	assert(p1 == nil and p2 == nil)
end

test_string_to_area()

--------------------------------------------------------------------------------
function table.copy(t, seen)
	local n = {}
	seen = seen or {}
	seen[t] = n
	for k, v in pairs(t) do
		n[(type(k) == "table" and (seen[k] or table.copy(k, seen))) or k] =
			(type(v) == "table" and (seen[v] or table.copy(v, seen))) or v
	end
	return n
end
--------------------------------------------------------------------------------
-- mainmenu only functions
--------------------------------------------------------------------------------
if INIT == "mainmenu" then
	function core.get_game(index)
		local games = game.get_games()

		if index > 0 and index <= #games then
			return games[index]
		end

		return nil
	end
end

if INIT == "client" or INIT == "mainmenu" then
	function fgettext_ne(text, ...)
		text = core.gettext(text)
		local arg = {n=select('#', ...), ...}
		if arg.n >= 1 then
			-- Insert positional parameters ($1, $2, ...)
			local result = ''
			local pos = 1
			while pos <= text:len() do
				local newpos = text:find('[$]', pos)
				if newpos == nil then
					result = result .. text:sub(pos)
					pos = text:len() + 1
				else
					local paramindex =
						tonumber(text:sub(newpos+1, newpos+1))
					result = result .. text:sub(pos, newpos-1)
						.. tostring(arg[paramindex])
					pos = newpos + 2
				end
			end
			text = result
		end
		return text
	end

	function fgettext(text, ...)
		return core.formspec_escape(fgettext_ne(text, ...))
	end
end

local ESCAPE_CHAR = string.char(0x1b)

function core.get_color_escape_sequence(color)
	return ESCAPE_CHAR .. "(c@" .. color .. ")"
end

function core.get_background_escape_sequence(color)
	return ESCAPE_CHAR .. "(b@" .. color .. ")"
end

function core.colorize(color, message)
	local lines = tostring(message):split("\n", true)
	local color_code = core.get_color_escape_sequence(color)

	for i, line in ipairs(lines) do
		lines[i] = color_code .. line
	end

	return table.concat(lines, "\n") .. core.get_color_escape_sequence("#ffffff")
end

function core.strip_foreground_colors(str)
	return (str:gsub(ESCAPE_CHAR .. "%(c@[^)]+%)", ""))
end

function core.strip_background_colors(str)
	return (str:gsub(ESCAPE_CHAR .. "%(b@[^)]+%)", ""))
end

function core.strip_colors(str)
	return (str:gsub(ESCAPE_CHAR .. "%([bc]@[^)]+%)", ""))
end

--------------------------------------------------------------------------------
-- Returns the exact coordinate of a pointed surface
--------------------------------------------------------------------------------
function core.pointed_thing_to_face_pos(placer, pointed_thing)
	local eye_offset_first = placer:get_eye_offset()
	local node_pos = pointed_thing.under
	local camera_pos = placer:get_pos()
	local pos_off = vector.multiply(
			vector.subtract(pointed_thing.above, node_pos), 0.5)
	local look_dir = placer:get_look_dir()
	local offset, nc
	local oc = {}

	for c, v in pairs(pos_off) do
		if nc or v == 0 then
			oc[#oc + 1] = c
		else
			offset = v
			nc = c
		end
	end

	local fine_pos = {[nc] = node_pos[nc] + offset}
	camera_pos.y = camera_pos.y + 1.625 + eye_offset_first.y / 10
	local f = (node_pos[nc] + offset - camera_pos[nc]) / look_dir[nc]

	for i = 1, #oc do
		fine_pos[oc[i]] = camera_pos[oc[i]] + look_dir[oc[i]] * f
	end
	return fine_pos
end


code:
--- Lua module to serialize values as Lua code.
-- From: https://github.com/fab13n/metalua/blob/no-dll/src/lib/serialize.lua
-- License: MIT
-- @copyright 2006-2997 Fabien Fleutot <metalua@gmail.com>
-- @author Fabien Fleutot <metalua@gmail.com>
-- @author ShadowNinja <shadowninja@minetest.net>
--------------------------------------------------------------------------------

--- Serialize an object into a source code string. This string, when passed as
-- an argument to deserialize(), returns an object structurally identical to
-- the original one.  The following are currently supported:
--   * Booleans, numbers, strings, and nil.
--   * Functions; uses interpreter-dependent (and sometimes platform-dependent) bytecode!
--   * Tables; they can cantain multiple references and can be recursive, but metatables aren't saved.
-- This works in two phases:
--   1. Recursively find and record multiple references and recursion.
--   2. Recursively dump the value into a string.
-- @param x Value to serialize (nil is allowed).
-- @return load()able string containing the value.
function core.serialize(x)
	local local_index  = 1  -- Top index of the "_" local table in the dump
	-- table->nil/1/2 set of tables seen.
	-- nil = not seen, 1 = seen once, 2 = seen multiple times.
	local seen = {}

	-- nest_points are places where a table appears within itself, directly
	-- or not.  For instance, all of these chunks create nest points in
	-- table x: "x = {}; x[x] = 1", "x = {}; x[1] = x",
	-- "x = {}; x[1] = {y = {x}}".
	-- To handle those, two tables are used by mark_nest_point:
	-- * nested - Transient set of tables being currently traversed.
	--   Used for detecting nested tables.
	-- * nest_points - parent->{key=value, ...} table cantaining the nested
	--   keys and values in the parent.  They're all dumped after all the
	--   other table operations have been performed.
	--
	-- mark_nest_point(p, k, v) fills nest_points with information required
	-- to remember that key/value (k, v) creates a nest point  in table
	-- parent. It also marks "parent" and the nested item(s) as occuring
	-- multiple times, since several references to it will be required in
	-- order to patch the nest points.
	local nest_points  = {}
	local nested = {}
	local function mark_nest_point(parent, k, v)
		local nk, nv = nested[k], nested[v]
		local np = nest_points[parent]
		if not np then
			np = {}
			nest_points[parent] = np
		end
		np[k] = v
		seen[parent] = 2
		if nk then seen[k] = 2 end
		if nv then seen[v] = 2 end
	end

	-- First phase, list the tables and functions which appear more than
	-- once in x.
	local function mark_multiple_occurences(x)
		local tp = type(x)
		if tp ~= "table" and tp ~= "function" then
			-- No identity (comparison is done by value, not by instance)
			return
		end
		if seen[x] == 1 then
			seen[x] = 2
		elseif seen[x] ~= 2 then
			seen[x] = 1
		end

		if tp == "table" then
			nested[x] = true
			for k, v in pairs(x) do
				if nested[k] or nested[v] then
					mark_nest_point(x, k, v)
				else
					mark_multiple_occurences(k)
					mark_multiple_occurences(v)
				end
			end
			nested[x] = nil
		end
	end

	local dumped     = {}  -- object->varname set
	local local_defs = {}  -- Dumped local definitions as source code lines

	-- Mutually recursive local functions:
	local dump_val, dump_or_ref_val

	-- If x occurs multiple times, dump the local variable rather than
	-- the value. If it's the first time it's dumped, also dump the
	-- content in local_defs.
	function dump_or_ref_val(x)
		if seen[x] ~= 2 then
			return dump_val(x)
		end
		local var = dumped[x]
		if var then  -- Already referenced
			return var
		end
		-- First occurence, create and register reference
		local val = dump_val(x)
		local i = local_index
		local_index = local_index + 1
		var = "_["..i.."]"
		local_defs[#local_defs + 1] = var.." = "..val
		dumped[x] = var
		return var
	end

	-- Second phase.  Dump the object; subparts occuring multiple times
	-- are dumped in local variables which can be referenced multiple
	-- times.  Care is taken to dump local vars in a sensible order.
	function dump_val(x)
		local  tp = type(x)
		if     x  == nil        then return "nil"
		elseif tp == "string"   then return string.format("%q", x)
		elseif tp == "boolean"  then return x and "true" or "false"
		elseif tp == "function" then
			return string.format("loadstring(%q)", string.dump(x))
		elseif tp == "number"   then
			-- Serialize integers with string.format to prevent
			-- scientific notation, which doesn't preserve
			-- precision and breaks things like node position
			-- hashes.  Serialize floats normally.
			if math.floor(x) == x then
				return string.format("%d", x)
			else
				return tostring(x)
			end
		elseif tp == "table" then
			local vals = {}
			local idx_dumped = {}
			local np = nest_points[x]
			for i, v in ipairs(x) do
				if not np or not np[i] then
					vals[#vals + 1] = dump_or_ref_val(v)
				end
				idx_dumped[i] = true
			end
			for k, v in pairs(x) do
				if (not np or not np[k]) and
						not idx_dumped[k] then
					vals[#vals + 1] = "["..dump_or_ref_val(k).."] = "
						..dump_or_ref_val(v)
				end
			end
			return "{"..table.concat(vals, ", ").."}"
		else
			error("Can't serialize data of type "..tp)
		end
	end

	local function dump_nest_points()
		for parent, vals in pairs(nest_points) do
			for k, v in pairs(vals) do
				local_defs[#local_defs + 1] = dump_or_ref_val(parent)
					.."["..dump_or_ref_val(k).."] = "
					..dump_or_ref_val(v)
			end
		end
	end

	mark_multiple_occurences(x)
	local top_level = dump_or_ref_val(x)
	dump_nest_points()

	if next(local_defs) then
		return "local _ = {}\n"
			..table.concat(local_defs, "\n")
			.."\nreturn "..top_level
	else
		return "return "..top_level
	end
end

-- Deserialization

local env = {
	loadstring = loadstring,
}

local safe_env = {
	loadstring = function() end,
}

function core.deserialize(str, safe)
	if type(str) ~= "string" then
		return nil, "Cannot deserialize type '"..type(str)
			.."'. Argument must be a string."
	end
	if str:byte(1) == 0x1B then
		return nil, "Bytecode prohibited"
	end
	local f, err = loadstring(str)
	if not f then return nil, err end
	setfenv(f, safe and safe_env or env)

	local good, data = pcall(f)
	if good then
		return data
	else
		return nil, data
	end
end

-- Unit tests
local test_in = {cat={sound="nyan", speed=400}, dog={sound="woof"}}
local test_out = core.deserialize(core.serialize(test_in))

assert(test_in.cat.sound == test_out.cat.sound)
assert(test_in.cat.speed == test_out.cat.speed)
assert(test_in.dog.sound == test_out.dog.sound)

test_in = {escape_chars="\n\r\t\v\\\"\'", non_european="θשׁ٩∂"}
test_out = core.deserialize(core.serialize(test_in))
assert(test_in.escape_chars == test_out.escape_chars)
assert(test_in.non_european == test_out.non_european)


code:
-- Always warn when creating a global variable, even outside of a function.
-- This ignores mod namespaces (variables with the same name as the current mod).
local WARN_INIT = false

local getinfo = debug.getinfo

function core.global_exists(name)
	if type(name) ~= "string" then
		error("core.global_exists: " .. tostring(name) .. " is not a string")
	end
	return rawget(_G, name) ~= nil
end

local meta = {}
local declared = {}
-- Key is source file, line, and variable name; seperated by NULs
local warned = {}

function meta:__newindex(name, value)
	local info = getinfo(2, "Sl")
	local desc = ("%s:%d"):format(info.short_src, info.currentline)
	if not declared[name] then
		local warn_key = ("%s\0%d\0%s"):format(info.source,
				info.currentline, name)
		if not warned[warn_key] and info.what ~= "main" and
				info.what ~= "C" then
			core.log("warning", ("Assignment to undeclared "..
					"global %q inside a function at %s.")
				:format(name, desc))
			warned[warn_key] = true
		end
		declared[name] = true
	end
	-- Ignore mod namespaces
	if WARN_INIT and name ~= core.get_current_modname() then
		core.log("warning", ("Global variable %q created at %s.")
			:format(name, desc))
	end
	rawset(self, name, value)
end

function meta:__index(name)
	local info = getinfo(2, "Sl")
	local warn_key = ("%s\0%d\0%s"):format(info.source, info.currentline, name)
	if not declared[name] and not warned[warn_key] and info.what ~= "C" then
		core.log("warning", ("Undeclared global variable %q accessed at %s:%s")
				:format(name, info.short_src, info.currentline))
		warned[warn_key] = true
	end
	return rawget(self, name)
end

setmetatable(_G, meta)


code:
vector = {}

function vector.new(a, b, c)
	if type(a) == "table" then
		assert(a.x and a.y and a.z, "Invalid vector passed to vector.new()")
		return {x=a.x, y=a.y, z=a.z}
	elseif a then
		assert(b and c, "Invalid arguments for vector.new()")
		return {x=a, y=b, z=c}
	end
	return {x=0, y=0, z=0}
end

function vector.equals(a, b)
	return a.x == b.x and
	       a.y == b.y and
	       a.z == b.z
end

function vector.length(v)
	return math.hypot(v.x, math.hypot(v.y, v.z))
end

function vector.normalize(v)
	local len = vector.length(v)
	if len == 0 then
		return {x=0, y=0, z=0}
	else
		return vector.divide(v, len)
	end
end

function vector.floor(v)
	return {
		x = math.floor(v.x),
		y = math.floor(v.y),
		z = math.floor(v.z)
	}
end

function vector.round(v)
	return {
		x = math.floor(v.x + 0.5),
		y = math.floor(v.y + 0.5),
		z = math.floor(v.z + 0.5)
	}
end

function vector.apply(v, func)
	return {
		x = func(v.x),
		y = func(v.y),
		z = func(v.z)
	}
end

function vector.distance(a, b)
	local x = a.x - b.x
	local y = a.y - b.y
	local z = a.z - b.z
	return math.hypot(x, math.hypot(y, z))
end

function vector.direction(pos1, pos2)
	local x_raw = pos2.x - pos1.x
	local y_raw = pos2.y - pos1.y
	local z_raw = pos2.z - pos1.z
	local x_abs = math.abs(x_raw)
	local y_abs = math.abs(y_raw)
	local z_abs = math.abs(z_raw)
	if x_abs >= y_abs and
	   x_abs >= z_abs then
		y_raw = y_raw * (1 / x_abs)
		z_raw = z_raw * (1 / x_abs)
		x_raw = x_raw / x_abs
	end
	if y_abs >= x_abs and
	   y_abs >= z_abs then
		x_raw = x_raw * (1 / y_abs)
		z_raw = z_raw * (1 / y_abs)
		y_raw = y_raw / y_abs
	end
	if z_abs >= y_abs and
	   z_abs >= x_abs then
		x_raw = x_raw * (1 / z_abs)
		y_raw = y_raw * (1 / z_abs)
		z_raw = z_raw / z_abs
	end
	return {x=x_raw, y=y_raw, z=z_raw}
end

function vector.add(a, b)
	if type(b) == "table" then
		return {x = a.x + b.x,
			y = a.y + b.y,
			z = a.z + b.z}
	else
		return {x = a.x + b,
			y = a.y + b,
			z = a.z + b}
	end
end

function vector.subtract(a, b)
	if type(b) == "table" then
		return {x = a.x - b.x,
			y = a.y - b.y,
			z = a.z - b.z}
	else
		return {x = a.x - b,
			y = a.y - b,
			z = a.z - b}
	end
end

function vector.multiply(a, b)
	if type(b) == "table" then
		return {x = a.x * b.x,
			y = a.y * b.y,
			z = a.z * b.z}
	else
		return {x = a.x * b,
			y = a.y * b,
			z = a.z * b}
	end
end

function vector.divide(a, b)
	if type(b) == "table" then
		return {x = a.x / b.x,
			y = a.y / b.y,
			z = a.z / b.z}
	else
		return {x = a.x / b,
			y = a.y / b,
			z = a.z / b}
	end
end

function vector.sort(a, b)
	return {x = math.min(a.x, b.x), y = math.min(a.y, b.y), z = math.min(a.z, b.z)},
		{x = math.max(a.x, b.x), y = math.max(a.y, b.y), z = math.max(a.z, b.z)}
end


code:
--Minetest
--Copyright (C) 2014 sapier
--
--This program is free software; you can redistribute it and/or modify
--it under the terms of the GNU Lesser General Public License as published by
--the Free Software Foundation; either version 2.1 of the License, or
--(at your option) any later version.
--
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
--GNU Lesser General Public License for more details.
--
--You should have received a copy of the GNU Lesser General Public License along
--with this program; if not, write to the Free Software Foundation, Inc.,
--51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

local function buttonbar_formspec(self)

	if self.hidden then
		return ""
	end

	local formspec = string.format("box[%f,%f;%f,%f;%s]",
			self.pos.x,self.pos.y ,self.size.x,self.size.y,self.bgcolor)

	for i=self.startbutton,#self.buttons,1 do
		local btn_name = self.buttons[i].name
		local btn_pos = {}

		if self.orientation == "horizontal" then
			btn_pos.x = self.pos.x + --base pos
			(i - self.startbutton) * self.btn_size +       --button offset
			self.btn_initial_offset
		else
			btn_pos.x = self.pos.x + (self.btn_size * 0.05)
		end

		if self.orientation == "vertical" then
			btn_pos.y = self.pos.y + --base pos
			(i - self.startbutton) * self.btn_size +       --button offset
			self.btn_initial_offset
		else
			btn_pos.y = self.pos.y + (self.btn_size * 0.05)
		end

		if (self.orientation == "vertical" and
			(btn_pos.y + self.btn_size <= self.pos.y + self.size.y)) or
			(self.orientation == "horizontal" and
			(btn_pos.x + self.btn_size <= self.pos.x + self.size.x)) then

		local borders="true"

		if self.buttons[i].image ~= nil then
			borders="false"
		end

		formspec = formspec ..
			string.format("image_button[%f,%f;%f,%f;%s;%s;%s;true;%s]tooltip[%s;%s]",
					btn_pos.x, btn_pos.y, self.btn_size, self.btn_size,
					self.buttons[i].image, btn_name, self.buttons[i].caption,
					borders, btn_name, self.buttons[i].tooltip)
		else
			--print("end of displayable buttons: orientation: " .. self.orientation)
			--print( "button_end: " .. (btn_pos.y + self.btn_size - (self.btn_size * 0.05)))
			--print( "bar_end: " .. (self.pos.x + self.size.x))
			break
		end
	end

	if (self.have_move_buttons) then
		local btn_dec_pos = {}
		btn_dec_pos.x = self.pos.x + (self.btn_size * 0.05)
		btn_dec_pos.y = self.pos.y + (self.btn_size * 0.05)
		local btn_inc_pos = {}
		local btn_size = {}

		if self.orientation == "horizontal" then
			btn_size.x = 0.5
			btn_size.y = self.btn_size
			btn_inc_pos.x = self.pos.x + self.size.x - 0.5
			btn_inc_pos.y = self.pos.y + (self.btn_size * 0.05)
		else
			btn_size.x = self.btn_size
			btn_size.y = 0.5
			btn_inc_pos.x = self.pos.x + (self.btn_size * 0.05)
			btn_inc_pos.y = self.pos.y + self.size.y - 0.5
		end

		local text_dec = "<"
		local text_inc = ">"
		if self.orientation == "vertical" then
			text_dec = "^"
			text_inc = "v"
		end

		formspec = formspec ..
			string.format("image_button[%f,%f;%f,%f;;btnbar_dec_%s;%s;true;true]",
					btn_dec_pos.x, btn_dec_pos.y, btn_size.x, btn_size.y,
					self.name, text_dec)

		formspec = formspec ..
			string.format("image_button[%f,%f;%f,%f;;btnbar_inc_%s;%s;true;true]",
					btn_inc_pos.x, btn_inc_pos.y, btn_size.x, btn_size.y,
					 self.name, text_inc)
	end

	return formspec
end

local function buttonbar_buttonhandler(self, fields)

	if fields["btnbar_inc_" .. self.name] ~= nil and
		self.startbutton < #self.buttons then

		self.startbutton = self.startbutton + 1
		return true
	end

	if fields["btnbar_dec_" .. self.name] ~= nil and self.startbutton > 1 then
		self.startbutton = self.startbutton - 1
		return true
	end

	for i=1,#self.buttons,1 do
		if fields[self.buttons[i].name] ~= nil then
			return self.userbuttonhandler(fields)
		end
	end
end

local buttonbar_metatable = {
	handle_buttons = buttonbar_buttonhandler,
	handle_events  = function(self, event) end,
	get_formspec   = buttonbar_formspec,

	hide = function(self) self.hidden = true end,
	show = function(self) self.hidden = false end,

	delete = function(self) ui.delete(self) end,

	add_button = function(self, name, caption, image, tooltip)
			if caption == nil then caption = "" end
			if image == nil then image = "" end
			if tooltip == nil then tooltip = "" end

			self.buttons[#self.buttons + 1] = {
				name = name,
				caption = caption,
				image = image,
				tooltip = tooltip
			}
			if self.orientation == "horizontal" then
				if ( (self.btn_size * #self.buttons) + (self.btn_size * 0.05 *2)
					> self.size.x ) then

					self.btn_initial_offset = self.btn_size * 0.05 + 0.5
					self.have_move_buttons = true
				end
			else
				if ((self.btn_size * #self.buttons) + (self.btn_size * 0.05 *2)
					> self.size.y ) then

					self.btn_initial_offset = self.btn_size * 0.05 + 0.5
					self.have_move_buttons = true
				end
			end
		end,

	set_bgparams = function(self, bgcolor)
			if (type(bgcolor) == "string") then
				self.bgcolor = bgcolor
			end
		end,
}

buttonbar_metatable.__index = buttonbar_metatable

function buttonbar_create(name, cbf_buttonhandler, pos, orientation, size)
	assert(name ~= nil)
	assert(cbf_buttonhandler ~= nil)
	assert(orientation == "vertical" or orientation == "horizontal")
	assert(pos ~= nil and type(pos) == "table")
	assert(size ~= nil and type(size) == "table")

	local self = {}
	self.name = name
	self.type = "addon"
	self.bgcolor = "#000000"
	self.pos = pos
	self.size = size
	self.orientation = orientation
	self.startbutton = 1
	self.have_move_buttons = false
	self.hidden = false

	if self.orientation == "horizontal" then
			self.btn_size = self.size.y
	else
			self.btn_size = self.size.x
	end

	if (self.btn_initial_offset == nil) then
		self.btn_initial_offset = self.btn_size * 0.05
	end

	self.userbuttonhandler = cbf_buttonhandler
	self.buttons = {}

	setmetatable(self,buttonbar_metatable)

	ui.add(self)
	return self
end


code:
--Minetest
--Copyright (C) 2014 sapier
--
--This program is free software; you can redistribute it and/or modify
--it under the terms of the GNU Lesser General Public License as published by
--the Free Software Foundation; either version 2.1 of the License, or
--(at your option) any later version.
--
--this program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
--GNU Lesser General Public License for more details.
--
--You should have received a copy of the GNU Lesser General Public License along
--with this program; if not, write to the Free Software Foundation, Inc.,
--51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

local function dialog_event_handler(self,event)
	if self.user_eventhandler == nil or
		self.user_eventhandler(event) == false then

		--close dialog on esc
		if event == "MenuQuit" then
			self:delete()
			return true
		end
	end
end

local dialog_metatable = {
	eventhandler = dialog_event_handler,
	get_formspec = function(self)
				if not self.hidden then return self.formspec(self.data) end
			end,
	handle_buttons = function(self,fields)
				if not self.hidden then return self.buttonhandler(self,fields) end
			end,
	handle_events  = function(self,event)
				if not self.hidden then return self.eventhandler(self,event) end
			end,
	hide = function(self) self.hidden = true end,
	show = function(self) self.hidden = false end,
	delete = function(self)
			if self.parent ~= nil then
				self.parent:show()
			end
			ui.delete(self)
		end,
	set_parent = function(self,parent) self.parent = parent end
}
dialog_metatable.__index = dialog_metatable

function dialog_create(name,get_formspec,buttonhandler,eventhandler)
	local self = {}

	self.name = name
	self.type = "toplevel"
	self.hidden = true
	self.data = {}

	self.formspec      = get_formspec
	self.buttonhandler = buttonhandler
	self.user_eventhandler  = eventhandler

	setmetatable(self,dialog_metatable)

	ui.add(self)
	return self
end


code:
--Minetest
--Copyright (C) 2014 sapier
--
--This program is free software; you can redistribute it and/or modify
--it under the terms of the GNU Lesser General Public License as published by
--the Free Software Foundation; either version 2.1 of the License, or
--(at your option) any later version.
--
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
--GNU Lesser General Public License for more details.
--
--You should have received a copy of the GNU Lesser General Public License along
--with this program; if not, write to the Free Software Foundation, Inc.,
--51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

--------------------------------------------------------------------------------
-- A tabview implementation                                                   --
-- Usage:                                                                     --
-- tabview.create: returns initialized tabview raw element                    --
-- element.add(tab): add a tab declaration                                    --
-- element.handle_buttons()                                                   --
-- element.handle_events()                                                    --
-- element.getFormspec() returns formspec of tabview                          --
--------------------------------------------------------------------------------

--------------------------------------------------------------------------------
local function add_tab(self,tab)
	assert(tab.size == nil or (type(tab.size) == table and
			tab.size.x ~= nil and tab.size.y ~= nil))
	assert(tab.cbf_formspec ~= nil and type(tab.cbf_formspec) == "function")
	assert(tab.cbf_button_handler == nil or
			type(tab.cbf_button_handler) == "function")
	assert(tab.cbf_events == nil or type(tab.cbf_events) == "function")

	local newtab = {
		name = tab.name,
		caption = tab.caption,
		button_handler = tab.cbf_button_handler,
		event_handler = tab.cbf_events,
		get_formspec = tab.cbf_formspec,
		tabsize = tab.tabsize,
		on_change = tab.on_change,
		tabdata = {},
	}

	self.tablist[#self.tablist + 1] = newtab

	if self.last_tab_index == #self.tablist then
		self.current_tab = tab.name
		if tab.on_activate ~= nil then
			tab.on_activate(nil,tab.name)
		end
	end
end

--------------------------------------------------------------------------------
local function get_formspec(self)
	local formspec = ""

	if not self.hidden and (self.parent == nil or not self.parent.hidden) then

		if self.parent == nil then
			local tsize = self.tablist[self.last_tab_index].tabsize or
					{width=self.width, height=self.height}
			formspec = formspec ..
					string.format("size[%f,%f,%s]",tsize.width,tsize.height,
						dump(self.fixed_size))
		end
		formspec = formspec .. self:tab_header()
		formspec = formspec ..
				self.tablist[self.last_tab_index].get_formspec(
					self,
					self.tablist[self.last_tab_index].name,
					self.tablist[self.last_tab_index].tabdata,
					self.tablist[self.last_tab_index].tabsize
					)
	end
	return formspec
end

--------------------------------------------------------------------------------
local function handle_buttons(self,fields)

	if self.hidden then
		return false
	end

	if self:handle_tab_buttons(fields) then
		return true
	end

	if self.glb_btn_handler ~= nil and
		self.glb_btn_handler(self,fields) then
		return true
	end

	if self.tablist[self.last_tab_index].button_handler ~= nil then
		return
			self.tablist[self.last_tab_index].button_handler(
					self,
					fields,
					self.tablist[self.last_tab_index].name,
					self.tablist[self.last_tab_index].tabdata
					)
	end

	return false
end

--------------------------------------------------------------------------------
local function handle_events(self,event)

	if self.hidden then
		return false
	end

	if self.glb_evt_handler ~= nil and
		self.glb_evt_handler(self,event) then
		return true
	end

	if self.tablist[self.last_tab_index].evt_handler ~= nil then
		return
			self.tablist[self.last_tab_index].evt_handler(
					self,
					event,
					self.tablist[self.last_tab_index].name,
					self.tablist[self.last_tab_index].tabdata
					)
	end

	return false
end

--------------------------------------------------------------------------------
local function tab_header(self)

	local toadd = ""

	for i=1,#self.tablist,1 do

		if toadd ~= "" then
			toadd = toadd .. ","
		end

		toadd = toadd .. self.tablist[i].caption
	end
	return string.format("tabheader[%f,%f;%s;%s;%i;true;false]",
			self.header_x, self.header_y, self.name, toadd, self.last_tab_index);
end

--------------------------------------------------------------------------------
local function switch_to_tab(self, index)
	--first call on_change for tab to leave
	if self.tablist[self.last_tab_index].on_change ~= nil then
		self.tablist[self.last_tab_index].on_change("LEAVE",
				self.current_tab, self.tablist[index].name)
	end

	--update tabview data
	self.last_tab_index = index
	local old_tab = self.current_tab
	self.current_tab = self.tablist[index].name

	if (self.autosave_tab) then
		core.settings:set(self.name .. "_LAST",self.current_tab)
	end

	-- call for tab to enter
	if self.tablist[index].on_change ~= nil then
		self.tablist[index].on_change("ENTER",
				old_tab,self.current_tab)
	end
end

--------------------------------------------------------------------------------
local function handle_tab_buttons(self,fields)
	--save tab selection to config file
	if fields[self.name] then
		local index = tonumber(fields[self.name])
		switch_to_tab(self, index)
		return true
	end

	return false
end

--------------------------------------------------------------------------------
local function set_tab_by_name(self, name)
	for i=1,#self.tablist,1 do
		if self.tablist[i].name == name then
			switch_to_tab(self, i)
			return true
		end
	end

	return false
end

--------------------------------------------------------------------------------
local function hide_tabview(self)
	self.hidden=true

	--call on_change as we're not gonna show self tab any longer
	if self.tablist[self.last_tab_index].on_change ~= nil then
		self.tablist[self.last_tab_index].on_change("LEAVE",
				self.current_tab, nil)
	end
end

--------------------------------------------------------------------------------
local function show_tabview(self)
	self.hidden=false

	-- call for tab to enter
	if self.tablist[self.last_tab_index].on_change ~= nil then
		self.tablist[self.last_tab_index].on_change("ENTER",
				nil,self.current_tab)
	end
end

local tabview_metatable = {
	add                       = add_tab,
	handle_buttons            = handle_buttons,
	handle_events             = handle_events,
	get_formspec              = get_formspec,
	show                      = show_tabview,
	hide                      = hide_tabview,
	delete                    = function(self) ui.delete(self) end,
	set_parent                = function(self,parent) self.parent = parent end,
	set_autosave_tab          =
			function(self,value) self.autosave_tab = value end,
	set_tab                   = set_tab_by_name,
	set_global_button_handler =
			function(self,handler) self.glb_btn_handler = handler end,
	set_global_event_handler =
			function(self,handler) self.glb_evt_handler = handler end,
	set_fixed_size =
			function(self,state) self.fixed_size = state end,
	tab_header = tab_header,
	handle_tab_buttons = handle_tab_buttons
}

tabview_metatable.__index = tabview_metatable

--------------------------------------------------------------------------------
function tabview_create(name, size, tabheaderpos)
	local self = {}

	self.name     = name
	self.type     = "toplevel"
	self.width    = size.x
	self.height   = size.y
	self.header_x = tabheaderpos.x
	self.header_y = tabheaderpos.y

	setmetatable(self, tabview_metatable)

	self.fixed_size     = true
	self.hidden         = true
	self.current_tab    = nil
	self.last_tab_index = 1
	self.tablist        = {}

	self.autosave_tab   = false

	ui.add(self)
	return self
end


code:
--Minetest
--Copyright (C) 2014 sapier
--
--This program is free software; you can redistribute it and/or modify
--it under the terms of the GNU Lesser General Public License as published by
--the Free Software Foundation; either version 2.1 of the License, or
--(at your option) any later version.
--
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
--GNU Lesser General Public License for more details.
--
--You should have received a copy of the GNU Lesser General Public License along
--with this program; if not, write to the Free Software Foundation, Inc.,
--51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

ui = {}
ui.childlist = {}
ui.default = nil

--------------------------------------------------------------------------------
function ui.add(child)
	--TODO check child
	ui.childlist[child.name] = child

	return child.name
end

--------------------------------------------------------------------------------
function ui.delete(child)

	if ui.childlist[child.name] == nil then
		return false
	end

	ui.childlist[child.name] = nil
	return true
end

--------------------------------------------------------------------------------
function ui.set_default(name)
	ui.default = name
end

--------------------------------------------------------------------------------
function ui.find_by_name(name)
	return ui.childlist[name]
end

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Internal functions not to be called from user
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------

local function wordwrap_quickhack(str)
	local res = ""
	local ar = str:split("\n")
	for i = 1, #ar do
		local text = ar[i]
		-- Hack to add word wrapping.
		-- TODO: Add engine support for wrapping in formspecs
		while #text > 80 do
			if res ~= "" then
				res = res .. ","
			end
			res = res .. core.formspec_escape(string.sub(text, 1, 79))
			text = string.sub(text, 80, #text)
		end
		if res ~= "" then
			res = res .. ","
		end
		res = res .. core.formspec_escape(text)
	end
	return res
end

--------------------------------------------------------------------------------
function ui.update()
	local formspec = ""

	-- handle errors
	if gamedata ~= nil and gamedata.reconnect_requested then
		formspec = wordwrap_quickhack(gamedata.errormessage or "")
		formspec = "size[12,5]" ..
				"label[0.5,0;" .. fgettext("The server has requested a reconnect:") ..
				"]textlist[0.2,0.8;11.5,3.5;;" .. formspec ..
				"]button[6,4.6;3,0.5;btn_reconnect_no;" .. fgettext("Main menu") .. "]" ..
				"button[3,4.6;3,0.5;btn_reconnect_yes;" .. fgettext("Reconnect") .. "]"
	elseif gamedata ~= nil and gamedata.errormessage ~= nil then
		formspec = wordwrap_quickhack(gamedata.errormessage)
		local error_title
		if string.find(gamedata.errormessage, "ModError") then
			error_title = fgettext("An error occured in a Lua script, such as a mod:")
		else
			error_title = fgettext("An error occured:")
		end
		formspec = "size[12,5]" ..
				"label[0.5,0;" .. error_title ..
				"]textlist[0.2,0.8;11.5,3.5;;" .. formspec ..
				"]button[4.5,4.6;3,0.5;btn_error_confirm;" .. fgettext("Ok") .. "]"
	else
		local active_toplevel_ui_elements = 0
		for key,value in pairs(ui.childlist) do
			if (value.type == "toplevel") then
				local retval = value:get_formspec()

				if retval ~= nil and retval ~= "" then
					active_toplevel_ui_elements = active_toplevel_ui_elements +1
					formspec = formspec .. retval
				end
			end
		end

		-- no need to show addons if there ain't a toplevel element
		if (active_toplevel_ui_elements > 0) then
			for key,value in pairs(ui.childlist) do
				if (value.type == "addon") then
					local retval = value:get_formspec()

					if retval ~= nil and retval ~= "" then
						formspec = formspec .. retval
					end
				end
			end
		end

		if (active_toplevel_ui_elements > 1) then
			core.log("warning", "more than one active ui "..
				"element, self most likely isn't intended")
		end

		if (active_toplevel_ui_elements == 0) then
			core.log("warning", "no toplevel ui element "..
					"active; switching to default")
			ui.childlist[ui.default]:show()
			formspec = ui.childlist[ui.default]:get_formspec()
		end
	end
	core.update_formspec(formspec)
end

--------------------------------------------------------------------------------
function ui.handle_buttons(fields)
	for key,value in pairs(ui.childlist) do

		local retval = value:handle_buttons(fields)

		if retval then
			ui.update()
			return
		end
	end
end

--------------------------------------------------------------------------------
function ui.handle_events(event)

	for key,value in pairs(ui.childlist) do

		if value.handle_events ~= nil then
			local retval = value:handle_events(event)

			if retval then
				return retval
			end
		end
	end
end

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- initialize callbacks
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
core.button_handler = function(fields)
	if fields["btn_reconnect_yes"] then
		gamedata.reconnect_requested = false
		gamedata.errormessage = nil
		gamedata.do_reconnect = true
		core.start()
		return
	elseif fields["btn_reconnect_no"] or fields["btn_error_confirm"] then
		gamedata.errormessage = nil
		gamedata.reconnect_requested = false
		ui.update()
		return
	end

	if ui.handle_buttons(fields) then
		ui.update()
	end
end

--------------------------------------------------------------------------------
core.event_handler = function(event)
	if ui.handle_events(event) then
		ui.update()
		return
	end

	if event == "Refresh" then
		ui.update()
		return
	end
end


code:
-- Minetest: builtin/auth.lua

--
-- Authentication handler
--

function core.string_to_privs(str, delim)
	assert(type(str) == "string")
	delim = delim or ','
	local privs = {}
	for _, priv in pairs(string.split(str, delim)) do
		privs[priv:trim()] = true
	end
	return privs
end

function core.privs_to_string(privs, delim)
	assert(type(privs) == "table")
	delim = delim or ','
	local list = {}
	for priv, bool in pairs(privs) do
		if bool then
			list[#list + 1] = priv
		end
	end
	return table.concat(list, delim)
end

assert(core.string_to_privs("a,b").b == true)
assert(core.privs_to_string({a=true,b=true}) == "a,b")

core.auth_file_path = core.get_worldpath().."/auth.txt"
core.auth_table = {}

local function read_auth_file()
	local newtable = {}
	local file, errmsg = io.open(core.auth_file_path, 'rb')
	if not file then
		core.log("info", core.auth_file_path.." could not be opened for reading ("..errmsg.."); assuming new world")
		return
	end
	for line in file:lines() do
		if line ~= "" then
			local fields = line:split(":", true)
			local name, password, privilege_string, last_login = unpack(fields)
			last_login = tonumber(last_login)
			if not (name and password and privilege_string) then
				error("Invalid line in auth.txt: "..dump(line))
			end
			local privileges = core.string_to_privs(privilege_string)
			newtable[name] = {password=password, privileges=privileges, last_login=last_login}
		end
	end
	io.close(file)
	core.auth_table = newtable
	core.notify_authentication_modified()
end

local function save_auth_file()
	local newtable = {}
	-- Check table for validness before attempting to save
	for name, stuff in pairs(core.auth_table) do
		assert(type(name) == "string")
		assert(name ~= "")
		assert(type(stuff) == "table")
		assert(type(stuff.password) == "string")
		assert(type(stuff.privileges) == "table")
		assert(stuff.last_login == nil or type(stuff.last_login) == "number")
	end
	local content = ""
	for name, stuff in pairs(core.auth_table) do
		local priv_string = core.privs_to_string(stuff.privileges)
		local parts = {name, stuff.password, priv_string, stuff.last_login or ""}
		content = content .. table.concat(parts, ":") .. "\n"
	end
	if not core.safe_file_write(core.auth_file_path, content) then
		error(core.auth_file_path.." could not be written to")
	end
end

read_auth_file()

core.builtin_auth_handler = {
	get_auth = function(name)
		assert(type(name) == "string")
		-- Figure out what password to use for a new player (singleplayer
		-- always has an empty password, otherwise use default, which is
		-- usually empty too)
		local new_password_hash = ""
		-- If not in authentication table, return nil
		if not core.auth_table[name] then
			return nil
		end
		-- Figure out what privileges the player should have.
		-- Take a copy of the privilege table
		local privileges = {}
		for priv, _ in pairs(core.auth_table[name].privileges) do
			privileges[priv] = true
		end
		-- If singleplayer, give all privileges except those marked as give_to_singleplayer = false
		if core.is_singleplayer() then
			for priv, def in pairs(core.registered_privileges) do
				if def.give_to_singleplayer then
					privileges[priv] = true
				end
			end
		-- For the admin, give everything
		elseif name == core.settings:get("name") then
			for priv, def in pairs(core.registered_privileges) do
				privileges[priv] = true
			end
		end
		-- All done
		return {
			password = core.auth_table[name].password,
			privileges = privileges,
			-- Is set to nil if unknown
			last_login = core.auth_table[name].last_login,
		}
	end,
	create_auth = function(name, password)
		assert(type(name) == "string")
		assert(type(password) == "string")
		core.log('info', "Built-in authentication handler adding player '"..name.."'")
		core.auth_table[name] = {
			password = password,
			privileges = core.string_to_privs(core.settings:get("default_privs")),
			last_login = os.time(),
		}
		save_auth_file()
	end,
	set_password = function(name, password)
		assert(type(name) == "string")
		assert(type(password) == "string")
		if not core.auth_table[name] then
			core.builtin_auth_handler.create_auth(name, password)
		else
			core.log('info', "Built-in authentication handler setting password of player '"..name.."'")
			core.auth_table[name].password = password
			save_auth_file()
		end
		return true
	end,
	set_privileges = function(name, privileges)
		assert(type(name) == "string")
		assert(type(privileges) == "table")
		if not core.auth_table[name] then
			core.builtin_auth_handler.create_auth(name,
				core.get_password_hash(name,
					core.settings:get("default_password")))
		end
		core.auth_table[name].privileges = privileges
		core.notify_authentication_modified(name)
		save_auth_file()
	end,
	reload = function()
		read_auth_file()
		return true
	end,
	record_login = function(name)
		assert(type(name) == "string")
		assert(core.auth_table[name]).last_login = os.time()
		save_auth_file()
	end,
}

function core.register_authentication_handler(handler)
	if core.registered_auth_handler then
		error("Add-on authentication handler already registered by "..core.registered_auth_handler_modname)
	end
	core.registered_auth_handler = handler
	core.registered_auth_handler_modname = core.get_current_modname()
	handler.mod_origin = core.registered_auth_handler_modname
end

function core.get_auth_handler()
	return core.registered_auth_handler or core.builtin_auth_handler
end

local function auth_pass(name)
	return function(...)
		local auth_handler = core.get_auth_handler()
		if auth_handler[name] then
			return auth_handler[name](...)
		end
		return false
	end
end

core.set_player_password = auth_pass("set_password")
core.set_player_privs    = auth_pass("set_privileges")
core.auth_reload         = auth_pass("reload")

local record_login = auth_pass("record_login")

core.register_on_joinplayer(function(player)
	record_login(player:get_player_name())
end)

core.register_on_prejoinplayer(function(name, ip)
	local auth = core.auth_table
	if auth[name] ~= nil then
		return
	end

	local name_lower = name:lower()
	for k in pairs(auth) do
		if k:lower() == name_lower then
			return string.format("\nCannot create new player called '%s'. "..
					"Another account called '%s' is already registered. "..
					"Please check the spelling if it's your account "..
					"or use a different nickname.", name, k)
		end
	end
end)