Merge branch 'master' of git://github.com/quietust/dfhack

develop
jj 2012-08-23 17:19:15 +02:00
commit 5b0f37276f
46 changed files with 3647 additions and 118 deletions

@ -111,6 +111,9 @@ IF(UNIX)
SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-g -Wall -Wno-unused-variable")
SET(CMAKE_CXX_FLAGS "-fvisibility=hidden -m32 -march=i686 -mtune=generic -std=c++0x")
SET(CMAKE_C_FLAGS "-fvisibility=hidden -m32 -march=i686 -mtune=generic")
ELSEIF(MSVC)
# for msvc, tell it to always use 8-byte pointers to member functions to avoid confusion
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /vmg /vmm")
ENDIF()
# use shared libraries for protobuf

@ -1204,6 +1204,152 @@ Constructions module
Returns *true, was_only_planned* if removed; or *false* if none found.
Screen API
----------
The screen module implements support for drawing to the tiled screen of the game.
Note that drawing only has any effect when done from callbacks, so it can only
be feasibly used in the core context.
Basic painting functions:
* ``dfhack.screen.getWindowSize()``
Returns *width, height* of the screen.
* ``dfhack.screen.getMousePos()``
Returns *x,y* of the tile the mouse is over.
* ``dfhack.screen.inGraphicsMode()``
Checks if [GRAPHICS:YES] was specified in init.
* ``dfhack.screen.paintTile(pen,x,y[,char,tile])``
Paints a tile using given parameters. Pen is a table with following possible fields:
``ch``
Provides the ordinary tile character, as either a 1-character string or a number.
Can be overridden with the ``char`` function parameter.
``fg``
Foreground color for the ordinary tile. Defaults to COLOR_GREY (7).
``bg``
Background color for the ordinary tile. Defaults to COLOR_BLACK (0).
``bold``
Bright/bold text flag. If *nil*, computed based on (fg & 8); fg is masked to 3 bits.
Otherwise should be *true/false*.
``tile``
Graphical tile id. Ignored unless [GRAPHICS:YES] was in init.txt.
``tile_color = true``
Specifies that the tile should be shaded with *fg/bg*.
``tile_fg, tile_bg``
If specified, overrides *tile_color* and supplies shading colors directly.
Returns *false* if coordinates out of bounds, or other error.
* ``dfhack.screen.paintString(pen,x,y,text)``
Paints the string starting at *x,y*. Uses the string characters
in sequence to override the ``ch`` field of pen.
Returns *true* if painting at least one character succeeded.
* ``dfhack.screen.fillRect(pen,x1,y1,x2,y2)``
Fills the rectangle specified by the coordinates with the given pen.
Returns *true* if painting at least one character succeeded.
* ``dfhack.screen.findGraphicsTile(pagename,x,y)``
Finds a tile from a graphics set (i.e. the raws used for creatures),
if in graphics mode and loaded.
Returns: *tile, tile_grayscale*, or *nil* if not found.
The values can then be used for the *tile* field of *pen* structures.
* ``dfhack.screen.clear()``
Fills the screen with blank background.
* ``dfhack.screen.invalidate()``
Requests repaint of the screen by setting a flag. Unlike other
functions in this section, this may be used at any time.
In order to actually be able to paint to the screen, it is necessary
to create and register a viewscreen (basically a modal dialog) with
the game.
**NOTE**: As a matter of policy, in order to avoid user confusion, all
interface screens added by dfhack should bear the "DFHack" signature.
Screens are managed with the following functions:
* ``dfhack.screen.show(screen[,below])``
Displays the given screen, possibly placing it below a different one.
The screen must not be already shown. Returns *true* if success.
* ``dfhack.screen.dismiss(screen)``
Marks the screen to be removed when the game enters its event loop.
* ``dfhack.screen.isDismissed(screen)``
Checks if the screen is already marked for removal.
Apart from a native viewscreen object, these functions accept a table
as a screen. In this case, ``show`` creates a new native viewscreen
that delegates all processing to methods stored in that table.
**NOTE**: Lua-implemented screens are only supported in the core context.
Supported callbacks and fields are:
* ``screen._native``
Initialized by ``show`` with a reference to the backing viewscreen
object, and removed again when the object is deleted.
* ``function screen:onDestroy()``
Called from the destructor when the viewscreen is deleted.
* ``function screen:onRender()``
Called when the viewscreen should paint itself. This is the only context
where the above painting functions work correctly.
If omitted, the screen is cleared; otherwise it should do that itself.
In order to make a see-through dialog, call ``self._native.parent:render()``.
* ``function screen:onIdle()``
Called every frame when the screen is on top of the stack.
* ``function screen:onHelp()``
Called when the help keybinding is activated (usually '?').
* ``function screen:onInput(keys)``
Called when keyboard or mouse events are available.
If any keys are pressed, the keys argument is a table mapping them to *true*.
Note that this refers to logical keybingings computed from real keys via
options; if multiple interpretations exist, the table will contain multiple keys.
The table also may contain special keys:
``_STRING``
Maps to an integer in range 0-255. Duplicates a separate "STRING_A???" code for convenience.
``_MOUSE_L, _MOUSE_R``
If the left or right mouse button is pressed.
If this method is omitted, the screen is dismissed on receival of the ``LEAVESCREEN`` key.
Internal API
------------
@ -1235,6 +1381,12 @@ and are only documented here for completeness:
Returns a sequence of tables describing virtual memory ranges of the process.
* ``dfhack.internal.patchMemory(dest,src,count)``
Like memmove below, but works even if dest is read-only memory, e.g. code.
If destination overlaps a completely invalid memory region, or another error
occurs, returns false.
* ``dfhack.internal.memmove(dest,src,count)``
Wraps the standard memmove function. Accepts both numbers and refs as pointers.

@ -3,7 +3,7 @@
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.9: http://docutils.sourceforge.net/" />
<meta name="generator" content="Docutils 0.8.1: http://docutils.sourceforge.net/" />
<title>DFHack Lua API</title>
<style type="text/css">
@ -351,27 +351,28 @@ ul.auto-toc {
<li><a class="reference internal" href="#burrows-module" id="id23">Burrows module</a></li>
<li><a class="reference internal" href="#buildings-module" id="id24">Buildings module</a></li>
<li><a class="reference internal" href="#constructions-module" id="id25">Constructions module</a></li>
<li><a class="reference internal" href="#internal-api" id="id26">Internal API</a></li>
<li><a class="reference internal" href="#screen-api" id="id26">Screen API</a></li>
<li><a class="reference internal" href="#internal-api" id="id27">Internal API</a></li>
</ul>
</li>
<li><a class="reference internal" href="#core-interpreter-context" id="id27">Core interpreter context</a><ul>
<li><a class="reference internal" href="#event-type" id="id28">Event type</a></li>
<li><a class="reference internal" href="#core-interpreter-context" id="id28">Core interpreter context</a><ul>
<li><a class="reference internal" href="#event-type" id="id29">Event type</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="reference internal" href="#lua-modules" id="id29">Lua Modules</a><ul>
<li><a class="reference internal" href="#global-environment" id="id30">Global environment</a></li>
<li><a class="reference internal" href="#utils" id="id31">utils</a></li>
<li><a class="reference internal" href="#dumper" id="id32">dumper</a></li>
<li><a class="reference internal" href="#lua-modules" id="id30">Lua Modules</a><ul>
<li><a class="reference internal" href="#global-environment" id="id31">Global environment</a></li>
<li><a class="reference internal" href="#utils" id="id32">utils</a></li>
<li><a class="reference internal" href="#dumper" id="id33">dumper</a></li>
</ul>
</li>
<li><a class="reference internal" href="#plugins" id="id33">Plugins</a><ul>
<li><a class="reference internal" href="#burrows" id="id34">burrows</a></li>
<li><a class="reference internal" href="#sort" id="id35">sort</a></li>
<li><a class="reference internal" href="#plugins" id="id34">Plugins</a><ul>
<li><a class="reference internal" href="#burrows" id="id35">burrows</a></li>
<li><a class="reference internal" href="#sort" id="id36">sort</a></li>
</ul>
</li>
<li><a class="reference internal" href="#scripts" id="id36">Scripts</a></li>
<li><a class="reference internal" href="#scripts" id="id37">Scripts</a></li>
</ul>
</div>
<p>The current version of DFHack has extensive support for
@ -1385,8 +1386,137 @@ Returns <em>true, was_only_planned</em> if removed; or <em>false</em> if none fo
</li>
</ul>
</div>
<div class="section" id="screen-api">
<h3><a class="toc-backref" href="#id26">Screen API</a></h3>
<p>The screen module implements support for drawing to the tiled screen of the game.
Note that drawing only has any effect when done from callbacks, so it can only
be feasibly used in the core context.</p>
<p>Basic painting functions:</p>
<ul>
<li><p class="first"><tt class="docutils literal">dfhack.screen.getWindowSize()</tt></p>
<p>Returns <em>width, height</em> of the screen.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.screen.getMousePos()</tt></p>
<p>Returns <em>x,y</em> of the tile the mouse is over.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.screen.inGraphicsMode()</tt></p>
<p>Checks if [GRAPHICS:YES] was specified in init.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.screen.paintTile(pen,x,y[,char,tile])</span></tt></p>
<p>Paints a tile using given parameters. Pen is a table with following possible fields:</p>
<dl class="docutils">
<dt><tt class="docutils literal">ch</tt></dt>
<dd><p class="first last">Provides the ordinary tile character, as either a 1-character string or a number.
Can be overridden with the <tt class="docutils literal">char</tt> function parameter.</p>
</dd>
<dt><tt class="docutils literal">fg</tt></dt>
<dd><p class="first last">Foreground color for the ordinary tile. Defaults to COLOR_GREY (7).</p>
</dd>
<dt><tt class="docutils literal">bg</tt></dt>
<dd><p class="first last">Background color for the ordinary tile. Defaults to COLOR_BLACK (0).</p>
</dd>
<dt><tt class="docutils literal">bold</tt></dt>
<dd><p class="first last">Bright/bold text flag. If <em>nil</em>, computed based on (fg &amp; 8); fg is masked to 3 bits.
Otherwise should be <em>true/false</em>.</p>
</dd>
<dt><tt class="docutils literal">tile</tt></dt>
<dd><p class="first last">Graphical tile id. Ignored unless [GRAPHICS:YES] was in init.txt.</p>
</dd>
<dt><tt class="docutils literal">tile_color = true</tt></dt>
<dd><p class="first last">Specifies that the tile should be shaded with <em>fg/bg</em>.</p>
</dd>
<dt><tt class="docutils literal">tile_fg, tile_bg</tt></dt>
<dd><p class="first last">If specified, overrides <em>tile_color</em> and supplies shading colors directly.</p>
</dd>
</dl>
<p>Returns <em>false</em> if coordinates out of bounds, or other error.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.screen.paintString(pen,x,y,text)</tt></p>
<p>Paints the string starting at <em>x,y</em>. Uses the string characters
in sequence to override the <tt class="docutils literal">ch</tt> field of pen.</p>
<p>Returns <em>true</em> if painting at least one character succeeded.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.screen.fillRect(pen,x1,y1,x2,y2)</tt></p>
<p>Fills the rectangle specified by the coordinates with the given pen.
Returns <em>true</em> if painting at least one character succeeded.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.screen.findGraphicsTile(pagename,x,y)</tt></p>
<p>Finds a tile from a graphics set (i.e. the raws used for creatures),
if in graphics mode and loaded.</p>
<p>Returns: <em>tile, tile_grayscale</em>, or <em>nil</em> if not found.
The values can then be used for the <em>tile</em> field of <em>pen</em> structures.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.screen.clear()</tt></p>
<p>Fills the screen with blank background.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.screen.invalidate()</tt></p>
<p>Requests repaint of the screen by setting a flag. Unlike other
functions in this section, this may be used at any time.</p>
</li>
</ul>
<p>In order to actually be able to paint to the screen, it is necessary
to create and register a viewscreen (basically a modal dialog) with
the game.</p>
<p><strong>NOTE</strong>: As a matter of policy, in order to avoid user confusion, all
interface screens added by dfhack should bear the &quot;DFHack&quot; signature.</p>
<p>Screens are managed with the following functions:</p>
<ul>
<li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.screen.show(screen[,below])</span></tt></p>
<p>Displays the given screen, possibly placing it below a different one.
The screen must not be already shown. Returns <em>true</em> if success.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.screen.dismiss(screen)</tt></p>
<p>Marks the screen to be removed when the game enters its event loop.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.screen.isDismissed(screen)</tt></p>
<p>Checks if the screen is already marked for removal.</p>
</li>
</ul>
<p>Apart from a native viewscreen object, these functions accept a table
as a screen. In this case, <tt class="docutils literal">show</tt> creates a new native viewscreen
that delegates all processing to methods stored in that table.</p>
<p><strong>NOTE</strong>: Lua-implemented screens are only supported in the core context.</p>
<p>Supported callbacks and fields are:</p>
<ul>
<li><p class="first"><tt class="docutils literal">screen._native</tt></p>
<p>Initialized by <tt class="docutils literal">show</tt> with a reference to the backing viewscreen
object, and removed again when the object is deleted.</p>
</li>
<li><p class="first"><tt class="docutils literal">function screen:onDestroy()</tt></p>
<p>Called from the destructor when the viewscreen is deleted.</p>
</li>
<li><p class="first"><tt class="docutils literal">function screen:onRender()</tt></p>
<p>Called when the viewscreen should paint itself. This is the only context
where the above painting functions work correctly.</p>
<p>If omitted, the screen is cleared; otherwise it should do that itself.
In order to make a see-through dialog, call <tt class="docutils literal">self._native.parent:render()</tt>.</p>
</li>
<li><p class="first"><tt class="docutils literal">function screen:onIdle()</tt></p>
<p>Called every frame when the screen is on top of the stack.</p>
</li>
<li><p class="first"><tt class="docutils literal">function screen:onHelp()</tt></p>
<p>Called when the help keybinding is activated (usually '?').</p>
</li>
<li><p class="first"><tt class="docutils literal">function screen:onInput(keys)</tt></p>
<p>Called when keyboard or mouse events are available.
If any keys are pressed, the keys argument is a table mapping them to <em>true</em>.
Note that this refers to logical keybingings computed from real keys via
options; if multiple interpretations exist, the table will contain multiple keys.</p>
<p>The table also may contain special keys:</p>
<dl class="docutils">
<dt><tt class="docutils literal">_STRING</tt></dt>
<dd><p class="first last">Maps to an integer in range 0-255. Duplicates a separate &quot;STRING_A???&quot; code for convenience.</p>
</dd>
<dt><tt class="docutils literal">_MOUSE_L, _MOUSE_R</tt></dt>
<dd><p class="first last">If the left or right mouse button is pressed.</p>
</dd>
</dl>
<p>If this method is omitted, the screen is dismissed on receival of the <tt class="docutils literal">LEAVESCREEN</tt> key.</p>
</li>
</ul>
</div>
<div class="section" id="internal-api">
<h3><a class="toc-backref" href="#id26">Internal API</a></h3>
<h3><a class="toc-backref" href="#id27">Internal API</a></h3>
<p>These functions are intended for the use by dfhack developers,
and are only documented here for completeness:</p>
<ul>
@ -1409,6 +1539,11 @@ global environment, persistent between calls to the script.</p>
<li><p class="first"><tt class="docutils literal">dfhack.internal.getMemRanges()</tt></p>
<p>Returns a sequence of tables describing virtual memory ranges of the process.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.internal.patchMemory(dest,src,count)</tt></p>
<p>Like memmove below, but works even if dest is read-only memory, e.g. code.
If destination overlaps a completely invalid memory region, or another error
occurs, returns false.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.internal.memmove(dest,src,count)</tt></p>
<p>Wraps the standard memmove function. Accepts both numbers and refs as pointers.</p>
</li>
@ -1429,7 +1564,7 @@ Returns: <em>found_index</em>, or <em>nil</em> if end reached.</p>
</div>
</div>
<div class="section" id="core-interpreter-context">
<h2><a class="toc-backref" href="#id27">Core interpreter context</a></h2>
<h2><a class="toc-backref" href="#id28">Core interpreter context</a></h2>
<p>While plugins can create any number of interpreter instances,
there is one special context managed by dfhack core. It is the
only context that can receive events from DF and plugins.</p>
@ -1460,7 +1595,7 @@ Using <tt class="docutils literal">timeout_active(id,nil)</tt> cancels the timer
</li>
</ul>
<div class="section" id="event-type">
<h3><a class="toc-backref" href="#id28">Event type</a></h3>
<h3><a class="toc-backref" href="#id29">Event type</a></h3>
<p>An event is just a lua table with a predefined metatable that
contains a __call metamethod. When it is invoked, it loops
through the table with next and calls all contained values.
@ -1486,7 +1621,7 @@ order using <tt class="docutils literal">dfhack.safecall</tt>.</p>
</div>
</div>
<div class="section" id="lua-modules">
<h1><a class="toc-backref" href="#id29">Lua Modules</a></h1>
<h1><a class="toc-backref" href="#id30">Lua Modules</a></h1>
<p>DFHack sets up the lua interpreter so that the built-in <tt class="docutils literal">require</tt>
function can be used to load shared lua code from hack/lua/.
The <tt class="docutils literal">dfhack</tt> namespace reference itself may be obtained via
@ -1515,7 +1650,7 @@ in this document.</p>
</li>
</ul>
<div class="section" id="global-environment">
<h2><a class="toc-backref" href="#id30">Global environment</a></h2>
<h2><a class="toc-backref" href="#id31">Global environment</a></h2>
<p>A number of variables and functions are provided in the base global
environment by the mandatory init file dfhack.lua:</p>
<ul>
@ -1556,7 +1691,7 @@ Returns <em>nil</em> if any of obj or indices is <em>nil</em>, or a numeric inde
</ul>
</div>
<div class="section" id="utils">
<h2><a class="toc-backref" href="#id31">utils</a></h2>
<h2><a class="toc-backref" href="#id32">utils</a></h2>
<ul>
<li><p class="first"><tt class="docutils literal">utils.compare(a,b)</tt></p>
<p>Comparator function; returns <em>-1</em> if a&lt;b, <em>1</em> if a&gt;b, <em>0</em> otherwise.</p>
@ -1669,7 +1804,7 @@ throws an error.</p>
</ul>
</div>
<div class="section" id="dumper">
<h2><a class="toc-backref" href="#id32">dumper</a></h2>
<h2><a class="toc-backref" href="#id33">dumper</a></h2>
<p>A third-party lua table dumper module from
<a class="reference external" href="http://lua-users.org/wiki/DataDumper">http://lua-users.org/wiki/DataDumper</a>. Defines one
function:</p>
@ -1683,14 +1818,14 @@ the other arguments see the original documentation link above.</p>
</div>
</div>
<div class="section" id="plugins">
<h1><a class="toc-backref" href="#id33">Plugins</a></h1>
<h1><a class="toc-backref" href="#id34">Plugins</a></h1>
<p>DFHack plugins may export native functions and events
to lua contexts. They are automatically imported by
<tt class="docutils literal"><span class="pre">mkmodule('plugins.&lt;name&gt;')</span></tt>; this means that a lua
module file is still necessary for <tt class="docutils literal">require</tt> to read.</p>
<p>The following plugins have lua support.</p>
<div class="section" id="burrows">
<h2><a class="toc-backref" href="#id34">burrows</a></h2>
<h2><a class="toc-backref" href="#id35">burrows</a></h2>
<p>Implements extended burrow manipulations.</p>
<p>Events:</p>
<ul>
@ -1728,13 +1863,13 @@ set is the same as used by the command line.</p>
<p>The lua module file also re-exports functions from <tt class="docutils literal">dfhack.burrows</tt>.</p>
</div>
<div class="section" id="sort">
<h2><a class="toc-backref" href="#id35">sort</a></h2>
<h2><a class="toc-backref" href="#id36">sort</a></h2>
<p>Does not export any native functions as of now. Instead, it
calls lua code to perform the actual ordering of list items.</p>
</div>
</div>
<div class="section" id="scripts">
<h1><a class="toc-backref" href="#id36">Scripts</a></h1>
<h1><a class="toc-backref" href="#id37">Scripts</a></h1>
<p>Any files with the .lua extension placed into hack/scripts/*
are automatically used by the DFHack core as commands. The
matching command name consists of the name of the file sans

@ -72,13 +72,13 @@ ELSE()
SET(HASH_SET_CLASS hash_set)
ENDIF()
CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/config.h.in" "${CMAKE_CURRENT_SOURCE_DIR}/config.h")
CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/config.h.in" "${CMAKE_CURRENT_BINARY_DIR}/config.h")
SET(LIBPROTOBUF_LITE_HDRS
google/protobuf/io/coded_stream.h
google/protobuf/io/coded_stream_inl.h
google/protobuf/stubs/common.h
config.h
${CMAKE_CURRENT_BINARY_DIR}/config.h
google/protobuf/extension_set.h
google/protobuf/generated_message_util.h
google/protobuf/stubs/hash.h
@ -207,6 +207,7 @@ ENDIF()
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
SET(PROTOBUF_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR})
INCLUDE_DIRECTORIES(${ZLIB_INCLUDE_DIRS})
include_directories(${CMAKE_CURRENT_BINARY_DIR})
# Protobuf shared libraries

@ -42,3 +42,6 @@ keybinding add Shift-I "job-material CINNABAR"
keybinding add Shift-B "job-material COBALTITE"
keybinding add Shift-O "job-material OBSIDIAN"
keybinding add Shift-G "job-material GLASS_GREEN"
# browse linked mechanisms
keybinding add Ctrl-M@dwarfmode/QueryBuilding/Some gui/mechanisms

@ -27,6 +27,7 @@ include/Core.h
include/ColorText.h
include/DataDefs.h
include/DataIdentity.h
include/VTableInterpose.h
include/LuaWrapper.h
include/LuaTools.h
include/Error.h
@ -53,6 +54,7 @@ SET(MAIN_SOURCES
Core.cpp
ColorText.cpp
DataDefs.cpp
VTableInterpose.cpp
LuaWrapper.cpp
LuaTypes.cpp
LuaTools.cpp
@ -117,6 +119,7 @@ include/modules/Maps.h
include/modules/MapCache.h
include/modules/Materials.h
include/modules/Notes.h
include/modules/Screen.h
include/modules/Translation.h
include/modules/Vegetation.h
include/modules/Vermin.h
@ -137,6 +140,7 @@ modules/kitchen.cpp
modules/Maps.cpp
modules/Materials.cpp
modules/Notes.cpp
modules/Screen.cpp
modules/Translation.cpp
modules/Vegetation.cpp
modules/Vermin.cpp

@ -275,7 +275,7 @@ namespace DFHack
/// Reset color to default
void reset_color(void)
{
color(Console::COLOR_RESET);
color(COLOR_RESET);
if(!rawmode)
fflush(dfout_C);
}

@ -277,7 +277,7 @@ namespace DFHack
/// Reset color to default
void reset_color(void)
{
color(Console::COLOR_RESET);
color(COLOR_RESET);
if(!rawmode)
fflush(dfout_C);
}

@ -179,7 +179,7 @@ namespace DFHack
void color(int index)
{
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, index == color_ostream::COLOR_RESET ? default_attributes : index);
SetConsoleTextAttribute(hConsole, index == COLOR_RESET ? default_attributes : index);
}
void reset_color( void )

@ -358,7 +358,7 @@ command_result Core::runCommand(color_ostream &con, const std::string &first, ve
continue;
if (pcmd.isHotkeyCommand())
con.color(Console::COLOR_CYAN);
con.color(COLOR_CYAN);
con.print("%s: %s\n",pcmd.name.c_str(), pcmd.description.c_str());
con.reset_color();
if (!pcmd.usage.empty())
@ -481,7 +481,7 @@ command_result Core::runCommand(color_ostream &con, const std::string &first, ve
{
const PluginCommand & pcmd = (plug->operator[](j));
if (pcmd.isHotkeyCommand())
con.color(Console::COLOR_CYAN);
con.color(COLOR_CYAN);
con.print(" %-22s - %s\n",pcmd.name.c_str(), pcmd.description.c_str());
con.reset_color();
}
@ -519,7 +519,7 @@ command_result Core::runCommand(color_ostream &con, const std::string &first, ve
for(auto iter = out.begin();iter != out.end();iter++)
{
if ((*iter).recolor)
con.color(Console::COLOR_CYAN);
con.color(COLOR_CYAN);
con.print(" %-22s- %s\n",(*iter).name.c_str(), (*iter).description.c_str());
con.reset_color();
}
@ -1027,35 +1027,41 @@ int Core::TileUpdate()
return true;
}
// should always be from simulation thread!
int Core::Update()
int Core::ClaimSuspend(bool force_base)
{
if(errorstate)
return -1;
auto tid = this_thread::get_id();
lock_guard<mutex> lock(d->AccessMutex);
// Pretend this thread has suspended the core in the usual way
if (force_base || d->df_suspend_depth <= 0)
{
lock_guard<mutex> lock(d->AccessMutex);
assert(d->df_suspend_depth == 0);
d->df_suspend_thread = this_thread::get_id();
d->df_suspend_depth = 1000;
}
// Initialize the core
bool first_update = false;
if(!started)
d->df_suspend_thread = tid;
d->df_suspend_depth = 1000000;
return 1000000;
}
else
{
first_update = true;
Init();
if(errorstate)
return -1;
Lua::Core::Reset(con, "core init");
assert(d->df_suspend_thread == tid);
return ++d->df_suspend_depth;
}
}
color_ostream_proxy out(con);
void Core::DisclaimSuspend(int level)
{
auto tid = this_thread::get_id();
lock_guard<mutex> lock(d->AccessMutex);
assert(d->df_suspend_depth == level && d->df_suspend_thread == tid);
if (level == 1000000)
d->df_suspend_depth = 0;
else
--d->df_suspend_depth;
}
void Core::doUpdate(color_ostream &out, bool first_update)
{
Lua::Core::Reset(out, "DF code execution");
if (first_update)
@ -1129,15 +1135,36 @@ int Core::Update()
// Execute per-frame handlers
onUpdate(out);
// Release the fake suspend lock
out << std::flush;
}
// should always be from simulation thread!
int Core::Update()
{
if(errorstate)
return -1;
color_ostream_proxy out(con);
// Pretend this thread has suspended the core in the usual way,
// and run various processing hooks.
{
lock_guard<mutex> lock(d->AccessMutex);
CoreSuspendClaimer suspend(true);
assert(d->df_suspend_depth == 1000);
d->df_suspend_depth = 0;
}
// Initialize the core
bool first_update = false;
out << std::flush;
if(!started)
{
first_update = true;
Init();
if(errorstate)
return -1;
Lua::Core::Reset(con, "core init");
}
doUpdate(out, first_update);
}
// wake waiting tools
// do not allow more tools to join in while we process stuff here
@ -1158,7 +1185,7 @@ int Core::Update()
// destroy condition
delete nc;
// check lua stack depth
Lua::Core::Reset(con, "suspend");
Lua::Core::Reset(out, "suspend");
}
return 0;
@ -1548,6 +1575,56 @@ void ClassNameCheck::getKnownClassNames(std::vector<std::string> &names)
names.push_back(*it);
}
bool Process::patchMemory(void *target, const void* src, size_t count)
{
uint8_t *sptr = (uint8_t*)target;
uint8_t *eptr = sptr + count;
// Find the valid memory ranges
std::vector<t_memrange> ranges;
getMemRanges(ranges);
unsigned start = 0;
while (start < ranges.size() && ranges[start].end <= sptr)
start++;
if (start >= ranges.size() || ranges[start].start > sptr)
return false;
unsigned end = start+1;
while (end < ranges.size() && ranges[end].start < eptr)
{
if (ranges[end].start != ranges[end-1].end)
return false;
end++;
}
if (ranges[end-1].end < eptr)
return false;
// Verify current permissions
for (unsigned i = start; i < end; i++)
if (!ranges[i].valid || !(ranges[i].read || ranges[i].execute) || ranges[i].shared)
return false;
// Apply writable permissions & update
bool ok = true;
for (unsigned i = start; i < end && ok; i++)
{
t_memrange perms = ranges[i];
perms.write = perms.read = true;
if (!setPermisions(perms, perms))
ok = false;
}
if (ok)
memmove(target, src, count);
for (unsigned i = start; i < end && ok; i++)
setPermisions(ranges[i], ranges[i]);
return ok;
}
/*******************************************************************************
M O D U L E S
*******************************************************************************/

@ -35,6 +35,7 @@ distribution.
// must be last due to MS stupidity
#include "DataDefs.h"
#include "DataIdentity.h"
#include "VTableInterpose.h"
#include "MiscUtils.h"
@ -214,6 +215,13 @@ virtual_identity::virtual_identity(size_t size, TAllocateFn alloc,
{
}
virtual_identity::~virtual_identity()
{
// Remove interpose entries, so that they don't try accessing this object later
for (int i = interpose_list.size()-1; i >= 0; i--)
interpose_list[i]->remove();
}
/* Vtable name to identity lookup. */
static std::map<std::string, virtual_identity*> name_lookup;

@ -39,6 +39,7 @@ distribution.
#include "modules/World.h"
#include "modules/Gui.h"
#include "modules/Screen.h"
#include "modules/Job.h"
#include "modules/Translation.h"
#include "modules/Units.h"
@ -84,6 +85,8 @@ distribution.
using namespace DFHack;
using namespace DFHack::LuaWrapper;
using Screen::Pen;
void dfhack_printerr(lua_State *S, const std::string &str);
void Lua::Push(lua_State *state, const Units::NoblePosition &pos)
@ -179,6 +182,68 @@ static df::coord CheckCoordXYZ(lua_State *state, int base, bool vararg = false)
return p;
}
template<class T>
static bool get_int_field(lua_State *L, T *pf, int idx, const char *name, int defval)
{
lua_getfield(L, idx, name);
bool nil = lua_isnil(L, -1);
if (nil) *pf = T(defval);
else if (lua_isnumber(L, -1)) *pf = T(lua_tointeger(L, -1));
else luaL_error(L, "Field %s is not a number.", name);
lua_pop(L, 1);
return !nil;
}
static bool get_char_field(lua_State *L, char *pf, int idx, const char *name, char defval)
{
lua_getfield(L, idx, name);
if (lua_type(L, -1) == LUA_TSTRING)
{
*pf = lua_tostring(L, -1)[0];
lua_pop(L, 1);
return true;
}
else
{
lua_pop(L, 1);
return get_int_field(L, pf, idx, name, defval);
}
}
static void decode_pen(lua_State *L, Pen &pen, int idx)
{
idx = lua_absindex(L, idx);
get_char_field(L, &pen.ch, idx, "ch", 0);
get_int_field(L, &pen.fg, idx, "fg", 7);
get_int_field(L, &pen.bg, idx, "bg", 0);
lua_getfield(L, idx, "bold");
if (lua_isnil(L, -1))
{
pen.bold = (pen.fg & 8) != 0;
pen.fg &= 7;
}
else pen.bold = lua_toboolean(L, -1);
lua_pop(L, 1);
get_int_field(L, &pen.tile, idx, "tile", 0);
bool tcolor = get_int_field(L, &pen.tile_fg, idx, "tile_fg", 7);
tcolor = get_int_field(L, &pen.tile_bg, idx, "tile_bg", 0) || tcolor;
if (tcolor)
pen.tile_mode = Pen::TileColor;
else
{
lua_getfield(L, idx, "tile_color");
pen.tile_mode = (lua_toboolean(L, -1) ? Pen::CharColor : Pen::AsIs);
lua_pop(L, 1);
}
}
/**************************************************
* Per-world persistent configuration storage API *
**************************************************/
@ -1019,6 +1084,164 @@ static const luaL_Reg dfhack_constructions_funcs[] = {
{ NULL, NULL }
};
/***** Screen module *****/
static const LuaWrapper::FunctionReg dfhack_screen_module[] = {
WRAPM(Screen, inGraphicsMode),
WRAPM(Screen, clear),
WRAPM(Screen, invalidate),
{ NULL, NULL }
};
static int screen_getMousePos(lua_State *L)
{
auto pos = Screen::getMousePos();
lua_pushinteger(L, pos.x);
lua_pushinteger(L, pos.y);
return 2;
}
static int screen_getWindowSize(lua_State *L)
{
auto pos = Screen::getWindowSize();
lua_pushinteger(L, pos.x);
lua_pushinteger(L, pos.y);
return 2;
}
static int screen_paintTile(lua_State *L)
{
Pen pen;
decode_pen(L, pen, 1);
int x = luaL_checkint(L, 2);
int y = luaL_checkint(L, 3);
if (lua_gettop(L) >= 4 && !lua_isnil(L, 4))
{
if (lua_type(L, 4) == LUA_TSTRING)
pen.ch = lua_tostring(L, 4)[0];
else
pen.ch = luaL_checkint(L, 4);
}
if (lua_gettop(L) >= 5 && !lua_isnil(L, 5))
pen.tile = luaL_checkint(L, 5);
lua_pushboolean(L, Screen::paintTile(pen, x, y));
return 1;
}
static int screen_paintString(lua_State *L)
{
Pen pen;
decode_pen(L, pen, 1);
int x = luaL_checkint(L, 2);
int y = luaL_checkint(L, 3);
const char *text = luaL_checkstring(L, 4);
lua_pushboolean(L, Screen::paintString(pen, x, y, text));
return 1;
}
static int screen_fillRect(lua_State *L)
{
Pen pen;
decode_pen(L, pen, 1);
int x1 = luaL_checkint(L, 2);
int y1 = luaL_checkint(L, 3);
int x2 = luaL_checkint(L, 4);
int y2 = luaL_checkint(L, 5);
lua_pushboolean(L, Screen::fillRect(pen, x1, y1, x2, y2));
return 1;
}
static int screen_findGraphicsTile(lua_State *L)
{
auto str = luaL_checkstring(L, 1);
int x = luaL_checkint(L, 2);
int y = luaL_checkint(L, 3);
int tile, tile_gs;
if (Screen::findGraphicsTile(str, x, y, &tile, &tile_gs))
{
lua_pushinteger(L, tile);
lua_pushinteger(L, tile_gs);
return 2;
}
else
{
lua_pushnil(L);
return 1;
}
}
namespace {
int screen_show(lua_State *L)
{
df::viewscreen *before = NULL;
if (lua_gettop(L) >= 2)
before = Lua::CheckDFObject<df::viewscreen>(L, 2);
df::viewscreen *screen = dfhack_lua_viewscreen::get_pointer(L, 1, true);
bool ok = Screen::show(screen, before);
// If it is a table, get_pointer created a new object. Don't leak it.
if (!ok && lua_istable(L, 1))
delete screen;
lua_pushboolean(L, ok);
return 1;
}
static int screen_dismiss(lua_State *L)
{
df::viewscreen *screen = dfhack_lua_viewscreen::get_pointer(L, 1, false);
Screen::dismiss(screen);
return 0;
}
static int screen_isDismissed(lua_State *L)
{
df::viewscreen *screen = dfhack_lua_viewscreen::get_pointer(L, 1, false);
lua_pushboolean(L, Screen::isDismissed(screen));
return 1;
}
static int screen_doSimulateInput(lua_State *L)
{
auto screen = Lua::CheckDFObject<df::viewscreen>(L, 1);
luaL_checktype(L, 2, LUA_TTABLE);
if (!screen)
luaL_argerror(L, 1, "NULL screen");
int sz = lua_rawlen(L, 2);
std::set<df::interface_key> keys;
for (int j = 1; j <= sz; j++)
{
lua_rawgeti(L, 2, j);
keys.insert((df::interface_key)lua_tointeger(L, -1));
lua_pop(L, 1);
}
screen->feed(&keys);
return 0;
}
}
static const luaL_Reg dfhack_screen_funcs[] = {
{ "getMousePos", screen_getMousePos },
{ "getWindowSize", screen_getWindowSize },
{ "paintTile", screen_paintTile },
{ "paintString", screen_paintString },
{ "fillRect", screen_fillRect },
{ "findGraphicsTile", screen_findGraphicsTile },
{ "show", &Lua::CallWithCatchWrapper<screen_show> },
{ "dismiss", screen_dismiss },
{ "isDismissed", screen_isDismissed },
{ "_doSimulateInput", screen_doSimulateInput },
{ NULL, NULL }
};
/***** Internal module *****/
static void *checkaddr(lua_State *L, int idx, bool allow_null = false)
@ -1124,6 +1347,17 @@ static int internal_getMemRanges(lua_State *L)
return 1;
}
static int internal_patchMemory(lua_State *L)
{
void *dest = checkaddr(L, 1);
void *src = checkaddr(L, 2);
int size = luaL_checkint(L, 3);
if (size < 0) luaL_argerror(L, 1, "negative size");
bool ok = Core::getInstance().p->patchMemory(dest, src, size);
lua_pushboolean(L, ok);
return 1;
}
static int internal_memmove(lua_State *L)
{
void *dest = checkaddr(L, 1);
@ -1214,6 +1448,7 @@ static const luaL_Reg dfhack_internal_funcs[] = {
{ "setAddress", internal_setAddress },
{ "getVTable", internal_getVTable },
{ "getMemRanges", internal_getMemRanges },
{ "patchMemory", internal_patchMemory },
{ "memmove", internal_memmove },
{ "memcmp", internal_memcmp },
{ "memscan", internal_memscan },
@ -1240,5 +1475,6 @@ void OpenDFHackApi(lua_State *state)
OpenModule(state, "burrows", dfhack_burrows_module, dfhack_burrows_funcs);
OpenModule(state, "buildings", dfhack_buildings_module, dfhack_buildings_funcs);
OpenModule(state, "constructions", dfhack_constructions_module);
OpenModule(state, "screen", dfhack_screen_module, dfhack_screen_funcs);
OpenModule(state, "internal", dfhack_internal_module, dfhack_internal_funcs);
}

@ -252,7 +252,7 @@ static int lua_dfhack_color(lua_State *S)
{
int cv = luaL_optint(S, 1, -1);
if (cv < -1 || cv > color_ostream::COLOR_MAX)
if (cv < -1 || cv > COLOR_MAX)
luaL_argerror(S, 1, "invalid color value");
color_ostream *out = Lua::GetOutput(S);

@ -37,6 +37,7 @@ distribution.
#include "DataDefs.h"
#include "DataIdentity.h"
#include "LuaWrapper.h"
#include "LuaTools.h"
#include "DataFuncs.h"
#include "MiscUtils.h"
@ -285,6 +286,9 @@ void container_identity::lua_item_read(lua_State *state, int fname_idx, void *pt
void container_identity::lua_item_write(lua_State *state, int fname_idx, void *ptr, int idx, int val_index)
{
if (is_readonly())
field_error(state, fname_idx, "container is read-only", "write");
auto id = (type_identity*)lua_touserdata(state, UPVAL_ITEM_ID);
void *pitem = item_pointer(id, ptr, idx);
id->lua_write(state, fname_idx, pitem, val_index);
@ -1064,6 +1068,27 @@ int LuaWrapper::method_wrapper_core(lua_State *state, function_identity_base *id
return 1;
}
int Lua::CallWithCatch(lua_State *state, int (*fn)(lua_State*), const char *context)
{
if (!context)
context = "native code";
try {
return fn(state);
}
catch (Error::NullPointer &e) {
const char *vn = e.varname();
return luaL_error(state, "%s: NULL pointer: %s", context, vn ? vn : "?");
}
catch (Error::InvalidArgument &e) {
const char *vn = e.expr();
return luaL_error(state, "%s: Invalid argument; expected: %s", context, vn ? vn : "?");
}
catch (std::exception &e) {
return luaL_error(state, "%s: C++ exception: %s", context, e.what());
}
}
/**
* Push a closure invoking the given function.
*/

@ -467,7 +467,7 @@ int Plugin::lua_cmd_wrapper(lua_State *state)
luaL_error(state, "plugin command %s() has been unloaded",
(cmd->owner->name+"."+cmd->name).c_str());
return cmd->command(state);
return Lua::CallWithCatch(state, cmd->command, cmd->name.c_str());
}
int Plugin::lua_fun_wrapper(lua_State *state)

@ -0,0 +1,249 @@
/*
https://github.com/peterix/dfhack
Copyright (c) 2009-2011 Petr Mrázek (peterix@gmail.com)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "Internal.h"
#include <string>
#include <vector>
#include <map>
#include "MemAccess.h"
#include "Core.h"
#include "VersionInfo.h"
#include "VTableInterpose.h"
#include "MiscUtils.h"
using namespace DFHack;
/*
* Code for accessing method pointers directly. Very compiler-specific.
*/
#if defined(_MSC_VER)
struct MSVC_MPTR {
void *method;
intptr_t this_shift;
};
bool DFHack::is_vmethod_pointer_(void *pptr)
{
auto pobj = (MSVC_MPTR*)pptr;
if (!pobj->method) return false;
// MSVC implements pointers to vmethods via thunks.
// This expects that they all follow a very specific pattern.
auto pval = (unsigned*)pobj->method;
switch (pval[0]) {
case 0x20FF018BU: // mov eax, [ecx]; jmp [eax]
case 0x60FF018BU: // mov eax, [ecx]; jmp [eax+0x??]
case 0xA0FF018BU: // mov eax, [ecx]; jmp [eax+0x????????]
return true;
default:
return false;
}
}
int DFHack::vmethod_pointer_to_idx_(void *pptr)
{
auto pobj = (MSVC_MPTR*)pptr;
if (!pobj->method || pobj->this_shift != 0) return -1;
auto pval = (unsigned*)pobj->method;
switch (pval[0]) {
case 0x20FF018BU: // mov eax, [ecx]; jmp [eax]
return 0;
case 0x60FF018BU: // mov eax, [ecx]; jmp [eax+0x??]
return ((int8_t)pval[1])/sizeof(void*);
case 0xA0FF018BU: // mov eax, [ecx]; jmp [eax+0x????????]
return ((int32_t)pval[1])/sizeof(void*);
default:
return -1;
}
}
void* DFHack::method_pointer_to_addr_(void *pptr)
{
if (is_vmethod_pointer_(pptr)) return NULL;
auto pobj = (MSVC_MPTR*)pptr;
return pobj->method;
}
void DFHack::addr_to_method_pointer_(void *pptr, void *addr)
{
auto pobj = (MSVC_MPTR*)pptr;
pobj->method = addr;
pobj->this_shift = 0;
}
#elif defined(__GXX_ABI_VERSION)
struct GCC_MPTR {
intptr_t method;
intptr_t this_shift;
};
bool DFHack::is_vmethod_pointer_(void *pptr)
{
auto pobj = (GCC_MPTR*)pptr;
return (pobj->method & 1) != 0;
}
int DFHack::vmethod_pointer_to_idx_(void *pptr)
{
auto pobj = (GCC_MPTR*)pptr;
if ((pobj->method & 1) == 0 || pobj->this_shift != 0)
return -1;
return (pobj->method-1)/sizeof(void*);
}
void* DFHack::method_pointer_to_addr_(void *pptr)
{
auto pobj = (GCC_MPTR*)pptr;
if ((pobj->method & 1) != 0 || pobj->this_shift != 0)
return NULL;
return (void*)pobj->method;
}
void DFHack::addr_to_method_pointer_(void *pptr, void *addr)
{
auto pobj = (GCC_MPTR*)pptr;
pobj->method = (intptr_t)addr;
pobj->this_shift = 0;
}
#else
#error Unknown compiler type
#endif
void *virtual_identity::get_vmethod_ptr(int idx)
{
assert(idx >= 0);
void **vtable = (void**)vtable_ptr;
if (!vtable) return NULL;
return vtable[idx];
}
bool virtual_identity::set_vmethod_ptr(int idx, void *ptr)
{
assert(idx >= 0);
void **vtable = (void**)vtable_ptr;
if (!vtable) return NULL;
return Core::getInstance().p->patchMemory(&vtable[idx], &ptr, sizeof(void*));
}
void VMethodInterposeLinkBase::set_chain(void *chain)
{
saved_chain = chain;
addr_to_method_pointer_(chain_mptr, chain);
}
VMethodInterposeLinkBase::VMethodInterposeLinkBase(virtual_identity *host, int vmethod_idx, void *interpose_method, void *chain_mptr)
: host(host), vmethod_idx(vmethod_idx), interpose_method(interpose_method), chain_mptr(chain_mptr),
saved_chain(NULL), next(NULL), prev(NULL)
{
if (vmethod_idx < 0 || interpose_method == NULL)
{
fprintf(stderr, "Bad VMethodInterposeLinkBase arguments: %d %08x\n",
vmethod_idx, unsigned(interpose_method));
fflush(stderr);
abort();
}
}
VMethodInterposeLinkBase::~VMethodInterposeLinkBase()
{
if (is_applied())
remove();
}
bool VMethodInterposeLinkBase::apply()
{
if (is_applied())
return true;
if (!host->vtable_ptr)
return false;
// Retrieve the current vtable entry
void *old_ptr = host->get_vmethod_ptr(vmethod_idx);
assert(old_ptr != NULL);
// Check if there are other interpose entries for the same slot
VMethodInterposeLinkBase *old_link = NULL;
for (int i = host->interpose_list.size()-1; i >= 0; i--)
{
if (host->interpose_list[i]->vmethod_idx != vmethod_idx)
continue;
old_link = host->interpose_list[i];
assert(old_link->next == NULL && old_ptr == old_link->interpose_method);
break;
}
// Apply the new method ptr
if (!host->set_vmethod_ptr(vmethod_idx, interpose_method))
return false;
set_chain(old_ptr);
host->interpose_list.push_back(this);
// Link into the chain if any
if (old_link)
{
old_link->next = this;
prev = old_link;
}
return true;
}
void VMethodInterposeLinkBase::remove()
{
if (!is_applied())
return;
// Remove from the list in the identity
for (int i = host->interpose_list.size()-1; i >= 0; i--)
if (host->interpose_list[i] == this)
vector_erase_at(host->interpose_list, i);
// Remove from the chain
if (prev)
prev->next = next;
if (next)
{
next->set_chain(saved_chain);
next->prev = prev;
}
else
{
host->set_vmethod_ptr(vmethod_idx, saved_chain);
}
prev = next = NULL;
set_chain(NULL);
}

@ -41,30 +41,32 @@ namespace dfproto
namespace DFHack
{
enum color_value
{
COLOR_RESET = -1,
COLOR_BLACK = 0,
COLOR_BLUE,
COLOR_GREEN,
COLOR_CYAN,
COLOR_RED,
COLOR_MAGENTA,
COLOR_BROWN,
COLOR_GREY,
COLOR_DARKGREY,
COLOR_LIGHTBLUE,
COLOR_LIGHTGREEN,
COLOR_LIGHTCYAN,
COLOR_LIGHTRED,
COLOR_LIGHTMAGENTA,
COLOR_YELLOW,
COLOR_WHITE,
COLOR_MAX = COLOR_WHITE
};
class DFHACK_EXPORT color_ostream : public std::ostream
{
public:
enum color_value
{
COLOR_RESET = -1,
COLOR_BLACK = 0,
COLOR_BLUE,
COLOR_GREEN,
COLOR_CYAN,
COLOR_RED,
COLOR_MAGENTA,
COLOR_BROWN,
COLOR_GREY,
COLOR_DARKGREY,
COLOR_LIGHTBLUE,
COLOR_LIGHTGREEN,
COLOR_LIGHTCYAN,
COLOR_LIGHTRED,
COLOR_LIGHTMAGENTA,
COLOR_YELLOW,
COLOR_WHITE,
COLOR_MAX = COLOR_WHITE
};
typedef DFHack::color_value color_value;
private:
color_value cur_color;

@ -174,6 +174,10 @@ namespace DFHack
struct Private;
Private *d;
friend class CoreSuspendClaimer;
int ClaimSuspend(bool force_base);
void DisclaimSuspend(int level);
bool Init();
int Update (void);
int TileUpdate (void);
@ -181,6 +185,7 @@ namespace DFHack
int DFH_SDL_Event(SDL::Event* event);
bool ncurses_wgetch(int in, int & out);
void doUpdate(color_ostream &out, bool first_update);
void onUpdate(color_ostream &out);
void onStateChange(color_ostream &out, state_change_event event);
@ -249,4 +254,20 @@ namespace DFHack
CoreSuspender(Core *core) : core(core) { core->Suspend(); }
~CoreSuspender() { core->Resume(); }
};
/** Claims the current thread already has the suspend lock.
* Strictly for use in callbacks from DF.
*/
class CoreSuspendClaimer {
Core *core;
int level;
public:
CoreSuspendClaimer(bool base = false) : core(&Core::getInstance()) {
level = core->ClaimSuspend(base);
}
CoreSuspendClaimer(Core *core, bool base = false) : core(core) {
level = core->ClaimSuspend(base);
}
~CoreSuspendClaimer() { core->DisclaimSuspend(level); }
};
}

@ -28,6 +28,7 @@ distribution.
#include <sstream>
#include <vector>
#include <map>
#include <set>
#include "Core.h"
#include "BitArray.h"
@ -292,6 +293,8 @@ namespace DFHack
typedef virtual_class *virtual_ptr;
#endif
class DFHACK_EXPORT VMethodInterposeLinkBase;
class DFHACK_EXPORT virtual_identity : public struct_identity {
static std::map<void*, virtual_identity*> known;
@ -299,6 +302,9 @@ namespace DFHack
void *vtable_ptr;
friend class VMethodInterposeLinkBase;
std::vector<VMethodInterposeLinkBase*> interpose_list;
protected:
virtual void doInit(Core *core);
@ -306,10 +312,14 @@ namespace DFHack
bool can_allocate() { return struct_identity::can_allocate() && (vtable_ptr != NULL); }
void *get_vmethod_ptr(int index);
bool set_vmethod_ptr(int index, void *ptr);
public:
virtual_identity(size_t size, TAllocateFn alloc,
const char *dfhack_name, const char *original_name,
virtual_identity *parent, const struct_field_info *fields);
~virtual_identity();
virtual identity_type type() { return IDTYPE_CLASS; }
@ -337,6 +347,8 @@ namespace DFHack
: (this == get(instance_ptr));
}
template<class P> static P get_vmethod_ptr(P selector);
public:
bool can_instantiate() { return can_allocate(); }
virtual_ptr instantiate() { return can_instantiate() ? (virtual_ptr)do_allocate() : NULL; }

@ -75,28 +75,31 @@ namespace df {
cur_lua_ostream_argument name(state);
#define INSTANTIATE_RETURN_TYPE(FArgs) \
template<FW_TARGSC class RT> struct return_type<RT (*) FArgs> { typedef RT type; }; \
template<FW_TARGSC class RT, class CT> struct return_type<RT (CT::*) FArgs> { typedef RT type; };
template<FW_TARGSC class RT> struct return_type<RT (*) FArgs> { \
typedef RT type; \
static const bool is_method = false; \
}; \
template<FW_TARGSC class RT, class CT> struct return_type<RT (CT::*) FArgs> { \
typedef RT type; \
typedef CT class_type; \
static const bool is_method = true; \
};
#define INSTANTIATE_WRAPPERS(Count, FArgs, Args, Loads) \
template<FW_TARGS> struct function_wrapper<void (*) FArgs, true> { \
static const bool is_method = false; \
static const int num_args = Count; \
static void execute(lua_State *state, int base, void (*cb) FArgs) { Loads; INVOKE_VOID(cb Args); } \
}; \
template<FW_TARGSC class RT> struct function_wrapper<RT (*) FArgs, false> { \
static const bool is_method = false; \
static const int num_args = Count; \
static void execute(lua_State *state, int base, RT (*cb) FArgs) { Loads; INVOKE_RV(cb Args); } \
}; \
template<FW_TARGSC class CT> struct function_wrapper<void (CT::*) FArgs, true> { \
static const bool is_method = true; \
static const int num_args = Count+1; \
static void execute(lua_State *state, int base, void (CT::*cb) FArgs) { \
LOAD_CLASS() Loads; INVOKE_VOID((self->*cb) Args); } \
}; \
template<FW_TARGSC class RT, class CT> struct function_wrapper<RT (CT::*) FArgs, false> { \
static const bool is_method = true; \
static const int num_args = Count+1; \
static void execute(lua_State *state, int base, RT (CT::*cb) FArgs) { \
LOAD_CLASS(); Loads; INVOKE_RV((self->*cb) Args); } \

@ -115,6 +115,8 @@ namespace DFHack
virtual void lua_item_read(lua_State *state, int fname_idx, void *ptr, int idx);
virtual void lua_item_write(lua_State *state, int fname_idx, void *ptr, int idx, int val_index);
virtual bool is_readonly() { return false; }
virtual bool resize(void *ptr, int size) { return false; }
virtual bool erase(void *ptr, int index) { return false; }
virtual bool insert(void *ptr, int index, void *pitem) { return false; }
@ -343,6 +345,33 @@ namespace df
}
};
template<class T>
class ro_stl_container_identity : public container_identity {
const char *name;
public:
ro_stl_container_identity(const char *name, type_identity *item, enum_identity *ienum = NULL)
: container_identity(sizeof(T), &allocator_fn<T>, item, ienum), name(name)
{}
std::string getFullName(type_identity *item) {
return name + container_identity::getFullName(item);
}
virtual bool is_readonly() { return true; }
virtual bool resize(void *ptr, int size) { return false; }
virtual bool erase(void *ptr, int size) { return false; }
virtual bool insert(void *ptr, int idx, void *item) { return false; }
protected:
virtual int item_count(void *ptr, CountMode) { return ((T*)ptr)->size(); }
virtual void *item_pointer(type_identity *item, void *ptr, int idx) {
auto iter = (*(T*)ptr).begin();
for (; idx > 0; idx--) ++iter;
return (void*)&*iter;
}
};
class bit_array_identity : public bit_container_identity {
public:
/*
@ -517,6 +546,10 @@ namespace df
static container_identity *get();
};
template<class T> struct identity_traits<std::set<T> > {
static container_identity *get();
};
template<> struct identity_traits<BitArray<int> > {
static bit_array_identity identity;
static bit_container_identity *get() { return &identity; }
@ -579,6 +612,13 @@ namespace df
return &identity;
}
template<class T>
inline container_identity *identity_traits<std::set<T> >::get() {
typedef std::set<T> container;
static ro_stl_container_identity<container> identity("set", identity_traits<T>::get());
return &identity;
}
template<class T>
inline bit_container_identity *identity_traits<BitArray<T> >::get() {
static bit_array_identity identity(identity_traits<T>::get());

@ -191,6 +191,16 @@ namespace DFHack {namespace Lua {
return cb(state, rv, ctx);
}
/**
* Call through to the function with try/catch for C++ exceptions.
*/
DFHACK_EXPORT int CallWithCatch(lua_State *, int (*fn)(lua_State*), const char *context = NULL);
template<int (*cb)(lua_State*)>
int CallWithCatchWrapper(lua_State *state) {
return CallWithCatch(state, cb);
}
/**
* Invoke lua function via pcall. Returns true if success.
* If an error is signalled, and perr is true, it is printed and popped from the stack.

@ -283,6 +283,9 @@ namespace DFHack
/// modify permisions of memory range
bool setPermisions(const t_memrange & range,const t_memrange &trgrange);
/// write a possibly read-only memory area
bool patchMemory(void *target, const void* src, size_t count);
private:
VersionInfo * my_descriptor;
PlatformSpecific *d;

@ -0,0 +1,173 @@
/*
https://github.com/peterix/dfhack
Copyright (c) 2009-2011 Petr Mrázek (peterix@gmail.com)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#pragma once
#include "DataFuncs.h"
namespace DFHack
{
template<bool> struct StaticAssert;
template<> struct StaticAssert<true> {};
#define STATIC_ASSERT(condition) { StaticAssert<(condition)>(); }
/* Wrapping around compiler-specific representation of pointers to methods. */
#if defined(_MSC_VER)
#define METHOD_POINTER_SIZE (sizeof(void*)*2)
#elif defined(__GXX_ABI_VERSION)
#define METHOD_POINTER_SIZE (sizeof(void*)*2)
#else
#error Unknown compiler type
#endif
#define ASSERT_METHOD_POINTER(type) \
STATIC_ASSERT(df::return_type<type>::is_method && sizeof(type)==METHOD_POINTER_SIZE);
DFHACK_EXPORT bool is_vmethod_pointer_(void*);
DFHACK_EXPORT int vmethod_pointer_to_idx_(void*);
DFHACK_EXPORT void* method_pointer_to_addr_(void*);
DFHACK_EXPORT void addr_to_method_pointer_(void*,void*);
template<class T> bool is_vmethod_pointer(T ptr) {
ASSERT_METHOD_POINTER(T);
return is_vmethod_pointer_(&ptr);
}
template<class T> int vmethod_pointer_to_idx(T ptr) {
ASSERT_METHOD_POINTER(T);
return vmethod_pointer_to_idx_(&ptr);
}
template<class T> void *method_pointer_to_addr(T ptr) {
ASSERT_METHOD_POINTER(T);
return method_pointer_to_addr_(&ptr);
}
template<class T> T addr_to_method_pointer(void *addr) {
ASSERT_METHOD_POINTER(T);
T rv;
addr_to_method_pointer_(&rv, addr);
return rv;
}
/* Access to vmethod pointers from the vtable. */
template<class P>
P virtual_identity::get_vmethod_ptr(P selector)
{
typedef typename df::return_type<P>::class_type host_class;
virtual_identity &identity = host_class::_identity;
int idx = vmethod_pointer_to_idx(selector);
return addr_to_method_pointer<P>(identity.get_vmethod_ptr(idx));
}
/* VMethod interpose API.
This API allows replacing an entry in the original vtable
with code defined by DFHack, while retaining ability to
call the original code. The API can be safely used from
plugins, and multiple hooks for the same vmethod are
automatically chained in undefined order.
Usage:
struct my_hack : df::someclass {
typedef df::someclass interpose_base;
DEFINE_VMETHOD_INTERPOSE(void, foo, (int arg)) {
// If needed by the code, claim the suspend lock.
// DO NOT USE THE USUAL CoreSuspender, OR IT WILL DEADLOCK!
// CoreSuspendClaimer suspend;
...
INTERPOSE_NEXT(foo)(arg) // call the original
...
}
};
IMPLEMENT_VMETHOD_INTERPOSE(my_hack, foo);
void init() {
if (!INTERPOSE_HOOK(my_hack, foo).apply())
error();
}
void shutdown() {
INTERPOSE_HOOK(my_hack, foo).remove();
}
*/
#define DEFINE_VMETHOD_INTERPOSE(rtype, name, args) \
typedef rtype (interpose_base::*interpose_ptr_##name)args; \
static DFHack::VMethodInterposeLink<interpose_base,interpose_ptr_##name> interpose_##name; \
rtype interpose_fn_##name args
#define IMPLEMENT_VMETHOD_INTERPOSE(class,name) \
DFHack::VMethodInterposeLink<class::interpose_base,class::interpose_ptr_##name> \
class::interpose_##name(&class::interpose_base::name, &class::interpose_fn_##name);
#define INTERPOSE_NEXT(name) (this->*interpose_##name.chain)
#define INTERPOSE_HOOK(class, name) (class::interpose_##name)
class DFHACK_EXPORT VMethodInterposeLinkBase {
/*
These link objects try to:
1) Allow multiple hooks into the same vmethod
2) Auto-remove hooks when a plugin is unloaded.
*/
virtual_identity *host; // Class with the vtable
int vmethod_idx;
void *interpose_method; // Pointer to the code of the interposing method
void *chain_mptr; // Pointer to the chain field below
void *saved_chain; // Previous pointer to the code
VMethodInterposeLinkBase *next, *prev; // Other hooks for the same method
void set_chain(void *chain);
public:
VMethodInterposeLinkBase(virtual_identity *host, int vmethod_idx, void *interpose_method, void *chain_mptr);
~VMethodInterposeLinkBase();
bool is_applied() { return saved_chain != NULL; }
bool apply();
void remove();
};
template<class Base, class Ptr>
class VMethodInterposeLink : public VMethodInterposeLinkBase {
public:
Ptr chain;
operator Ptr () { return chain; }
template<class Ptr2>
VMethodInterposeLink(Ptr target, Ptr2 src)
: VMethodInterposeLinkBase(
&Base::_identity,
vmethod_pointer_to_idx(target),
method_pointer_to_addr(src),
&chain
)
{ src = target; /* check compatibility */ }
};
}

@ -0,0 +1,170 @@
/*
https://github.com/peterix/dfhack
Copyright (c) 2009-2011 Petr Mrázek (peterix@gmail.com)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#pragma once
#include "Export.h"
#include "Module.h"
#include "BitArray.h"
#include "ColorText.h"
#include <string>
#include "DataDefs.h"
#include "df/graphic.h"
#include "df/viewscreen.h"
/**
* \defgroup grp_screen utilities for painting to the screen
* @ingroup grp_screen
*/
namespace DFHack
{
class Core;
/**
* The Screen module
* \ingroup grp_modules
* \ingroup grp_screen
*/
namespace Screen
{
/// Data structure describing all properties a screen tile can have
struct Pen {
// Ordinary text symbol
char ch;
int8_t fg, bg;
bool bold;
// Graphics tile
int tile;
enum TileMode {
AsIs, // Tile colors used without modification
CharColor, // The fg/bg pair is used
TileColor // The fields below are used
} tile_mode;
int8_t tile_fg, tile_bg;
Pen(char ch = 0, int8_t fg = 7, int8_t bg = 0, int tile = 0, bool color_tile = false)
: ch(ch), fg(fg&7), bg(bg), bold(!!(fg&8)),
tile(tile), tile_mode(color_tile ? CharColor : AsIs), tile_fg(0), tile_bg(0)
{}
Pen(char ch, int8_t fg, int8_t bg, bool bold, int tile = 0, bool color_tile = false)
: ch(ch), fg(fg), bg(bg), bold(bold),
tile(tile), tile_mode(color_tile ? CharColor : AsIs), tile_fg(0), tile_bg(0)
{}
Pen(char ch, int8_t fg, int8_t bg, int tile, int8_t tile_fg, int8_t tile_bg)
: ch(ch), fg(fg&7), bg(bg), bold(!!(fg&8)),
tile(tile), tile_mode(TileColor), tile_fg(tile_fg), tile_bg(tile_bg)
{}
Pen(char ch, int8_t fg, int8_t bg, bool bold, int tile, int8_t tile_fg, int8_t tile_bg)
: ch(ch), fg(fg), bg(bg), bold(bold),
tile(tile), tile_mode(TileColor), tile_fg(tile_fg), tile_bg(tile_bg)
{}
};
DFHACK_EXPORT df::coord2d getMousePos();
DFHACK_EXPORT df::coord2d getWindowSize();
/// Returns the state of [GRAPHICS:YES/NO]
DFHACK_EXPORT bool inGraphicsMode();
/// Paint one screen tile with the given pen
DFHACK_EXPORT bool paintTile(const Pen &pen, int x, int y);
/// Paint a string onto the screen. Ignores ch and tile of pen.
DFHACK_EXPORT bool paintString(const Pen &pen, int x, int y, const std::string &text);
/// Fills a rectangle with one pen. Possibly more efficient than a loop over paintTile.
DFHACK_EXPORT bool fillRect(const Pen &pen, int x1, int y1, int x2, int y2);
/// Draws a standard dark gray window border with a title string
DFHACK_EXPORT bool drawBorder(const std::string &title);
/// Wipes the screen to full black
DFHACK_EXPORT bool clear();
/// Requests repaint
DFHACK_EXPORT bool invalidate();
/// Find a loaded graphics tile from graphics raws.
DFHACK_EXPORT bool findGraphicsTile(const std::string &page, int x, int y, int *ptile, int *pgs = NULL);
// Push and remove viewscreens
DFHACK_EXPORT bool show(df::viewscreen *screen, df::viewscreen *before = NULL);
DFHACK_EXPORT void dismiss(df::viewscreen *screen);
DFHACK_EXPORT bool isDismissed(df::viewscreen *screen);
}
class DFHACK_EXPORT dfhack_viewscreen : public df::viewscreen {
df::coord2d last_size;
void check_resize();
protected:
bool text_input_mode;
public:
dfhack_viewscreen();
virtual ~dfhack_viewscreen();
static bool is_instance(df::viewscreen *screen);
virtual void logic();
virtual void render();
virtual int8_t movies_okay() { return 1; }
virtual bool key_conflict(df::interface_key key);
virtual bool is_lua_screen() { return false; }
virtual std::string getFocusString() = 0;
};
class DFHACK_EXPORT dfhack_lua_viewscreen : public dfhack_viewscreen {
std::string focus;
void update_focus(lua_State *L, int idx);
bool safe_call_lua(int (*pf)(lua_State *), int args, int rvs);
static dfhack_lua_viewscreen *get_self(lua_State *L);
static int do_destroy(lua_State *L);
static int do_render(lua_State *L);
static int do_notify(lua_State *L);
static int do_input(lua_State *L);
public:
dfhack_lua_viewscreen(lua_State *L, int table_idx);
virtual ~dfhack_lua_viewscreen();
static df::viewscreen *get_pointer(lua_State *L, int idx, bool make);
virtual bool is_lua_screen() { return true; }
virtual std::string getFocusString() { return focus; }
virtual void render();
virtual void logic();
virtual void help();
virtual void resize(int w, int h);
virtual void feed(std::set<df::interface_key> *keys);
};
}

@ -226,6 +226,9 @@ DFHACK_EXPORT bool getNoblePositions(std::vector<NoblePosition> *pvec, df::unit
DFHACK_EXPORT std::string getProfessionName(df::unit *unit, bool ignore_noble = false, bool plural = false);
DFHACK_EXPORT std::string getCasteProfessionName(int race, int caste, df::profession pid, bool plural = false);
DFHACK_EXPORT int8_t getProfessionColor(df::unit *unit, bool ignore_noble = false);
DFHACK_EXPORT int8_t getCasteProfessionColor(int race, int caste, df::profession pid);
}
}
#endif

@ -102,6 +102,23 @@ function reload(module)
dofile(path)
end
-- Trivial classes
function defclass(class,parent)
class = class or {}
rawset(class, '__index', rawget(class, '__index') or class)
if parent then
setmetatable(class, parent)
end
return class
end
function mkinstance(class,table)
table = table or {}
setmetatable(table, class)
return table
end
-- Misc functions
function printall(table)
@ -188,6 +205,12 @@ function dfhack.buildings.getSize(bld)
return bld.x2+1-x, bld.y2+1-y, bld.centerx-x, bld.centery-y
end
dfhack.screen.__index = dfhack.screen
function dfhack.screen:__tostring()
return "<lua viewscreen: "..tostring(self._native)..">"
end
-- Interactive
local print_banner = true

@ -0,0 +1,354 @@
-- Viewscreen implementation utility collection.
local _ENV = mkmodule('gui')
local dscreen = dfhack.screen
CLEAR_PEN = {ch=32,fg=0,bg=0}
function simulateInput(screen,...)
local keys = {}
local function push_key(arg)
local kv = arg
if type(arg) == 'string' then
kv = df.interface_key[arg]
if kv == nil then
error('Invalid keycode: '..arg)
end
end
if type(arg) == 'number' then
keys[#keys+1] = kv
end
end
for i = 1,select('#',...) do
local arg = select(i,...)
if arg ~= nil then
local t = type(arg)
if type(arg) == 'table' then
for k,v in pairs(arg) do
if v == true then
push_key(k)
else
push_key(v)
end
end
else
push_key(arg)
end
end
end
dscreen._doSimulateInput(screen, keys)
end
function mkdims_xy(x1,y1,x2,y2)
return { x1=x1, y1=y1, x2=x2, y2=y2, width=x2-x1+1, height=y2-y1+1 }
end
function mkdims_wh(x1,y1,w,h)
return { x1=x1, y1=y1, x2=x1+w-1, y2=y1+h-1, width=w, height=h }
end
function inset(rect,dx1,dy1,dx2,dy2)
return mkdims_xy(
rect.x1+dx1, rect.y1+dy1,
rect.x2-(dx2 or dx1), rect.y2-(dy2 or dy1)
)
end
local function to_pen(default, pen, bg, bold)
if pen == nil then
return default or {}
elseif type(pen) ~= 'table' then
return {fg=pen,bg=bg,bold=bold}
else
return pen
end
end
----------------------------
-- Clipped painter object --
----------------------------
Painter = defclass(Painter, nil)
function Painter.new(rect, pen)
rect = rect or mkdims_wh(0,0,dscreen.getWindowSize())
local self = {
x1 = rect.x1, clip_x1 = rect.x1,
y1 = rect.y1, clip_y1 = rect.y1,
x2 = rect.x2, clip_x2 = rect.x2,
y2 = rect.y2, clip_y2 = rect.y2,
width = rect.x2-rect.x1+1,
height = rect.y2-rect.y1+1,
cur_pen = to_pen(nil, pen or COLOR_GREY)
}
return mkinstance(Painter, self):seek(0,0)
end
function Painter:isValidPos()
return self.x >= self.clip_x1 and self.x <= self.clip_x2
and self.y >= self.clip_y1 and self.y <= self.clip_y2
end
function Painter:viewport(x,y,w,h)
local x1,y1 = self.x1+x, self.y1+y
local x2,y2 = x1+w-1, y1+h-1
local vp = {
-- Logical viewport
x1 = x1, y1 = y1, x2 = x2, y2 = y2,
width = w, height = h,
-- Actual clipping rect
clip_x1 = math.max(self.clip_x1, x1),
clip_y1 = math.max(self.clip_y1, y1),
clip_x2 = math.min(self.clip_x2, x2),
clip_y2 = math.min(self.clip_y2, y2),
-- Pen
cur_pen = self.cur_pen
}
return mkinstance(Painter, vp):seek(0,0)
end
function Painter:localX()
return self.x - self.x1
end
function Painter:localY()
return self.y - self.y1
end
function Painter:seek(x,y)
if x then self.x = self.x1 + x end
if y then self.y = self.y1 + y end
return self
end
function Painter:advance(dx,dy)
if dx then self.x = self.x + dx end
if dy then self.y = self.y + dy end
return self
end
function Painter:newline(dx)
self.y = self.y + 1
self.x = self.x1 + (dx or 0)
return self
end
function Painter:pen(pen,...)
self.cur_pen = to_pen(self.cur_pen, pen, ...)
return self
end
function Painter:color(fg,bold,bg)
self.cur_pen = copyall(self.cur_pen)
self.cur_pen.fg = fg
self.cur_pen.bold = bold
if bg then self.cur_pen.bg = bg end
return self
end
function Painter:clear()
dscreen.fillRect(CLEAR_PEN, self.clip_x1, self.clip_y1, self.clip_x2, self.clip_y2)
return self
end
function Painter:fill(x1,y1,x2,y2,pen,bg,bold)
if type(x1) == 'table' then
x1, y1, x2, y2, pen, bg, bold = x1.x1, x1.y1, x1.x2, x1.y2, y1, x2, y2
end
x1 = math.max(x1,self.clip_x1)
y1 = math.max(y1,self.clip_y1)
x2 = math.min(x2,self.clip_x2)
y2 = math.min(y2,self.clip_y2)
dscreen.fillRect(to_pen(self.cur_pen,pen,bg,bold),x1,y1,x2,y2)
return self
end
function Painter:char(char,pen,...)
if self:isValidPos() then
dscreen.paintTile(to_pen(self.cur_pen, pen, ...), self.x, self.y, char)
end
return self:advance(1, nil)
end
function Painter:tile(char,tile,pen,...)
if self:isValidPos() then
dscreen.paintTile(to_pen(self.cur_pen, pen, ...), self.x, self.y, char, tile)
end
return self:advance(1, nil)
end
function Painter:string(text,pen,...)
if self.y >= self.clip_y1 and self.y <= self.clip_y2 then
local dx = 0
if self.x < self.clip_x1 then
dx = self.clip_x1 - self.x
end
local len = #text
if self.x + len - 1 > self.clip_x2 then
len = self.clip_x2 - self.x + 1
end
if len > dx then
dscreen.paintString(
to_pen(self.cur_pen, pen, ...),
self.x+dx, self.y,
string.sub(text,dx+1,len)
)
end
end
return self:advance(#text, nil)
end
------------------------
-- Base screen object --
------------------------
Screen = defclass(Screen, dfhack.screen)
Screen.text_input_mode = false
function Screen:isShown()
return self._native ~= nil
end
function Screen:isActive()
return self:isShown() and not self:isDismissed()
end
function Screen:renderParent()
if self._native and self._native.parent then
self._native.parent:render()
else
dscreen.clear()
end
end
function Screen:sendInputToParent(...)
if self._native and self._native.parent then
simulateInput(self._native.parent, ...)
end
end
function Screen:show(below)
if self._native then
error("This screen is already on display")
end
self:onAboutToShow(below)
if dscreen.show(self, below) then
self:onShown()
else
error('Could not show screen')
end
end
function Screen:onAboutToShow()
end
function Screen:onShown()
end
function Screen:dismiss()
if self._native and not dscreen.isDismissed(self) then
dscreen.dismiss(self)
self:onDismissed()
end
end
function Screen:onDismissed()
end
------------------------
-- Framed screen object --
------------------------
-- Plain grey-colored frame.
GREY_FRAME = {
frame_pen = { ch = ' ', fg = COLOR_BLACK, bg = COLOR_GREY },
title_pen = { fg = COLOR_BLACK, bg = COLOR_WHITE },
signature_pen = { fg = COLOR_BLACK, bg = COLOR_GREY },
}
-- The usual boundary used by the DF screens. Often has fancy pattern in tilesets.
BOUNDARY_FRAME = {
frame_pen = { ch = 0xDB, fg = COLOR_DARKGREY, bg = COLOR_BLACK },
title_pen = { fg = COLOR_BLACK, bg = COLOR_GREY },
signature_pen = { fg = COLOR_BLACK, bg = COLOR_DARKGREY },
}
GREY_LINE_FRAME = {
frame_pen = { ch = 206, fg = COLOR_GREY, bg = COLOR_BLACK },
h_frame_pen = { ch = 205, fg = COLOR_GREY, bg = COLOR_BLACK },
v_frame_pen = { ch = 186, fg = COLOR_GREY, bg = COLOR_BLACK },
lt_frame_pen = { ch = 201, fg = COLOR_GREY, bg = COLOR_BLACK },
lb_frame_pen = { ch = 200, fg = COLOR_GREY, bg = COLOR_BLACK },
rt_frame_pen = { ch = 187, fg = COLOR_GREY, bg = COLOR_BLACK },
rb_frame_pen = { ch = 188, fg = COLOR_GREY, bg = COLOR_BLACK },
title_pen = { fg = COLOR_BLACK, bg = COLOR_GREY },
signature_pen = { fg = COLOR_DARKGREY, bg = COLOR_BLACK },
}
function paint_frame(x1,y1,x2,y2,style,title)
local pen = style.frame_pen
dscreen.paintTile(style.lt_frame_pen or pen, x1, y1)
dscreen.paintTile(style.rt_frame_pen or pen, x2, y1)
dscreen.paintTile(style.lb_frame_pen or pen, x1, y2)
dscreen.paintTile(style.rb_frame_pen or pen, x2, y2)
dscreen.fillRect(style.t_frame_pen or style.h_frame_pen or pen,x1+1,y1,x2-1,y1)
dscreen.fillRect(style.b_frame_pen or style.h_frame_pen or pen,x1+1,y2,x2-1,y2)
dscreen.fillRect(style.l_frame_pen or style.v_frame_pen or pen,x1,y1+1,x1,y2-1)
dscreen.fillRect(style.r_frame_pen or style.v_frame_pen or pen,x2,y1+1,x2,y2-1)
dscreen.paintString(style.signature_pen or style.title_pen or pen,x2-7,y2,"DFHack")
if title then
local x = math.max(0,math.floor((x2-x1-3-#title)/2)) + x1
local tstr = ' '..title..' '
if #tstr > x2-x1-1 then
tstr = string.sub(tstr,1,x2-x1-1)
end
dscreen.paintString(style.title_pen or pen, x, y1, tstr)
end
end
FramedScreen = defclass(FramedScreen, Screen)
FramedScreen.frame_style = BOUNDARY_FRAME
local function hint_coord(gap,hint)
if hint and hint > 0 then
return math.min(hint,gap)
elseif hint and hint < 0 then
return math.max(0,gap-hint)
else
return math.floor(gap/2)
end
end
function FramedScreen:updateFrameSize(sw,sh)
local iw, ih = sw-2, sh-2
local width = math.min(self.frame_width or iw, iw)
local height = math.min(self.frame_height or ih, ih)
local gw, gh = iw-width, ih-height
local x1, y1 = hint_coord(gw,self.frame_xhint), hint_coord(gh,self.frame_yhint)
self.frame_rect = mkdims_wh(x1+1,y1+1,width,height)
self.frame_opaque = (gw == 0 and gh == 0)
end
function FramedScreen:onResize(w,h)
self:updateFrameSize(w,h)
end
function FramedScreen:onRender()
local rect = self.frame_rect
local x1,y1,x2,y2 = rect.x1-1, rect.y1-1, rect.x2+1, rect.y2+1
if self.frame_opaque then
dscreen.clear()
else
self:renderParent()
dscreen.fillRect(CLEAR_PEN,x1,y1,x2,y2)
end
paint_frame(x1,y1,x2,y2,self.frame_style,self.frame_title)
self:onRenderBody(Painter.new(rect))
end
return _ENV

@ -0,0 +1,266 @@
-- Support for messing with the dwarfmode screen
local _ENV = mkmodule('gui.dwarfmode')
local gui = require('gui')
local dscreen = dfhack.screen
local world_map = df.global.world.map
AREA_MAP_WIDTH = 23
MENU_WIDTH = 30
function getPanelLayout()
local sw, sh = dscreen.getWindowSize()
local view_height = sh-2
local view_rb = sw-1
local area_x2 = sw-AREA_MAP_WIDTH-2
local menu_x2 = sw-MENU_WIDTH-2
local menu_x1 = area_x2-MENU_WIDTH-1
local area_pos = df.global.ui_area_map_width
local menu_pos = df.global.ui_menu_width
local rv = {}
if area_pos < 3 then
rv.area_map = gui.mkdims_xy(area_x2+1,1,view_rb-1,view_height)
view_rb = area_x2
end
if menu_pos < area_pos or df.global.ui.main.mode ~= 0 then
if menu_pos >= area_pos then
rv.menu_forced = true
menu_pos = area_pos-1
end
local menu_x = menu_x2
if menu_pos < 2 then menu_x = menu_x1 end
rv.menu = gui.mkdims_xy(menu_x+1,1,view_rb-1,view_height)
view_rb = menu_x
end
rv.area_pos = area_pos
rv.menu_pos = menu_pos
rv.map = gui.mkdims_xy(1,1,view_rb-1,view_height)
return rv
end
function getCursorPos()
if df.global.cursor.x ~= -30000 then
return copyall(df.global.cursor)
end
end
function setCursorPos(cursor)
df.global.cursor = cursor
end
function clearCursorPos()
df.global.cursor = xyz2pos(nil)
end
Viewport = defclass(Viewport)
function Viewport.make(map,x,y,z)
local self = gui.mkdims_wh(x,y,map.width,map.height)
self.z = z
return mkinstance(Viewport, self)
end
function Viewport.get(layout)
return Viewport.make(
(layout or getPanelLayout()).map,
df.global.window_x,
df.global.window_y,
df.global.window_z
)
end
function Viewport:resize(layout)
return Viewport.make(
(layout or getPanelLayout()).map,
self.x1, self.y1, self.z
)
end
function Viewport:set()
local vp = self:clip()
df.global.window_x = vp.x1
df.global.window_y = vp.y1
df.global.window_z = vp.z
return vp
end
function Viewport:clip(x,y,z)
return self:make(
math.max(0, math.min(x or self.x1, world_map.x_count-self.width)),
math.max(0, math.min(y or self.y1, world_map.y_count-self.height)),
math.max(0, math.min(z or self.z, world_map.z_count-1))
)
end
function Viewport:isVisibleXY(target,gap)
gap = gap or 0
return math.max(target.x-gap,0) >= self.x1
and math.min(target.x+gap,world_map.x_count-1) <= self.x2
and math.max(target.y-gap,0) >= self.y1
and math.min(target.y+gap,world_map.y_count-1) <= self.y2
end
function Viewport:isVisible(target,gap)
gap = gap or 0
return self:isVisibleXY(target,gap) and target.z == self.z
end
function Viewport:centerOn(target)
return self:clip(
target.x - math.floor(self.width/2),
target.y - math.floor(self.height/2),
target.z
)
end
function Viewport:scrollTo(target,gap)
gap = math.max(0, gap or 5)
if gap*2 >= math.min(self.width, self.height) then
gap = math.floor(math.min(self.width, self.height)/2)
end
local x = math.min(self.x1, target.x-gap)
x = math.max(x, target.x+gap+1-self.width)
local y = math.min(self.y1, target.y-gap)
y = math.max(y, target.y+gap+1-self.height)
return self:clip(x, y, target.z)
end
function Viewport:reveal(target,gap,max_scroll,scroll_gap,scroll_z)
gap = math.max(0, gap or 5)
if self:isVisible(target, gap) then
return self
end
max_scroll = math.max(0, max_scroll or 5)
if self:isVisibleXY(target, -max_scroll)
and (scroll_z or target.z == self.z) then
return self:scrollTo(target, scroll_gap or gap)
else
return self:centerOn(target)
end
end
MOVEMENT_KEYS = {
CURSOR_UP = { 0, -1, 0 }, CURSOR_DOWN = { 0, 1, 0 },
CURSOR_LEFT = { -1, 0, 0 }, CURSOR_RIGHT = { 1, 0, 0 },
CURSOR_UPLEFT = { -1, -1, 0 }, CURSOR_UPRIGHT = { 1, -1, 0 },
CURSOR_DOWNLEFT = { -1, 1, 0 }, CURSOR_DOWNRIGHT = { 1, 1, 0 },
CURSOR_UP_FAST = { 0, -1, 0, true }, CURSOR_DOWN_FAST = { 0, 1, 0, true },
CURSOR_LEFT_FAST = { -1, 0, 0, true }, CURSOR_RIGHT_FAST = { 1, 0, 0, true },
CURSOR_UPLEFT_FAST = { -1, -1, 0, true }, CURSOR_UPRIGHT_FAST = { 1, -1, 0, true },
CURSOR_DOWNLEFT_FAST = { -1, 1, 0, true }, CURSOR_DOWNRIGHT_FAST = { 1, 1, 0, true },
CURSOR_UP_Z = { 0, 0, 1 }, CURSOR_DOWN_Z = { 0, 0, -1 },
CURSOR_UP_Z_AUX = { 0, 0, 1 }, CURSOR_DOWN_Z_AUX = { 0, 0, -1 },
}
function Viewport:scrollByKey(key)
local info = MOVEMENT_KEYS[key]
if info then
local delta = 10
if info[4] then delta = 20 end
return self:clip(
self.x1 + delta*info[1],
self.y1 + delta*info[2],
self.z + info[3]
)
else
return self
end
end
DwarfOverlay = defclass(DwarfOverlay, gui.Screen)
function DwarfOverlay:updateLayout()
self.df_layout = getPanelLayout()
end
function DwarfOverlay:onShown()
self:updateLayout()
end
function DwarfOverlay:onResize(w,h)
self:updateLayout()
end
function DwarfOverlay:getViewport(old_vp)
if old_vp then
return old_vp:resize(self.df_layout)
else
return Viewport.get(self.df_layout)
end
end
function DwarfOverlay:propagateMoveKeys(keys)
for code,_ in pairs(MOVEMENT_KEYS) do
if keys[code] then
self:sendInputToParent(code)
return code
end
end
end
function DwarfOverlay:simulateViewScroll(keys, anchor, no_clip_cursor)
local layout = self.df_layout
local cursor = getCursorPos()
anchor = anchor or cursor
if anchor and keys.A_MOVE_SAME_SQUARE then
self:getViewport():centerOn(anchor):set()
return 'A_MOVE_SAME_SQUARE'
end
for code,_ in pairs(MOVEMENT_KEYS) do
if keys[code] then
local vp = self:getViewport():scrollByKey(code)
if (cursor and not no_clip_cursor) or no_clip_cursor == false then
vp = vp:reveal(anchor,4,20,4,true)
end
vp:set()
return code
end
end
end
function DwarfOverlay:onAboutToShow(below)
local screen = dfhack.gui.getCurViewscreen()
if below then screen = below.parent end
if not df.viewscreen_dwarfmodest:is_instance(screen) then
error("This screen requires the main dwarfmode view")
end
end
MenuOverlay = defclass(MenuOverlay, DwarfOverlay)
function MenuOverlay:onAboutToShow(below)
DwarfOverlay.onAboutToShow(self,below)
self:updateLayout()
if not self.df_layout.menu then
error("The menu panel of dwarfmode is not visible")
end
end
function MenuOverlay:onRender()
self:renderParent()
self:updateLayout()
local menu = self.df_layout.menu
if menu then
-- Paint signature on the frame.
dscreen.paintString(
{fg=COLOR_BLACK,bg=COLOR_DARKGREY},
menu.x1+1, menu.y2+1, "DFHack"
)
self:onRenderBody(gui.Painter.new(menu))
end
end
return _ENV

@ -361,6 +361,18 @@ function insert_or_update(vector,item,field,cmp)
return added,cur,pos
end
-- Calls a method with a string temporary
function call_with_string(obj,methodname,...)
return dfhack.with_temp_object(
df.new "string",
function(str,obj,methodname,...)
obj[methodname](obj,str,...)
return str.value
end,
obj,methodname,...
)
end
-- Ask a yes-no question
function prompt_yes_no(msg,default)
local prompt = msg

@ -42,6 +42,7 @@ using namespace std;
using namespace DFHack;
#include "modules/Job.h"
#include "modules/Screen.h"
#include "DataDefs.h"
#include "df/world.h"
@ -466,6 +467,11 @@ std::string Gui::getFocusString(df::viewscreen *top)
return name;
}
else if (dfhack_viewscreen::is_instance(top))
{
auto name = static_cast<dfhack_viewscreen*>(top)->getFocusString();
return name.empty() ? "dfhack" : "dfhack/"+name;
}
else
{
Core &core = Core::getInstance();

@ -189,7 +189,7 @@ void DFHack::Job::printJobDetails(color_ostream &out, df::job *job)
{
CHECK_NULL_POINTER(job);
out.color(job->flags.bits.suspend ? Console::COLOR_DARKGREY : Console::COLOR_GREY);
out.color(job->flags.bits.suspend ? COLOR_DARKGREY : COLOR_GREY);
out << "Job " << job->id << ": " << ENUM_KEY_STR(job_type,job->job_type);
if (job->flags.whole)
out << " (" << bitfield_to_string(job->flags) << ")";

@ -0,0 +1,578 @@
/*
https://github.com/peterix/dfhack
Copyright (c) 2009-2011 Petr Mrázek (peterix@gmail.com)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "Internal.h"
#include <string>
#include <vector>
#include <map>
using namespace std;
#include "modules/Screen.h"
#include "MemAccess.h"
#include "VersionInfo.h"
#include "Types.h"
#include "Error.h"
#include "ModuleFactory.h"
#include "Core.h"
#include "PluginManager.h"
#include "LuaTools.h"
#include "MiscUtils.h"
using namespace DFHack;
#include "DataDefs.h"
#include "df/init.h"
#include "df/texture_handler.h"
#include "df/tile_page.h"
#include "df/interfacest.h"
#include "df/enabler.h"
using namespace df::enums;
using df::global::init;
using df::global::gps;
using df::global::texture;
using df::global::gview;
using df::global::enabler;
using Screen::Pen;
/*
* Screen painting API.
*/
df::coord2d Screen::getMousePos()
{
if (!gps || (enabler && !enabler->tracking_on))
return df::coord2d(-1, -1);
return df::coord2d(gps->mouse_x, gps->mouse_y);
}
df::coord2d Screen::getWindowSize()
{
if (!gps) return df::coord2d(80, 25);
return df::coord2d(gps->dimx, gps->dimy);
}
bool Screen::inGraphicsMode()
{
return init && init->display.flag.is_set(init_display_flags::USE_GRAPHICS);
}
static void doSetTile(const Pen &pen, int index)
{
auto screen = gps->screen + index*4;
screen[0] = uint8_t(pen.ch);
screen[1] = uint8_t(pen.fg) & 15;
screen[2] = uint8_t(pen.bg) & 15;
screen[3] = uint8_t(pen.bold) & 1;
gps->screentexpos[index] = pen.tile;
gps->screentexpos_addcolor[index] = (pen.tile_mode == Screen::Pen::CharColor);
gps->screentexpos_grayscale[index] = (pen.tile_mode == Screen::Pen::TileColor);
gps->screentexpos_cf[index] = pen.tile_fg;
gps->screentexpos_cbr[index] = pen.tile_bg;
}
bool Screen::paintTile(const Pen &pen, int x, int y)
{
if (!gps) return false;
int dimx = gps->dimx, dimy = gps->dimy;
if (x < 0 || x >= dimx || y < 0 || y >= dimy) return false;
doSetTile(pen, x*dimy + y);
return true;
}
bool Screen::paintString(const Pen &pen, int x, int y, const std::string &text)
{
if (!gps || y < 0 || y >= gps->dimy) return false;
Pen tmp(pen);
bool ok = false;
for (size_t i = -std::min(0,x); i < text.size(); i++)
{
if (x + i >= size_t(gps->dimx))
break;
tmp.ch = text[i];
tmp.tile = (pen.tile ? pen.tile + uint8_t(text[i]) : 0);
paintTile(tmp, x+i, y);
ok = true;
}
return ok;
}
bool Screen::fillRect(const Pen &pen, int x1, int y1, int x2, int y2)
{
if (!gps) return false;
if (x1 < 0) x1 = 0;
if (y1 < 0) y1 = 0;
if (x2 >= gps->dimx) x2 = gps->dimx-1;
if (y2 >= gps->dimy) y2 = gps->dimy-1;
if (x1 > x2 || y1 > y2) return false;
for (int x = x1; x <= x2; x++)
{
int index = x*gps->dimy;
for (int y = y1; y <= y2; y++)
doSetTile(pen, index+y);
}
return true;
}
bool Screen::drawBorder(const std::string &title)
{
if (!gps) return false;
int dimx = gps->dimx, dimy = gps->dimy;
Pen border(0xDB, 8);
Pen text(0, 0, 7);
Pen signature(0, 0, 8);
for (int x = 0; x < dimx; x++)
{
doSetTile(border, x * dimy + 0);
doSetTile(border, x * dimy + dimy - 1);
}
for (int y = 0; y < dimy; y++)
{
doSetTile(border, 0 * dimy + y);
doSetTile(border, (dimx - 1) * dimy + y);
}
paintString(signature, dimx-8, dimy-1, "DFHack");
return paintString(text, (dimx - title.length()) / 2, 0, title);
}
bool Screen::clear()
{
if (!gps) return false;
return fillRect(Pen(' ',0,0,false), 0, 0, gps->dimx-1, gps->dimy-1);
}
bool Screen::invalidate()
{
if (!enabler) return false;
enabler->flag.bits.render = true;
return true;
}
bool Screen::findGraphicsTile(const std::string &pagename, int x, int y, int *ptile, int *pgs)
{
if (!gps || !texture || x < 0 || y < 0) return false;
for (size_t i = 0; i < texture->page.size(); i++)
{
auto page = texture->page[i];
if (!page->loaded || page->token != pagename) continue;
if (x >= page->page_dim_x || y >= page->page_dim_y)
break;
int idx = y*page->page_dim_x + x;
if (size_t(idx) >= page->texpos.size())
break;
if (ptile) *ptile = page->texpos[idx];
if (pgs) *pgs = page->texpos_gs[idx];
return true;
}
return false;
}
bool Screen::show(df::viewscreen *screen, df::viewscreen *before)
{
CHECK_NULL_POINTER(screen);
CHECK_INVALID_ARGUMENT(!screen->parent && !screen->child);
if (!gps || !gview) return false;
df::viewscreen *parent = &gview->view;
while (parent && parent->child != before)
parent = parent->child;
if (!parent) return false;
gps->force_full_display_count += 2;
screen->child = parent->child;
screen->parent = parent;
parent->child = screen;
if (screen->child)
screen->child->parent = screen;
return true;
}
void Screen::dismiss(df::viewscreen *screen)
{
CHECK_NULL_POINTER(screen);
screen->breakdown_level = interface_breakdown_types::STOPSCREEN;
}
bool Screen::isDismissed(df::viewscreen *screen)
{
CHECK_NULL_POINTER(screen);
return screen->breakdown_level != interface_breakdown_types::NONE;
}
/*
* Base DFHack viewscreen.
*/
static std::set<df::viewscreen*> dfhack_screens;
dfhack_viewscreen::dfhack_viewscreen() : text_input_mode(false)
{
dfhack_screens.insert(this);
}
dfhack_viewscreen::~dfhack_viewscreen()
{
dfhack_screens.erase(this);
}
bool dfhack_viewscreen::is_instance(df::viewscreen *screen)
{
return dfhack_screens.count(screen) != 0;
}
void dfhack_viewscreen::check_resize()
{
auto size = Screen::getWindowSize();
if (size != last_size)
{
last_size = size;
resize(size.x, size.y);
}
}
void dfhack_viewscreen::logic()
{
check_resize();
// Various stuff works poorly unless always repainting
Screen::invalidate();
}
void dfhack_viewscreen::render()
{
check_resize();
}
bool dfhack_viewscreen::key_conflict(df::interface_key key)
{
if (key == interface_key::OPTIONS)
return true;
if (text_input_mode)
{
if (key == interface_key::HELP || key == interface_key::MOVIES)
return true;
}
return false;
}
/*
* Lua-backed viewscreen.
*/
static int DFHACK_LUA_VS_TOKEN = 0;
df::viewscreen *dfhack_lua_viewscreen::get_pointer(lua_State *L, int idx, bool make)
{
df::viewscreen *screen;
if (lua_istable(L, idx))
{
if (!Lua::IsCoreContext(L))
luaL_error(L, "only the core context can create lua screens");
lua_rawgetp(L, idx, &DFHACK_LUA_VS_TOKEN);
if (!lua_isnil(L, -1))
{
if (make)
luaL_error(L, "this screen is already on display");
screen = (df::viewscreen*)lua_touserdata(L, -1);
}
else
{
if (!make)
luaL_error(L, "this screen is not on display");
screen = new dfhack_lua_viewscreen(L, idx);
}
lua_pop(L, 1);
}
else
screen = Lua::CheckDFObject<df::viewscreen>(L, idx);
return screen;
}
bool dfhack_lua_viewscreen::safe_call_lua(int (*pf)(lua_State *), int args, int rvs)
{
CoreSuspendClaimer suspend;
color_ostream_proxy out(Core::getInstance().getConsole());
auto L = Lua::Core::State;
lua_pushcfunction(L, pf);
if (args > 0) lua_insert(L, -args-1);
lua_pushlightuserdata(L, this);
if (args > 0) lua_insert(L, -args-1);
return Lua::Core::SafeCall(out, args+1, rvs);
}
dfhack_lua_viewscreen *dfhack_lua_viewscreen::get_self(lua_State *L)
{
auto self = (dfhack_lua_viewscreen*)lua_touserdata(L, 1);
lua_rawgetp(L, LUA_REGISTRYINDEX, self);
if (!lua_istable(L, -1)) return NULL;
return self;
}
int dfhack_lua_viewscreen::do_destroy(lua_State *L)
{
auto self = get_self(L);
if (!self) return 0;
lua_pushnil(L);
lua_rawsetp(L, LUA_REGISTRYINDEX, self);
lua_pushnil(L);
lua_rawsetp(L, -2, &DFHACK_LUA_VS_TOKEN);
lua_pushnil(L);
lua_setfield(L, -2, "_native");
lua_getfield(L, -1, "onDestroy");
if (lua_isnil(L, -1))
return 0;
lua_pushvalue(L, -2);
lua_call(L, 1, 0);
return 0;
}
void dfhack_lua_viewscreen::update_focus(lua_State *L, int idx)
{
lua_getfield(L, idx, "text_input_mode");
text_input_mode = lua_toboolean(L, -1);
lua_pop(L, 1);
lua_getfield(L, idx, "focus_path");
auto str = lua_tostring(L, -1);
if (!str) str = "";
focus = str;
lua_pop(L, 1);
if (focus.empty())
focus = "lua";
else
focus = "lua/"+focus;
}
int dfhack_lua_viewscreen::do_render(lua_State *L)
{
auto self = get_self(L);
if (!self) return 0;
lua_getfield(L, -1, "onRender");
if (lua_isnil(L, -1))
{
Screen::clear();
return 0;
}
lua_pushvalue(L, -2);
lua_call(L, 1, 0);
return 0;
}
int dfhack_lua_viewscreen::do_notify(lua_State *L)
{
int args = lua_gettop(L);
auto self = get_self(L);
if (!self) return 0;
lua_pushvalue(L, 2);
lua_gettable(L, -2);
if (lua_isnil(L, -1))
return 0;
// self field args table fn -> table fn table args
lua_replace(L, 1);
lua_copy(L, -1, 2);
lua_insert(L, 1);
lua_call(L, args-1, 1);
self->update_focus(L, 1);
return 1;
}
int dfhack_lua_viewscreen::do_input(lua_State *L)
{
auto self = get_self(L);
if (!self) return 0;
auto keys = (std::set<df::interface_key>*)lua_touserdata(L, 2);
lua_getfield(L, -1, "onInput");
if (lua_isnil(L, -1))
{
if (keys->count(interface_key::LEAVESCREEN))
Screen::dismiss(self);
return 0;
}
lua_pushvalue(L, -2);
lua_createtable(L, 0, keys->size()+3);
for (auto it = keys->begin(); it != keys->end(); ++it)
{
auto key = *it;
if (auto name = enum_item_raw_key(key))
lua_pushstring(L, name);
else
lua_pushinteger(L, key);
lua_pushboolean(L, true);
lua_rawset(L, -3);
if (key >= interface_key::STRING_A000 &&
key <= interface_key::STRING_A255)
{
lua_pushinteger(L, key - interface_key::STRING_A000);
lua_setfield(L, -2, "_STRING");
}
}
if (enabler && enabler->tracking_on)
{
if (enabler->mouse_lbut) {
lua_pushboolean(L, true);
lua_setfield(L, -2, "_MOUSE_L");
}
if (enabler->mouse_rbut) {
lua_pushboolean(L, true);
lua_setfield(L, -2, "_MOUSE_R");
}
}
lua_call(L, 2, 0);
self->update_focus(L, -1);
return 0;
}
dfhack_lua_viewscreen::dfhack_lua_viewscreen(lua_State *L, int table_idx)
{
assert(Lua::IsCoreContext(L));
Lua::PushDFObject(L, (df::viewscreen*)this);
lua_setfield(L, table_idx, "_native");
lua_pushlightuserdata(L, this);
lua_rawsetp(L, table_idx, &DFHACK_LUA_VS_TOKEN);
lua_pushvalue(L, table_idx);
lua_rawsetp(L, LUA_REGISTRYINDEX, this);
update_focus(L, table_idx);
}
dfhack_lua_viewscreen::~dfhack_lua_viewscreen()
{
safe_call_lua(do_destroy, 0, 0);
}
void dfhack_lua_viewscreen::render()
{
if (Screen::isDismissed(this)) return;
dfhack_viewscreen::render();
safe_call_lua(do_render, 0, 0);
}
void dfhack_lua_viewscreen::logic()
{
if (Screen::isDismissed(this)) return;
dfhack_viewscreen::logic();
lua_pushstring(Lua::Core::State, "onIdle");
safe_call_lua(do_notify, 1, 0);
}
void dfhack_lua_viewscreen::help()
{
if (Screen::isDismissed(this)) return;
lua_pushstring(Lua::Core::State, "onHelp");
safe_call_lua(do_notify, 1, 0);
}
void dfhack_lua_viewscreen::resize(int w, int h)
{
if (Screen::isDismissed(this)) return;
auto L = Lua::Core::State;
lua_pushstring(L, "onResize");
lua_pushinteger(L, w);
lua_pushinteger(L, h);
safe_call_lua(do_notify, 3, 0);
}
void dfhack_lua_viewscreen::feed(std::set<df::interface_key> *keys)
{
if (Screen::isDismissed(this)) return;
lua_pushlightuserdata(Lua::Core::State, keys);
safe_call_lua(do_input, 1, 0);
}

@ -948,3 +948,40 @@ std::string DFHack::Units::getCasteProfessionName(int race, int casteid, df::pro
return Translation::capitalize(prof, true);
}
int8_t DFHack::Units::getProfessionColor(df::unit *unit, bool ignore_noble)
{
std::vector<NoblePosition> np;
if (!ignore_noble && getNoblePositions(&np, unit))
{
if (np[0].position->flags.is_set(entity_position_flags::COLOR))
return np[0].position->color[0] + np[0].position->color[2] * 8;
}
return getCasteProfessionColor(unit->race, unit->caste, unit->profession);
}
int8_t DFHack::Units::getCasteProfessionColor(int race, int casteid, df::profession pid)
{
// make sure it's an actual profession
if (pid < 0 || !is_valid_enum_item(pid))
return 3;
// If it's not a Peasant, it's hardcoded
if (pid != profession::STANDARD)
return ENUM_ATTR(profession, color, pid);
if (auto creature = df::creature_raw::find(race))
{
if (auto caste = vector_get(creature->caste, casteid))
{
if (caste->flags.is_set(caste_raw_flags::CASTE_COLOR))
return caste->caste_color[0] + caste->caste_color[2] * 8;
}
return creature->color[0] + creature->color[2] * 8;
}
// default to dwarven peasant color
return 3;
}

@ -1 +1 @@
Subproject commit 9f91e74767b4d583b580d46e16143216ba62ae66
Subproject commit 1eeaa08360c39a9a2d811544c2443309adc1a8f1

@ -110,6 +110,7 @@ if (BUILD_SUPPORTED)
DFHACK_PLUGIN(catsplosion catsplosion.cpp)
DFHACK_PLUGIN(regrass regrass.cpp)
DFHACK_PLUGIN(forceequip forceequip.cpp)
DFHACK_PLUGIN(manipulator manipulator.cpp)
# this one exports functions to lua
DFHACK_PLUGIN(burrows burrows.cpp LINK_LIBRARIES lua)
DFHACK_PLUGIN(sort sort.cpp LINK_LIBRARIES lua)

@ -462,7 +462,7 @@ void joinCounts(std::map<df::coord, int> &counts)
static void printCompanionHeader(color_ostream &out, size_t i, df::unit *unit)
{
out.color(Console::COLOR_GREY);
out.color(COLOR_GREY);
if (i < 28)
out << char('a'+i);

@ -114,6 +114,28 @@ command_result cleanunits (color_ostream &out)
return CR_OK;
}
command_result cleanplants (color_ostream &out)
{
// Invoked from clean(), already suspended
int cleaned_plants = 0, cleaned_total = 0;
for (size_t i = 0; i < world->plants.all.size(); i++)
{
df::plant *plant = world->plants.all[i];
if (plant->contaminants.size())
{
for (size_t j = 0; j < plant->contaminants.size(); j++)
delete plant->contaminants[j];
cleaned_plants++;
cleaned_total += plant->contaminants.size();
plant->contaminants.clear();
}
}
if (cleaned_total)
out.print("Removed %d contaminants from %d plants.\n", cleaned_total, cleaned_plants);
return CR_OK;
}
command_result spotclean (color_ostream &out, vector <string> & parameters)
{
// HOTKEY COMMAND: CORE ALREADY SUSPENDED
@ -153,6 +175,7 @@ command_result clean (color_ostream &out, vector <string> & parameters)
bool mud = false;
bool units = false;
bool items = false;
bool plants = false;
for(size_t i = 0; i < parameters.size();i++)
{
if(parameters[i] == "map")
@ -161,11 +184,14 @@ command_result clean (color_ostream &out, vector <string> & parameters)
units = true;
else if(parameters[i] == "items")
items = true;
else if(parameters[i] == "plants")
plants = true;
else if(parameters[i] == "all")
{
map = true;
items = true;
units = true;
plants = true;
}
else if(parameters[i] == "snow")
snow = true;
@ -174,7 +200,7 @@ command_result clean (color_ostream &out, vector <string> & parameters)
else
return CR_WRONG_USAGE;
}
if(!map && !units && !items)
if(!map && !units && !items && !plants)
return CR_WRONG_USAGE;
CoreSuspender suspend;
@ -185,6 +211,8 @@ command_result clean (color_ostream &out, vector <string> & parameters)
cleanunits(out);
if(items)
cleanitems(out);
if(plants)
cleanplants(out);
return CR_OK;
}
@ -198,6 +226,7 @@ DFhackCExport command_result plugin_init ( color_ostream &out, std::vector <Plug
" map - clean the map tiles\n"
" items - clean all items\n"
" units - clean all creatures\n"
" plants - clean all plants\n"
" all - clean everything.\n"
"More options for 'map':\n"
" snow - also remove snow\n"

@ -17,3 +17,4 @@ DFHACK_PLUGIN(stockcheck stockcheck.cpp)
DFHACK_PLUGIN(stripcaged stripcaged.cpp)
DFHACK_PLUGIN(rprobe rprobe.cpp)
DFHACK_PLUGIN(nestboxes nestboxes.cpp)
DFHACK_PLUGIN(vshook vshook.cpp)

@ -257,7 +257,7 @@ command_result kittens (color_ostream &out, vector <string> & parameters)
};
con.cursor(false);
con.clear();
Console::color_value color = Console::COLOR_BLUE;
Console::color_value color = COLOR_BLUE;
while(1)
{
if(shutdown_flag)
@ -282,7 +282,7 @@ command_result kittens (color_ostream &out, vector <string> & parameters)
con.flush();
con.msleep(60);
((int&)color) ++;
if(color > Console::COLOR_MAX)
color = Console::COLOR_BLUE;
if(color > COLOR_MAX)
color = COLOR_BLUE;
}
}

@ -73,7 +73,7 @@ void outputHex(uint8_t *buf,uint8_t *lbuf,size_t len,size_t start,color_ostream
con.reset_color();
if(isAddr((uint32_t *)(buf+j+i),ranges))
con.color(Console::COLOR_LIGHTRED); //coloring in the middle does not work
con.color(COLOR_LIGHTRED); //coloring in the middle does not work
//TODO make something better?
}
if(lbuf[j+i]!=buf[j+i])

@ -0,0 +1,55 @@
#include "Core.h"
#include <Console.h>
#include <Export.h>
#include <PluginManager.h>
#include <modules/Gui.h>
#include <modules/Screen.h>
#include <vector>
#include <cstdio>
#include <stack>
#include <string>
#include <cmath>
#include <VTableInterpose.h>
#include "df/graphic.h"
#include "df/viewscreen_titlest.h"
using std::vector;
using std::string;
using std::stack;
using namespace DFHack;
using df::global::gps;
DFHACK_PLUGIN("vshook");
struct title_hook : df::viewscreen_titlest {
typedef df::viewscreen_titlest interpose_base;
DEFINE_VMETHOD_INTERPOSE(void, render, ())
{
INTERPOSE_NEXT(render)();
Screen::Pen pen(' ',COLOR_WHITE,COLOR_BLACK);
Screen::paintString(pen,0,0,"DFHack " DFHACK_VERSION);
}
};
IMPLEMENT_VMETHOD_INTERPOSE(title_hook, render);
DFhackCExport command_result plugin_init ( color_ostream &out, std::vector <PluginCommand> &commands)
{
if (gps)
{
if (!INTERPOSE_HOOK(title_hook, render).apply())
out.printerr("Could not interpose viewscreen_titlest::render\n");
}
return CR_OK;
}
DFhackCExport command_result plugin_shutdown ( color_ostream &out )
{
INTERPOSE_HOOK(title_hook, render).remove();
return CR_OK;
}

@ -0,0 +1,661 @@
// Dwarf Manipulator - a Therapist-style labor editor
#include "Core.h"
#include <Console.h>
#include <Export.h>
#include <PluginManager.h>
#include <MiscUtils.h>
#include <modules/Screen.h>
#include <modules/Translation.h>
#include <modules/Units.h>
#include <vector>
#include <string>
#include <set>
#include <VTableInterpose.h>
#include "df/world.h"
#include "df/ui.h"
#include "df/graphic.h"
#include "df/enabler.h"
#include "df/viewscreen_unitlistst.h"
#include "df/interface_key.h"
#include "df/unit.h"
#include "df/unit_soul.h"
#include "df/unit_skill.h"
#include "df/creature_raw.h"
#include "df/caste_raw.h"
using std::set;
using std::vector;
using std::string;
using namespace DFHack;
using namespace df::enums;
using df::global::world;
using df::global::ui;
using df::global::gps;
using df::global::enabler;
DFHACK_PLUGIN("manipulator");
struct SkillLevel
{
const char *name;
int points;
char abbrev;
};
#define NUM_SKILL_LEVELS (sizeof(skill_levels) / sizeof(SkillLevel))
// The various skill rankings. Zero skill is hardcoded to "Not" and '-'.
const SkillLevel skill_levels[] = {
{"Dabbling", 500, '0'},
{"Novice", 600, '1'},
{"Adequate", 700, '2'},
{"Competent", 800, '3'},
{"Skilled", 900, '4'},
{"Proficient", 1000, '5'},
{"Talented", 1100, '6'},
{"Adept", 1200, '7'},
{"Expert", 1300, '8'},
{"Professional",1400, '9'},
{"Accomplished",1500, 'A'},
{"Great", 1600, 'B'},
{"Master", 1700, 'C'},
{"High Master", 1800, 'D'},
{"Grand Master",1900, 'E'},
{"Legendary", 2000, 'U'},
{"Legendary+1", 2100, 'V'},
{"Legendary+2", 2200, 'W'},
{"Legendary+3", 2300, 'X'},
{"Legendary+4", 2400, 'Y'},
{"Legendary+5", 0, 'Z'}
};
struct SkillColumn
{
df::profession profession;
df::unit_labor labor;
df::job_skill skill;
char label[3];
bool special; // specified labor is mutually exclusive with all other special labors
};
#define NUM_COLUMNS (sizeof(columns) / sizeof(SkillColumn))
// All of the skill/labor columns we want to display. Includes profession (for color), labor, skill, and 2 character label
const SkillColumn columns[] = {
// Mining
{profession::MINER, unit_labor::MINE, job_skill::MINING, "Mi", true},
// Woodworking
{profession::WOODWORKER, unit_labor::CARPENTER, job_skill::CARPENTRY, "Ca"},
{profession::WOODWORKER, unit_labor::BOWYER, job_skill::BOWYER, "Bw"},
{profession::WOODWORKER, unit_labor::CUTWOOD, job_skill::WOODCUTTING, "WC", true},
// Stoneworking
{profession::STONEWORKER, unit_labor::MASON, job_skill::MASONRY, "Ma"},
{profession::STONEWORKER, unit_labor::DETAIL, job_skill::DETAILSTONE, "En"},
// Hunting/Related
{profession::RANGER, unit_labor::ANIMALTRAIN, job_skill::ANIMALTRAIN, "Tr"},
{profession::RANGER, unit_labor::ANIMALCARE, job_skill::ANIMALCARE, "Ca"},
{profession::RANGER, unit_labor::HUNT, job_skill::SNEAK, "Hu", true},
{profession::RANGER, unit_labor::TRAPPER, job_skill::TRAPPING, "Tr"},
{profession::RANGER, unit_labor::DISSECT_VERMIN, job_skill::DISSECT_VERMIN, "Di"},
// Healthcare
{profession::DOCTOR, unit_labor::DIAGNOSE, job_skill::DIAGNOSE, "Di"},
{profession::DOCTOR, unit_labor::SURGERY, job_skill::SURGERY, "Su"},
{profession::DOCTOR, unit_labor::BONE_SETTING, job_skill::SET_BONE, "Bo"},
{profession::DOCTOR, unit_labor::SUTURING, job_skill::SUTURE, "St"},
{profession::DOCTOR, unit_labor::DRESSING_WOUNDS, job_skill::DRESS_WOUNDS, "Dr"},
{profession::DOCTOR, unit_labor::FEED_WATER_CIVILIANS, job_skill::NONE, "Fd"},
{profession::DOCTOR, unit_labor::RECOVER_WOUNDED, job_skill::NONE, "Re"},
// Farming/Related
{profession::FARMER, unit_labor::BUTCHER, job_skill::BUTCHER, "Bu"},
{profession::FARMER, unit_labor::TANNER, job_skill::TANNER, "Ta"},
{profession::FARMER, unit_labor::PLANT, job_skill::PLANT, "Gr"},
{profession::FARMER, unit_labor::DYER, job_skill::DYER, "Dy"},
{profession::FARMER, unit_labor::SOAP_MAKER, job_skill::SOAP_MAKING, "So"},
{profession::FARMER, unit_labor::BURN_WOOD, job_skill::WOOD_BURNING, "WB"},
{profession::FARMER, unit_labor::POTASH_MAKING, job_skill::POTASH_MAKING, "Po"},
{profession::FARMER, unit_labor::LYE_MAKING, job_skill::LYE_MAKING, "Ly"},
{profession::FARMER, unit_labor::MILLER, job_skill::MILLING, "Ml"},
{profession::FARMER, unit_labor::BREWER, job_skill::BREWING, "Br"},
{profession::FARMER, unit_labor::HERBALIST, job_skill::HERBALISM, "He"},
{profession::FARMER, unit_labor::PROCESS_PLANT, job_skill::PROCESSPLANTS, "Th"},
{profession::FARMER, unit_labor::MAKE_CHEESE, job_skill::CHEESEMAKING, "Ch"},
{profession::FARMER, unit_labor::MILK, job_skill::MILK, "Mk"},
{profession::FARMER, unit_labor::SHEARER, job_skill::SHEARING, "Sh"},
{profession::FARMER, unit_labor::SPINNER, job_skill::SPINNING, "Sp"},
{profession::FARMER, unit_labor::COOK, job_skill::COOK, "Co"},
{profession::FARMER, unit_labor::PRESSING, job_skill::PRESSING, "Pr"},
{profession::FARMER, unit_labor::BEEKEEPING, job_skill::BEEKEEPING, "Be"},
// Fishing/Related
{profession::FISHERMAN, unit_labor::FISH, job_skill::FISH, "Fi"},
{profession::FISHERMAN, unit_labor::CLEAN_FISH, job_skill::PROCESSFISH, "Cl"},
{profession::FISHERMAN, unit_labor::DISSECT_FISH, job_skill::DISSECT_FISH, "Di"},
// Metalsmithing
{profession::METALSMITH, unit_labor::SMELT, job_skill::SMELT, "Fu"},
{profession::METALSMITH, unit_labor::FORGE_WEAPON, job_skill::FORGE_WEAPON, "We"},
{profession::METALSMITH, unit_labor::FORGE_ARMOR, job_skill::FORGE_ARMOR, "Ar"},
{profession::METALSMITH, unit_labor::FORGE_FURNITURE, job_skill::FORGE_FURNITURE, "Bl"},
{profession::METALSMITH, unit_labor::METAL_CRAFT, job_skill::METALCRAFT, "Cr"},
// Jewelry
{profession::JEWELER, unit_labor::CUT_GEM, job_skill::CUTGEM, "Cu"},
{profession::JEWELER, unit_labor::ENCRUST_GEM, job_skill::ENCRUSTGEM, "Se"},
// Crafts
{profession::CRAFTSMAN, unit_labor::LEATHER, job_skill::LEATHERWORK, "Le"},
{profession::CRAFTSMAN, unit_labor::WOOD_CRAFT, job_skill::WOODCRAFT, "Wo"},
{profession::CRAFTSMAN, unit_labor::STONE_CRAFT, job_skill::STONECRAFT, "St"},
{profession::CRAFTSMAN, unit_labor::BONE_CARVE, job_skill::BONECARVE, "Bo"},
{profession::CRAFTSMAN, unit_labor::GLASSMAKER, job_skill::GLASSMAKER, "Gl"},
{profession::CRAFTSMAN, unit_labor::WEAVER, job_skill::WEAVING, "We"},
{profession::CRAFTSMAN, unit_labor::CLOTHESMAKER, job_skill::CLOTHESMAKING, "Cl"},
{profession::CRAFTSMAN, unit_labor::EXTRACT_STRAND, job_skill::EXTRACT_STRAND, "Ad"},
{profession::CRAFTSMAN, unit_labor::POTTERY, job_skill::POTTERY, "Po"},
{profession::CRAFTSMAN, unit_labor::GLAZING, job_skill::GLAZING, "Gl"},
{profession::CRAFTSMAN, unit_labor::WAX_WORKING, job_skill::WAX_WORKING, "Wx"},
// Engineering
{profession::ENGINEER, unit_labor::SIEGECRAFT, job_skill::SIEGECRAFT, "En"},
{profession::ENGINEER, unit_labor::SIEGEOPERATE, job_skill::SIEGEOPERATE, "Op"},
{profession::ENGINEER, unit_labor::MECHANIC, job_skill::MECHANICS, "Me"},
{profession::ENGINEER, unit_labor::OPERATE_PUMP, job_skill::OPERATE_PUMP, "Pu"},
// Hauling
{profession::STANDARD, unit_labor::HAUL_STONE, job_skill::NONE, "St"},
{profession::STANDARD, unit_labor::HAUL_WOOD, job_skill::NONE, "Wo"},
{profession::STANDARD, unit_labor::HAUL_ITEM, job_skill::NONE, "It"},
{profession::STANDARD, unit_labor::HAUL_BODY, job_skill::NONE, "Bu"},
{profession::STANDARD, unit_labor::HAUL_FOOD, job_skill::NONE, "Fo"},
{profession::STANDARD, unit_labor::HAUL_REFUSE, job_skill::NONE, "Re"},
{profession::STANDARD, unit_labor::HAUL_FURNITURE, job_skill::NONE, "Fu"},
{profession::STANDARD, unit_labor::HAUL_ANIMAL, job_skill::NONE, "An"},
{profession::STANDARD, unit_labor::PUSH_HAUL_VEHICLE, job_skill::NONE, "Ve"},
// Other Jobs
{profession::CHILD, unit_labor::ARCHITECT, job_skill::DESIGNBUILDING, "Ar"},
{profession::CHILD, unit_labor::ALCHEMIST, job_skill::ALCHEMY, "Al"},
{profession::CHILD, unit_labor::CLEAN, job_skill::NONE, "Cl"},
// Military
{profession::WRESTLER, unit_labor::NONE, job_skill::WRESTLING, "Wr"},
{profession::WRESTLER, unit_labor::NONE, job_skill::AXE, "Ax"},
{profession::WRESTLER, unit_labor::NONE, job_skill::SWORD, "Sw"},
{profession::WRESTLER, unit_labor::NONE, job_skill::MACE, "Mc"},
{profession::WRESTLER, unit_labor::NONE, job_skill::HAMMER, "Ha"},
{profession::WRESTLER, unit_labor::NONE, job_skill::SPEAR, "Sp"},
{profession::WRESTLER, unit_labor::NONE, job_skill::DAGGER, "Kn"},
{profession::WRESTLER, unit_labor::NONE, job_skill::CROSSBOW, "Cb"},
{profession::WRESTLER, unit_labor::NONE, job_skill::BOW, "Bo"},
{profession::WRESTLER, unit_labor::NONE, job_skill::BLOWGUN, "Bl"},
{profession::WRESTLER, unit_labor::NONE, job_skill::PIKE, "Pk"},
{profession::WRESTLER, unit_labor::NONE, job_skill::WHIP, "La"},
{profession::WRESTLER, unit_labor::NONE, job_skill::ARMOR, "Ar"},
{profession::WRESTLER, unit_labor::NONE, job_skill::SHIELD, "Sh"},
{profession::WRESTLER, unit_labor::NONE, job_skill::BITE, "Bi"},
{profession::WRESTLER, unit_labor::NONE, job_skill::GRASP_STRIKE, "Pu"},
{profession::WRESTLER, unit_labor::NONE, job_skill::STANCE_STRIKE, "Ki"},
{profession::WRESTLER, unit_labor::NONE, job_skill::DODGING, "Do"},
{profession::WRESTLER, unit_labor::NONE, job_skill::MISC_WEAPON, "Mi"},
{profession::WRESTLER, unit_labor::NONE, job_skill::MELEE_COMBAT, "Fi"},
{profession::WRESTLER, unit_labor::NONE, job_skill::RANGED_COMBAT, "Ar"},
{profession::RECRUIT, unit_labor::NONE, job_skill::LEADERSHIP, "Le"},
{profession::RECRUIT, unit_labor::NONE, job_skill::TEACHING, "Te"},
{profession::RECRUIT, unit_labor::NONE, job_skill::KNOWLEDGE_ACQUISITION, "Lr"},
{profession::RECRUIT, unit_labor::NONE, job_skill::DISCIPLINE, "Di"},
{profession::RECRUIT, unit_labor::NONE, job_skill::CONCENTRATION, "Co"},
{profession::RECRUIT, unit_labor::NONE, job_skill::SITUATIONAL_AWARENESS, "Aw"},
{profession::RECRUIT, unit_labor::NONE, job_skill::COORDINATION, "Cr"},
{profession::RECRUIT, unit_labor::NONE, job_skill::BALANCE, "Ba"},
// Social
{profession::STANDARD, unit_labor::NONE, job_skill::PERSUASION, "Pe"},
{profession::STANDARD, unit_labor::NONE, job_skill::NEGOTIATION, "Ne"},
{profession::STANDARD, unit_labor::NONE, job_skill::JUDGING_INTENT, "Ju"},
{profession::STANDARD, unit_labor::NONE, job_skill::LYING, "Ly"},
{profession::STANDARD, unit_labor::NONE, job_skill::INTIMIDATION, "In"},
{profession::STANDARD, unit_labor::NONE, job_skill::CONVERSATION, "Cn"},
{profession::STANDARD, unit_labor::NONE, job_skill::COMEDY, "Cm"},
{profession::STANDARD, unit_labor::NONE, job_skill::FLATTERY, "Fl"},
{profession::STANDARD, unit_labor::NONE, job_skill::CONSOLE, "Cs"},
{profession::STANDARD, unit_labor::NONE, job_skill::PACIFY, "Pc"},
{profession::ADMINISTRATOR, unit_labor::NONE, job_skill::APPRAISAL, "Ap"},
{profession::ADMINISTRATOR, unit_labor::NONE, job_skill::ORGANIZATION, "Or"},
{profession::ADMINISTRATOR, unit_labor::NONE, job_skill::RECORD_KEEPING, "RK"},
// Miscellaneous
{profession::STANDARD, unit_labor::NONE, job_skill::THROW, "Th"},
{profession::STANDARD, unit_labor::NONE, job_skill::CRUTCH_WALK, "CW"},
{profession::STANDARD, unit_labor::NONE, job_skill::SWIMMING, "Sw"},
{profession::STANDARD, unit_labor::NONE, job_skill::KNAPPING, "Kn"},
{profession::DRUNK, unit_labor::NONE, job_skill::WRITING, "Wr"},
{profession::DRUNK, unit_labor::NONE, job_skill::PROSE, "Pr"},
{profession::DRUNK, unit_labor::NONE, job_skill::POETRY, "Po"},
{profession::DRUNK, unit_labor::NONE, job_skill::READING, "Rd"},
{profession::DRUNK, unit_labor::NONE, job_skill::SPEAKING, "Sp"},
{profession::ADMINISTRATOR, unit_labor::NONE, job_skill::MILITARY_TACTICS, "MT"},
{profession::ADMINISTRATOR, unit_labor::NONE, job_skill::TRACKING, "Tr"},
{profession::ADMINISTRATOR, unit_labor::NONE, job_skill::MAGIC_NATURE, "Dr"},
};
struct UnitInfo
{
df::unit *unit;
bool allowEdit;
string name;
string transname;
string profession;
int8_t color;
};
#define FILTER_NONWORKERS 0x0001
#define FILTER_NONDWARVES 0x0002
#define FILTER_NONCIV 0x0004
#define FILTER_ANIMALS 0x0008
#define FILTER_LIVING 0x0010
#define FILTER_DEAD 0x0020
class viewscreen_unitlaborsst : public dfhack_viewscreen {
public:
static viewscreen_unitlaborsst *create (char pushtype, df::viewscreen *scr = NULL);
void feed(set<df::interface_key> *events);
void render();
void resize(int w, int h) { calcSize(); }
void help() { }
std::string getFocusString() { return "unitlabors"; }
viewscreen_unitlaborsst();
~viewscreen_unitlaborsst() { };
protected:
vector<UnitInfo *> units;
int filter;
int first_row, sel_row;
int first_column, sel_column;
int height, name_width, prof_width, labors_width;
// bool descending;
// int sort_skill;
// int sort_labor;
void readUnits ();
void calcSize ();
};
viewscreen_unitlaborsst::viewscreen_unitlaborsst()
{
filter = FILTER_LIVING;
first_row = sel_row = 0;
first_column = sel_column = 0;
calcSize();
readUnits();
}
void viewscreen_unitlaborsst::readUnits ()
{
for (size_t i = 0; i < units.size(); i++)
delete units[i];
units.clear();
UnitInfo *cur = new UnitInfo;
for (size_t i = 0; i < world->units.active.size(); i++)
{
df::unit *unit = world->units.active[i];
cur->unit = unit;
cur->allowEdit = true;
if (unit->race != ui->race_id)
{
cur->allowEdit = false;
if (!(filter & FILTER_NONDWARVES))
continue;
}
if (unit->civ_id != ui->civ_id)
{
cur->allowEdit = false;
if (!(filter & FILTER_NONCIV))
continue;
}
if (unit->flags1.bits.dead)
{
cur->allowEdit = false;
if (!(filter & FILTER_DEAD))
continue;
}
else
{
if (!(filter & FILTER_LIVING))
continue;
}
if (!ENUM_ATTR(profession, can_assign_labor, unit->profession))
{
cur->allowEdit = false;
if (!(filter & FILTER_NONWORKERS))
continue;
}
if (!unit->name.first_name.length())
{
if (!(filter & FILTER_ANIMALS))
continue;
}
cur->name = Translation::TranslateName(&unit->name, false);
cur->transname = Translation::TranslateName(&unit->name, true);
cur->profession = Units::getProfessionName(unit);
cur->color = Units::getProfessionColor(unit);
units.push_back(cur);
cur = new UnitInfo;
}
delete cur;
}
void viewscreen_unitlaborsst::calcSize()
{
height = gps->dimy - 10;
if (height > units.size())
height = units.size();
name_width = prof_width = labors_width = 0;
for (int i = 4; i < gps->dimx; i++)
{
// 20% for Name, 20% for Profession, 60% for Labors
switch ((i - 4) % 5)
{
case 0: case 2: case 4:
labors_width++;
break;
case 1:
name_width++;
break;
case 3:
prof_width++;
break;
}
}
while (labors_width > NUM_COLUMNS)
{
if (labors_width & 1)
name_width++;
else
prof_width++;
labors_width--;
}
// don't adjust scroll position immediately after the window opened
if (units.size() == 0)
return;
// if the window grows vertically, scroll upward to eliminate blank rows from the bottom
if (first_row > units.size() - height)
first_row = units.size() - height;
// if it shrinks vertically, scroll downward to keep the cursor visible
if (first_row < sel_row - height + 1)
first_row = sel_row - height + 1;
// if the window grows horizontally, scroll to the left to eliminate blank columns from the right
if (first_column > NUM_COLUMNS - labors_width)
first_column = NUM_COLUMNS - labors_width;
// if it shrinks horizontally, scroll to the right to keep the cursor visible
if (first_column < sel_column - labors_width + 1)
first_column = sel_column - labors_width + 1;
}
void viewscreen_unitlaborsst::feed(set<df::interface_key> *events)
{
if (events->count(interface_key::LEAVESCREEN))
{
events->clear();
Screen::dismiss(this);
return;
}
// TODO - allow modifying filters
if (!units.size())
return;
if (events->count(interface_key::CURSOR_UP) || events->count(interface_key::CURSOR_UPLEFT) || events->count(interface_key::CURSOR_UPRIGHT))
sel_row--;
if (events->count(interface_key::CURSOR_UP_FAST) || events->count(interface_key::CURSOR_UPLEFT_FAST) || events->count(interface_key::CURSOR_UPRIGHT_FAST))
sel_row -= 10;
if (events->count(interface_key::CURSOR_DOWN) || events->count(interface_key::CURSOR_DOWNLEFT) || events->count(interface_key::CURSOR_DOWNRIGHT))
sel_row++;
if (events->count(interface_key::CURSOR_DOWN_FAST) || events->count(interface_key::CURSOR_DOWNLEFT_FAST) || events->count(interface_key::CURSOR_DOWNRIGHT_FAST))
sel_row += 10;
if (sel_row < 0)
sel_row = 0;
if (sel_row > units.size() - 1)
sel_row = units.size() - 1;
if (sel_row < first_row)
first_row = sel_row;
if (first_row < sel_row - height + 1)
first_row = sel_row - height + 1;
if (events->count(interface_key::CURSOR_LEFT) || events->count(interface_key::CURSOR_UPLEFT) || events->count(interface_key::CURSOR_DOWNLEFT))
sel_column--;
if (events->count(interface_key::CURSOR_LEFT_FAST) || events->count(interface_key::CURSOR_UPLEFT_FAST) || events->count(interface_key::CURSOR_DOWNLEFT_FAST))
sel_column -= 10;
if (events->count(interface_key::CURSOR_RIGHT) || events->count(interface_key::CURSOR_UPRIGHT) || events->count(interface_key::CURSOR_DOWNRIGHT))
sel_column++;
if (events->count(interface_key::CURSOR_RIGHT_FAST) || events->count(interface_key::CURSOR_UPRIGHT_FAST) || events->count(interface_key::CURSOR_DOWNRIGHT_FAST))
sel_column += 10;
if ((sel_column != 0) && events->count(interface_key::CURSOR_UP_Z))
{
// go to beginning of current column group; if already at the beginning, go to the beginning of the previous one
sel_column--;
df::profession cur = columns[sel_column].profession;
while ((sel_column > 0) && columns[sel_column - 1].profession == cur)
sel_column--;
}
if ((sel_column != NUM_COLUMNS - 1) && events->count(interface_key::CURSOR_DOWN_Z))
{
// go to end of current column group; if already at the end, go to the end of the next one
sel_column++;
df::profession cur = columns[sel_column].profession;
while ((sel_column < NUM_COLUMNS - 1) && columns[sel_column + 1].profession == cur)
sel_column++;
}
if (sel_column < 0)
sel_column = 0;
if (sel_column > NUM_COLUMNS - 1)
sel_column = NUM_COLUMNS - 1;
if (sel_column < first_column)
first_column = sel_column;
if (first_column < sel_column - labors_width + 1)
first_column = sel_column - labors_width + 1;
UnitInfo *cur = units[sel_row];
if (events->count(interface_key::SELECT) && (cur->allowEdit) && (columns[sel_column].labor != unit_labor::NONE))
{
df::unit *unit = cur->unit;
const SkillColumn &col = columns[sel_column];
if (col.special)
{
if (!unit->status.labors[col.labor])
{
for (int i = 0; i < NUM_COLUMNS; i++)
{
if ((columns[i].labor != unit_labor::NONE) && columns[i].special)
unit->status.labors[columns[i].labor] = false;
}
}
unit->military.pickup_flags.bits.update = true;
}
unit->status.labors[col.labor] = !unit->status.labors[col.labor];
}
// TODO: add sorting
}
void viewscreen_unitlaborsst::render()
{
if (Screen::isDismissed(this))
return;
dfhack_viewscreen::render();
Screen::clear();
Screen::drawBorder(" Manage Labors ");
for (int col = 0; col < labors_width; col++)
{
int col_offset = col + first_column;
if (col_offset >= NUM_COLUMNS)
break;
int8_t fg = Units::getCasteProfessionColor(ui->race_id, -1, columns[col_offset].profession);
int8_t bg = 0;
if (col_offset == sel_column)
{
fg = 0;
bg = 7;
}
Screen::paintTile(Screen::Pen(columns[col_offset].label[0], fg, bg), 1 + name_width + 1 + prof_width + 1 + col, 1);
Screen::paintTile(Screen::Pen(columns[col_offset].label[1], fg, bg), 1 + name_width + 1 + prof_width + 1 + col, 2);
}
for (int row = 0; row < height; row++)
{
int row_offset = row + first_row;
if (row_offset >= units.size())
break;
UnitInfo *cur = units[row_offset];
df::unit *unit = cur->unit;
int8_t fg = 15, bg = 0;
if (row_offset == sel_row)
{
fg = 0;
bg = 7;
}
string name = cur->name;
name.resize(name_width);
Screen::paintString(Screen::Pen(' ', fg, bg), 1, 3 + row, name);
string profession = cur->profession;
profession.resize(prof_width);
fg = cur->color;
bg = 0;
Screen::paintString(Screen::Pen(' ', fg, bg), 1 + prof_width + 1, 3 + row, profession);
// Print unit's skills and labor assignments
for (int col = 0; col < labors_width; col++)
{
int col_offset = col + first_column;
fg = 15;
bg = 0;
if ((col_offset == sel_column) && (row_offset == sel_row))
fg = 9;
if ((columns[col_offset].labor != unit_labor::NONE) && (unit->status.labors[columns[col_offset].labor]))
bg = 7;
char c = '-';
if (columns[col_offset].skill != job_skill::NONE)
{
df::unit_skill *skill = binsearch_in_vector<df::unit_skill,df::enum_field<df::job_skill,int16_t>>(unit->status.current_soul->skills, &df::unit_skill::id, columns[col_offset].skill);
if ((skill != NULL) && (skill->rating || skill->experience))
{
int level = skill->rating;
if (level > NUM_SKILL_LEVELS - 1)
level = NUM_SKILL_LEVELS - 1;
c = skill_levels[level].abbrev;
}
}
Screen::paintTile(Screen::Pen(c, fg, bg), 1 + name_width + 1 + prof_width + 1 + col, 3 + row);
}
}
UnitInfo *cur = units[sel_row];
if (cur != NULL)
{
df::unit *unit = cur->unit;
string str = cur->transname;
if (str.length())
str += ", ";
str += cur->profession;
str += ":";
Screen::paintString(Screen::Pen(' ', 15, 0), 1, 3 + height + 2, str);
int y = 1 + str.length() + 1;
if (columns[sel_column].skill == job_skill::NONE)
{
str = ENUM_ATTR_STR(unit_labor, caption, columns[sel_column].labor);
if (unit->status.labors[columns[sel_column].labor])
str += " Enabled";
else
str += " Not Enabled";
Screen::paintString(Screen::Pen(' ', 9, 0), y, 3 + height + 2, str);
}
else
{
df::unit_skill *skill = binsearch_in_vector<df::unit_skill,df::enum_field<df::job_skill,int16_t>>(unit->status.current_soul->skills, &df::unit_skill::id, columns[sel_column].skill);
if (skill)
{
int level = skill->rating;
if (level > NUM_SKILL_LEVELS - 1)
level = NUM_SKILL_LEVELS - 1;
str = stl_sprintf("%s %s", skill_levels[level].name, ENUM_ATTR_STR(job_skill, caption_noun, columns[sel_column].skill));
if (level != NUM_SKILL_LEVELS - 1)
str += stl_sprintf(" (%d/%d)", skill->experience, skill_levels[level].points);
}
else
str = stl_sprintf("Not %s (0/500)", ENUM_ATTR_STR(job_skill, caption_noun, columns[sel_column].skill));
Screen::paintString(Screen::Pen(' ', 9, 0), y, 3 + height + 2, str);
}
}
// TODO - print command help info
}
struct unitlist_hook : df::viewscreen_unitlistst
{
typedef df::viewscreen_unitlistst interpose_base;
DEFINE_VMETHOD_INTERPOSE(void, feed, (set<df::interface_key> *input))
{
if (input->count(interface_key::UNITVIEW_PRF_PROF))
{
Screen::dismiss(this);
Screen::show(new viewscreen_unitlaborsst());
return;
}
INTERPOSE_NEXT(feed)(input);
}
};
IMPLEMENT_VMETHOD_INTERPOSE(unitlist_hook, feed);
DFhackCExport command_result plugin_init ( color_ostream &out, vector <PluginCommand> &commands)
{
if (gps)
{
if (!INTERPOSE_HOOK(unitlist_hook, feed).apply())
out.printerr("Could not interpose viewscreen_unitlistst::feed\n");
}
return CR_OK;
}
DFhackCExport command_result plugin_shutdown ( color_ostream &out )
{
INTERPOSE_HOOK(unitlist_hook, feed).remove();
return CR_OK;
}

@ -43,7 +43,6 @@ using std::string;
using std::endl;
using namespace DFHack;
using namespace df::enums;
using namespace df::enums::item_quality;
using df::global::world;
using df::global::ui;
@ -285,7 +284,7 @@ struct ItemConstraint {
int weight;
std::vector<ProtectedJob*> jobs;
enum item_quality min_quality;
item_quality::item_quality min_quality;
int item_amount, item_count, item_inuse;
bool request_suspend, request_resume;
@ -296,8 +295,8 @@ struct ItemConstraint {
public:
ItemConstraint()
: is_craft(false), weight(0), item_amount(0), item_count(0), item_inuse(0)
, is_active(false), cant_resume_reported(false), min_quality(Ordinary)
: is_craft(false), weight(0), min_quality(item_quality::Ordinary),item_amount(0),
item_count(0), item_inuse(0), is_active(false), cant_resume_reported(false)
{}
int goalCount() { return config.ival(0); }
@ -685,15 +684,15 @@ static ItemConstraint *get_constraint(color_ostream &out, const std::string &str
return NULL;
}
enum item_quality minqual = Ordinary;
item_quality::item_quality minqual = item_quality::Ordinary;
std::string qualstr = vector_get(tokens, 3);
if(!qualstr.empty()) {
if(qualstr == "ordinary") minqual = Ordinary;
else if(qualstr == "wellcrafted") minqual = WellCrafted;
else if(qualstr == "finelycrafted") minqual = FinelyCrafted;
else if(qualstr == "superior") minqual = Superior;
else if(qualstr == "exceptional") minqual = Exceptional;
else if(qualstr == "masterful") minqual = Masterful;
if(qualstr == "ordinary") minqual = item_quality::Ordinary;
else if(qualstr == "wellcrafted") minqual = item_quality::WellCrafted;
else if(qualstr == "finelycrafted") minqual = item_quality::FinelyCrafted;
else if(qualstr == "superior") minqual = item_quality::Superior;
else if(qualstr == "exceptional") minqual = item_quality::Exceptional;
else if(qualstr == "masterful") minqual = item_quality::Masterful;
else {
out.printerr("Cannot find quality: %s\nKnown qualities: ordinary, wellcrafted, finelycrafted, superior, exceptional, masterful\n", qualstr.c_str());
return NULL;
@ -1381,15 +1380,15 @@ static void print_constraint(color_ostream &out, ItemConstraint *cv, bool no_job
{
Console::color_value color;
if (cv->request_resume)
color = Console::COLOR_GREEN;
color = COLOR_GREEN;
else if (cv->request_suspend)
color = Console::COLOR_CYAN;
color = COLOR_CYAN;
else
color = Console::COLOR_DARKGREY;
color = COLOR_DARKGREY;
out.color(color);
out << prefix << "Constraint " << flush;
out.color(Console::COLOR_GREY);
out.color(COLOR_GREY);
out << cv->config.val() << " " << flush;
out.color(color);
out << (cv->goalByCount() ? "count " : "amount ")
@ -1438,18 +1437,18 @@ static void print_constraint(color_ostream &out, ItemConstraint *cv, bool no_job
{
if (pj->want_resumed)
{
out.color(Console::COLOR_YELLOW);
out.color(COLOR_YELLOW);
out << start << " (delayed)" << endl;
}
else
{
out.color(Console::COLOR_BLUE);
out.color(COLOR_BLUE);
out << start << " (suspended)" << endl;
}
}
else
{
out.color(Console::COLOR_GREEN);
out.color(COLOR_GREEN);
out << start << endl;
}
@ -1473,11 +1472,11 @@ static void print_job(color_ostream &out, ProtectedJob *pj)
isOptionEnabled(CF_AUTOMELT))
{
if (meltable_count <= 0)
out.color(Console::COLOR_CYAN);
out.color(COLOR_CYAN);
else if (pj->want_resumed && !pj->isActuallyResumed())
out.color(Console::COLOR_YELLOW);
out.color(COLOR_YELLOW);
else
out.color(Console::COLOR_GREEN);
out.color(COLOR_GREEN);
out << " Meltable: " << meltable_count << " objects." << endl;
out.reset_color();
}
@ -1504,13 +1503,14 @@ static command_result workflow_cmd(color_ostream &out, vector <string> & paramet
}
df::building *workshop = NULL;
df::job *job = NULL;
//FIXME: unused variable!
//df::job *job = NULL;
if (Gui::dwarfmode_hotkey(Core::getTopViewscreen()) &&
ui->main.mode == ui_sidebar_mode::QueryBuilding)
{
workshop = world->selected_building;
job = Gui::getSelectedWorkshopJob(out, true);
//job = Gui::getSelectedWorkshopJob(out, true);
}
std::string cmd = parameters.empty() ? "list" : parameters[0];

@ -0,0 +1,22 @@
-- Test lua viewscreens.
local gui = require 'gui'
local text = 'Woohoo, lua viewscreen :)'
local screen = mkinstance(gui.FramedScreen, {
frame_style = gui.GREY_LINE_FRAME,
frame_title = 'Hello World',
frame_width = #text+6,
frame_height = 3,
onRenderBody = function(self, dc)
dc:seek(3,1):string(text, COLOR_LIGHTGREEN)
end,
onInput = function(self,keys)
if keys.LEAVESCREEN or keys.SELECT then
self:dismiss()
end
end
})
screen:show()

@ -0,0 +1,154 @@
-- Shows mechanisms linked to the current building.
local utils = require 'utils'
local gui = require 'gui'
local guidm = require 'gui.dwarfmode'
function getBuildingName(building)
return utils.call_with_string(building, 'getName')
end
function getBuildingCenter(building)
return xyz2pos(building.centerx, building.centery, building.z)
end
function listMechanismLinks(building)
local lst = {}
local function push(item, mode)
if item then
lst[#lst+1] = {
obj = item, mode = mode,
name = getBuildingName(item),
center = getBuildingCenter(item)
}
end
end
push(building, 'self')
if not df.building_actual:is_instance(building) then
return lst
end
local item, tref, tgt
for _,v in ipairs(building.contained_items) do
item = v.item
if df.item_trappartsst:is_instance(item) then
tref = dfhack.items.getGeneralRef(item, df.general_ref_type.BUILDING_TRIGGER)
if tref then
push(tref:getBuilding(), 'trigger')
end
tref = dfhack.items.getGeneralRef(item, df.general_ref_type.BUILDING_TRIGGERTARGET)
if tref then
push(tref:getBuilding(), 'target')
end
end
end
return lst
end
MechanismList = defclass(MechanismList, guidm.MenuOverlay)
MechanismList.focus_path = 'mechanisms'
function MechanismList.new(building)
local self = {
links = {},
selected = 1
}
return mkinstance(MechanismList, self):init(building)
end
function MechanismList:init(building)
local links = listMechanismLinks(building)
links[1].viewport = self:getViewport()
links[1].cursor = guidm.getCursorPos()
if #links <= 1 then
links[1].mode = 'none'
end
self.links = links
self.selected = 1
return self
end
local colors = {
self = COLOR_CYAN, none = COLOR_CYAN,
trigger = COLOR_GREEN, target = COLOR_GREEN
}
local icons = {
self = 128, none = 63, trigger = 27, target = 26
}
function MechanismList:onRenderBody(dc)
dc:clear()
dc:seek(1,1):string("Mechanism Links", COLOR_WHITE):newline()
for i,v in ipairs(self.links) do
local pen = { fg=colors[v.mode], bold = (i == self.selected) }
dc:newline(1):pen(pen):char(icons[v.mode])
dc:advance(1):string(v.name)
end
local nlinks = #self.links
if nlinks <= 1 then
dc:newline():newline(1):string("This building has no links", COLOR_LIGHTRED)
end
dc:newline():newline(1):pen(COLOR_WHITE)
dc:string("Esc", COLOR_LIGHTGREEN):string(": Back, ")
dc:string("Enter", COLOR_LIGHTGREEN):string(": Switch")
end
function MechanismList:zoomToLink(link,back)
df.global.world.selected_building = link.obj
if back then
guidm.setCursorPos(link.cursor)
self:getViewport(link.viewport):set()
else
guidm.setCursorPos(link.center)
self:getViewport():reveal(link.center, 5, 0, 10):set()
end
end
function MechanismList:changeSelected(delta)
if #self.links <= 1 then return end
self.selected = 1 + (self.selected + delta - 1) % #self.links
self:zoomToLink(self.links[self.selected])
end
function MechanismList:onInput(keys)
if keys.SECONDSCROLL_UP then
self:changeSelected(-1)
elseif keys.SECONDSCROLL_DOWN then
self:changeSelected(1)
elseif keys.LEAVESCREEN then
self:dismiss()
if self.selected ~= 1 then
self:zoomToLink(self.links[1], true)
end
elseif keys.SELECT_ALL then
if self.selected > 1 then
self:init(self.links[self.selected].obj)
end
elseif keys.SELECT then
self:dismiss()
elseif self:simulateViewScroll(keys) then
return
end
end
if not df.viewscreen_dwarfmodest:is_instance(dfhack.gui.getCurViewscreen()) then
qerror("This script requires the main dwarfmode view")
end
if df.global.ui.main.mode ~= df.ui_sidebar_mode.QueryBuilding then
qerror("This script requires the 'q' interface mode")
end
local list = MechanismList.new(df.global.world.selected_building)
list:show()
list:changeSelected(1)